Projet

Général

Profil

Paste
Télécharger (26,2 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / rules / includes / rules.plugins.inc @ 950416da

1
<?php
2

    
3
/**
4
 * @file
5
 * Contains plugin info and implementations not needed for rule evaluation.
6
 */
7

    
8
/**
9
 * Implements a rules action.
10
 */
11
class RulesAction extends RulesAbstractPlugin implements RulesActionInterface {
12

    
13
  /**
14
   * @var string
15
   */
16
  protected $itemName = 'action';
17

    
18
  /**
19
   * Execute the callback and update/save data as specified by the action.
20
   */
21
  protected function executeCallback(array $args, RulesState $state = NULL) {
22
    rules_log('Evaluating the action %name.', array('%name' => $this->elementName), RulesLog::INFO, $this);
23
    $return = $this->__call('execute', empty($this->info['named parameter']) ? $args : array($args));
24
    // Get the (partially) wrapped arguments.
25
    $args = $state->currentArguments;
26

    
27
    if (is_array($return)) {
28
      foreach ($return as $name => $data) {
29
        // Add provided variables.
30
        if (isset($this->info['provides'][$name])) {
31
          $var_name = isset($this->settings[$name . ':var']) ? $this->settings[$name . ':var'] : $name;
32
          if (!$state->varInfo($var_name)) {
33
            $state->addVariable($var_name, $data, $this->info['provides'][$name]);
34
            rules_log('Added the provided variable %name of type %type', array('%name' => $var_name, '%type' => $this->info['provides'][$name]['type']), RulesLog::INFO, $this);
35
            if (!empty($this->info['provides'][$name]['save']) && $state->variables[$var_name] instanceof EntityMetadataWrapper) {
36
              $state->saveChanges($var_name, $state->variables[$var_name]);
37
            }
38
          }
39
        }
40
        // Support updating variables by returning the values.
41
        elseif (!isset($this->info['provides'][$name])) {
42
          // Update the data value using the wrapper.
43
          if (isset($args[$name]) && $args[$name] instanceof EntityMetadataWrapper) {
44
            try {
45
              $args[$name]->set($data);
46
            }
47
            catch (EntityMetadataWrapperException $e) {
48
              throw new RulesEvaluationException('Unable to update the argument for parameter %name: %error', array('%name' => $name, '%error' => $e->getMessage()), $this);
49
            }
50
          }
51
          elseif (array_key_exists($name, $args)) {
52
            // Map back to the source variable name and update it.
53
            $var_name = !empty($this->settings[$name . ':select']) ? str_replace('-', '_', $this->settings[$name . ':select']) : $name;
54
            $state->variables[$var_name] = $data;
55
          }
56
        }
57
      }
58
    }
59
    // Save parameters as defined in the parameter info.
60
    if ($return !== FALSE) {
61
      foreach ($this->info['parameter'] as $name => $info) {
62
        if (!empty($info['save']) && $args[$name] instanceof EntityMetadataWrapper) {
63
          if (isset($this->settings[$name . ':select'])) {
64
            $state->saveChanges($this->settings[$name . ':select'], $args[$name]);
65
          }
66
          else {
67
            // Wrapper has been configured via direct input, so just save.
68
            rules_log('Saved argument of type %type for parameter %name.', array('%name' => $name, '%type' => $args[$name]->type()));
69
            $args[$name]->save();
70
          }
71
        }
72
      }
73
    }
74
  }
75

    
76
}
77

    
78
/**
79
 * Implements a rules condition.
80
 */
81
class RulesCondition extends RulesAbstractPlugin implements RulesConditionInterface {
82

    
83
  /**
84
   * @var string
85
   */
86
  protected $itemName = 'condition';
87

    
88
  /**
89
   * @var bool
90
   */
91
  protected $negate = FALSE;
92

    
93
  public function providesVariables() {
94
    return array();
95
  }
96

    
97
  public function negate($negate = TRUE) {
98
    $this->negate = (bool) $negate;
99
    return $this;
100
  }
101

    
102
  public function isNegated() {
103
    return $this->negate;
104
  }
105

    
106
  protected function executeCallback(array $args, RulesState $state = NULL) {
107
    $return = (bool) $this->__call('execute', empty($this->info['named parameter']) ? $args : array($args));
108
    rules_log('The condition %name evaluated to %bool', array('%name' => $this->elementName, '%bool' => $return ? 'TRUE' : 'FALSE'), RulesLog::INFO, $this);
109
    return $this->negate ? !$return : $return;
110
  }
111

    
112
  public function __sleep() {
113
    return parent::__sleep() + array('negate' => 'negate');
114
  }
115

    
116
  /**
117
   * Just return the boolean result.
118
   */
119
  protected function returnVariables(RulesState $state, $result = NULL) {
120
    return $result;
121
  }
122

    
123
  protected function exportToArray() {
124
    $not = $this->negate ? 'NOT ' : '';
125
    $export = $this->exportSettings();
126
    // Abbreviate the export making "USING" implicit.
127
    return array($not . $this->elementName => isset($export['USING']) ? $export['USING'] : array());
128
  }
129

    
130
  public function import(array $export) {
131
    $this->elementName = rules_array_key($export);
132
    if (strpos($this->elementName, 'NOT ') === 0) {
133
      $this->elementName = substr($this->elementName, 4);
134
      $this->negate = TRUE;
135
    }
136
    // After setting the element name, setup the element again so the right
137
    // element info is loaded.
138
    $this->setUp();
139

    
140
    // Re-add 'USING' which has been removed for abbreviation.
141
    $this->importSettings(array('USING' => reset($export)));
142
  }
143

    
144
  public function label() {
145
    $label = parent::label();
146
    return $this->negate ? t('NOT !condition', array('!condition' => $label)) : $label;
147
  }
148

    
149
}
150

    
151
/**
152
 * An actual rule.
153
 *
154
 * Note: A rule also implements the RulesActionInterface (inherited).
155
 */
156
class Rule extends RulesActionContainer {
157

    
158
  protected $conditions = NULL;
159

    
160
  /**
161
   * @var string
162
   */
163
  protected $itemName = 'rule';
164

    
165
  /**
166
   * @var string
167
   */
168
  public $label = 'unlabeled';
169

    
170
  public function __construct($variables = array(), $providesVars = array()) {
171
    parent::__construct($variables, $providesVars);
172

    
173
    // Initialize the conditions container.
174
    if (!isset($this->conditions)) {
175
      $this->conditions = rules_and();
176
      // Don't use setParent() to avoid having it added to the children.
177
      $this->conditions->parent = $this;
178
    }
179
  }
180

    
181
  /**
182
   * Gets an iterator over all contained conditions.
183
   *
184
   * Note that this iterator also implements the ArrayAccess interface.
185
   *
186
   * @return RulesRecursiveElementIterator
187
   */
188
  public function conditions() {
189
    return $this->conditions->getIterator();
190
  }
191

    
192
  /**
193
   * Returns the "And" condition container, which contains all conditions of
194
   * this rule.
195
   *
196
   * @return RulesAnd
197
   */
198
  public function conditionContainer() {
199
    return $this->conditions;
200
  }
201

    
202
  public function __sleep() {
203
    return parent::__sleep() + drupal_map_assoc(array('conditions', 'label'));
204
  }
205

    
206
  /**
207
   * Gets an iterator over all contained actions.
208
   *
209
   * Note that this iterator also implements the ArrayAccess interface.
210
   *
211
   * @return RulesRecursiveElementIterator
212
   */
213
  public function actions() {
214
    return parent::getIterator();
215
  }
216

    
217
  /**
218
   * Adds a condition.
219
   *
220
   * Pass either an instance of the RulesConditionInterface or the arguments as
221
   * needed by rules_condition().
222
   *
223
   * @return $this
224
   */
225
  public function condition($name, $settings = array()) {
226
    $this->conditions->condition($name, $settings);
227
    return $this;
228
  }
229

    
230
  public function sortChildren($deep = FALSE) {
231
    $this->conditions->sortChildren($deep);
232
    parent::sortChildren($deep);
233
  }
234

    
235
  public function evaluate(RulesState $state) {
236
    rules_log('Evaluating conditions of rule %label.', array('%label' => $this->label), RulesLog::INFO, $this);
237
    if ($this->conditions->evaluate($state)) {
238
      rules_log('Rule %label fires.', array('%label' => $this->label), RulesLog::INFO, $this, TRUE);
239
      parent::evaluate($state);
240
      rules_log('Rule %label has fired.', array('%label' => $this->label), RulesLog::INFO, $this, FALSE);
241
    }
242
  }
243

    
244
  /**
245
   * Fires the rule, i.e. evaluates the rule without checking its conditions.
246
   *
247
   * @see RulesPlugin::evaluate()
248
   */
249
  public function fire(RulesState $state) {
250
    rules_log('Firing rule %label.', array('%label' => $this->label), RulesLog::INFO, $this);
251
    parent::evaluate($state);
252
  }
253

    
254
  public function integrityCheck() {
255
    parent::integrityCheck();
256
    $this->conditions->integrityCheck();
257
    return $this;
258
  }
259

    
260
  public function access() {
261
    return (!isset($this->conditions) || $this->conditions->access()) && parent::access();
262
  }
263

    
264
  public function dependencies() {
265
    return array_keys(array_flip($this->conditions->dependencies()) + array_flip(parent::dependencies()));
266
  }
267

    
268
  public function destroy() {
269
    $this->conditions->destroy();
270
    parent::destroy();
271
  }
272

    
273
  /**
274
   * @return RulesRecursiveElementIterator
275
   */
276
  public function getIterator() {
277
    $array = array_merge(array($this->conditions), $this->children);
278
    return new RulesRecursiveElementIterator($array);
279
  }
280

    
281
  protected function stateVariables($element = NULL) {
282
    // Don't add in provided action variables for the conditions.
283
    if (isset($element) && $element === $this->conditions) {
284
      return $this->availableVariables();
285
    }
286
    $vars = parent::stateVariables($element);
287
    // Take variable info assertions of conditions into account.
288
    if ($assertions = $this->conditions->variableInfoAssertions()) {
289
      $vars = RulesData::addMetadataAssertions($vars, $assertions);
290
    }
291
    return $vars;
292
  }
293

    
294
  protected function exportFlat() {
295
    return $this->isRoot();
296
  }
297

    
298
  protected function exportToArray() {
299
    $export = parent::exportToArray();
300
    if (!$this->isRoot()) {
301
      $export[strtoupper($this->plugin())]['LABEL'] = $this->label;
302
    }
303
    return $export;
304
  }
305

    
306
  protected function exportChildren($key = NULL) {
307
    $export = array();
308
    if ($this->conditions->children) {
309
      $export = $this->conditions->exportChildren('IF');
310
    }
311
    return $export + parent::exportChildren('DO');
312
  }
313

    
314
  public function import(array $export) {
315
    if (!$this->isRoot() && isset($export[strtoupper($this->plugin())]['LABEL'])) {
316
      $this->label = $export[strtoupper($this->plugin())]['LABEL'];
317
    }
318
    parent::import($export);
319
  }
320

    
321
  protected function importChildren($export, $key = NULL) {
322
    if (!empty($export['IF'])) {
323
      $this->conditions->importChildren($export, 'IF');
324
    }
325
    parent::importChildren($export, 'DO');
326
  }
327

    
328
  public function __clone() {
329
    parent::__clone();
330
    $this->conditions = clone $this->conditions;
331
    $this->conditions->parent = $this;
332
  }
333

    
334
  /**
335
   * Overrides RulesPlugin::variableInfoAssertions().
336
   *
337
   * Rules may not provide any variable info assertions, as Rules are only
338
   * conditionally executed.
339
   */
340
  protected function variableInfoAssertions() {
341
    return array();
342
  }
343

    
344
  /**
345
   * Overridden to ensure the whole Rule is deleted at once.
346
   */
347
  public function delete($keep_children = FALSE) {
348
    parent::delete($keep_children);
349
  }
350

    
351
  /**
352
   * Overridden to expose the variables of all actions for embedded rules.
353
   */
354
  public function providesVariables() {
355
    $provides = parent::providesVariables();
356
    if (!$this->isRoot()) {
357
      foreach ($this->actions() as $action) {
358
        $provides += $action->providesVariables();
359
      }
360
    }
361
    return $provides;
362
  }
363

    
364
  public function resetInternalCache() {
365
    parent::resetInternalCache();
366
    $this->conditions->resetInternalCache();
367
  }
368

    
369
}
370

    
371
/**
372
 * Represents rules getting triggered by events.
373
 */
374
class RulesReactionRule extends Rule implements RulesTriggerableInterface {
375

    
376
  /**
377
   * @var string
378
   */
379
  protected $itemName = 'reaction rule';
380

    
381
  /**
382
   * @var array
383
   */
384
  protected $events = array();
385

    
386
  /**
387
   * @var array
388
   */
389
  protected $eventSettings = array();
390

    
391
  /**
392
   * Implements RulesTriggerableInterface::events().
393
   */
394
  public function events() {
395
    return $this->events;
396
  }
397

    
398
  /**
399
   * Implements RulesTriggerableInterface::removeEvent().
400
   */
401
  public function removeEvent($event) {
402
    if (($id = array_search($event, $this->events)) !== FALSE) {
403
      unset($this->events[$id]);
404
    }
405
    return $this;
406
  }
407

    
408
  /**
409
   * Implements RulesTriggerableInterface::event().
410
   */
411
  public function event($event_name, array $settings = NULL) {
412
    // Process any settings and determine the configured event's name.
413
    if ($settings) {
414
      $handler = rules_get_event_handler($event_name, $settings);
415
      if ($suffix = $handler->getEventNameSuffix()) {
416
        $event_name .= '--' . $suffix;
417
        $this->eventSettings[$event_name] = $settings;
418
      }
419
      else {
420
        // Do not store settings if there is no suffix.
421
        unset($this->eventSettings[$event_name]);
422
      }
423
    }
424
    if (array_search($event_name, $this->events) === FALSE) {
425
      $this->events[] = $event_name;
426
    }
427
    return $this;
428
  }
429

    
430
  /**
431
   * Implements RulesTriggerableInterface::getEventSettings().
432
   */
433
  public function getEventSettings($event_name) {
434
    if (isset($this->eventSettings[$event_name])) {
435
      return $this->eventSettings[$event_name];
436
    }
437
  }
438

    
439
  public function integrityCheck() {
440
    parent::integrityCheck();
441
    // Check integrity of the configured events.
442
    foreach ($this->events as $event_name) {
443
      $handler = rules_get_event_handler($event_name, $this->getEventSettings($event_name));
444
      $handler->validate();
445
    }
446
    return $this;
447
  }
448

    
449
  /**
450
   * Reaction rules can't add variables to the parent scope, so clone $state.
451
   */
452
  public function evaluate(RulesState $state) {
453
    // Implement recursion prevention for reaction rules.
454
    if ($state->isBlocked($this)) {
455
      return rules_log('Not evaluating @plugin %label to prevent recursion.', array('%label' => $this->label(), '@plugin' => $this->plugin()), RulesLog::INFO, $this);
456
    }
457
    $state->block($this);
458
    $copy = clone $state;
459
    parent::evaluate($copy);
460
    $state->unblock($this);
461
  }
462

    
463
  public function access() {
464
    foreach ($this->events as $event_name) {
465
      $event_info = rules_get_event_info($event_name);
466
      if (!empty($event_info['access callback']) && !call_user_func($event_info['access callback'], 'event', $event_info['name'])) {
467
        return FALSE;
468
      }
469
    }
470
    return parent::access();
471
  }
472

    
473
  public function dependencies() {
474
    $modules = array_flip(parent::dependencies());
475
    foreach ($this->events as $event_name) {
476
      $event_info = rules_get_event_info($event_name);
477
      if (isset($event_info['module'])) {
478
        $modules[$event_info['module']] = TRUE;
479
      }
480
    }
481
    return array_keys($modules);
482
  }
483

    
484
  public function providesVariables() {
485
    return array();
486
  }
487

    
488
  public function parameterInfo($optional = FALSE) {
489
    // If executed directly, all variables as defined by the event need to
490
    // be passed.
491
    return rules_filter_array($this->availableVariables(), 'handler', FALSE);
492
  }
493

    
494
  public function availableVariables() {
495
    if (!isset($this->availableVariables)) {
496
      if (isset($this->parent)) {
497
        // Return the event variables provided by the event set, once cached.
498
        $this->availableVariables = $this->parent->stateVariables();
499
      }
500
      else {
501
        // The intersection of the variables provided by the events are
502
        // available.
503
        foreach ($this->events as $event_name) {
504
          $handler = rules_get_event_handler($event_name, $this->getEventSettings($event_name));
505

    
506
          if (isset($this->availableVariables)) {
507
            $event_vars = $handler->availableVariables();
508
            // Merge variable info by intersecting the variable-info keys also,
509
            // so we have only metadata available that is valid for all of the
510
            // provided variables.
511
            foreach (array_intersect_key($this->availableVariables, $event_vars) as $name => $variable_info) {
512
              $this->availableVariables[$name] = array_intersect_key($variable_info, $event_vars[$name]);
513
            }
514
          }
515
          else {
516
            $this->availableVariables = $handler->availableVariables();
517
          }
518
        }
519
        $this->availableVariables = isset($this->availableVariables) ? RulesState::defaultVariables() + $this->availableVariables : RulesState::defaultVariables();
520
      }
521
    }
522
    return $this->availableVariables;
523
  }
524

    
525
  public function __sleep() {
526
    return parent::__sleep() + drupal_map_assoc(array('events', 'eventSettings'));
527
  }
528

    
529
  protected function exportChildren($key = 'ON') {
530
    foreach ($this->events as $event_name) {
531
      $export[$key][$event_name] = (array) $this->getEventSettings($event_name);
532
    }
533
    return $export + parent::exportChildren();
534
  }
535

    
536
  protected function importChildren($export, $key = 'ON') {
537
    // Detect and support old-style exports: a numerically indexed array of
538
    // event names.
539
    if (is_string(reset($export[$key])) && is_numeric(key($export[$key]))) {
540
      $this->events = $export[$key];
541
    }
542
    else {
543
      $this->events = array_keys($export[$key]);
544
      $this->eventSettings = array_filter($export[$key]);
545
    }
546
    parent::importChildren($export);
547
  }
548

    
549
  /**
550
   * Overrides optimize().
551
   */
552
  public function optimize() {
553
    parent::optimize();
554
    // No need to keep event settings for evaluation.
555
    $this->eventSettings = array();
556
  }
557

    
558
}
559

    
560
/**
561
 * A logical AND.
562
 */
563
class RulesAnd extends RulesConditionContainer {
564

    
565
  /**
566
   * @var string
567
   */
568
  protected $itemName = 'and';
569

    
570
  public function evaluate(RulesState $state) {
571
    foreach ($this->children as $condition) {
572
      if (!$condition->evaluate($state)) {
573
        rules_log('AND evaluated to FALSE.');
574
        return $this->negate;
575
      }
576
    }
577
    rules_log('AND evaluated to TRUE.');
578
    return !$this->negate;
579
  }
580

    
581
  public function label() {
582
    return !empty($this->label) ? $this->label : ($this->negate ? t('NOT AND') : t('AND'));
583
  }
584

    
585
}
586

    
587
/**
588
 * A logical OR.
589
 */
590
class RulesOr extends RulesConditionContainer {
591

    
592
  /**
593
   * @var string
594
   */
595
  protected $itemName = 'or';
596

    
597
  public function evaluate(RulesState $state) {
598
    foreach ($this->children as $condition) {
599
      if ($condition->evaluate($state)) {
600
        rules_log('OR evaluated to TRUE.');
601
        return !$this->negate;
602
      }
603
    }
604
    rules_log('OR evaluated to FALSE.');
605
    return $this->negate;
606
  }
607

    
608
  public function label() {
609
    return !empty($this->label) ? $this->label : ($this->negate ? t('NOT OR') : t('OR'));
610
  }
611

    
612
  /**
613
   * Overrides RulesContainerPlugin::stateVariables().
614
   *
615
   * Overridden to exclude all variable assertions as in an OR we cannot assert
616
   * the children are successfully evaluated.
617
   */
618
  protected function stateVariables($element = NULL) {
619
    $vars = $this->availableVariables();
620
    if (isset($element)) {
621
      // Add in variables provided by siblings executed before the element.
622
      foreach ($this->children as $child) {
623
        if ($child === $element) {
624
          break;
625
        }
626
        $vars += $child->providesVariables();
627
      }
628
    }
629
    return $vars;
630
  }
631

    
632
}
633

    
634
/**
635
 * A loop element.
636
 */
637
class RulesLoop extends RulesActionContainer {
638

    
639
  /**
640
   * @var string
641
   */
642
  protected $itemName = 'loop';
643
  protected $listItemInfo;
644

    
645
  public function __construct($settings = array(), $variables = NULL) {
646
    $this->setUp();
647
    $this->settings = (array) $settings + array(
648
      'item:var' => 'list_item',
649
      'item:label' => t('Current list item'),
650
    );
651
    if (!empty($variables)) {
652
      $this->info['variables'] = $variables;
653
    }
654
  }
655

    
656
  public function pluginParameterInfo() {
657
    $info['list'] = array(
658
      'type' => 'list',
659
      'restriction' => 'selector',
660
      'label' => t('List'),
661
      'description' => t('The list to loop over. The loop will step through each item in the list, allowing further actions on them. See <a href="@url"> the online handbook</a> for more information on how to use loops.',
662
        array('@url' => rules_external_help('loops'))),
663
    );
664
    return $info;
665
  }
666

    
667
  public function integrityCheck() {
668
    parent::integrityCheck();
669
    $this->checkVarName($this->settings['item:var']);
670
  }
671

    
672
  public function listItemInfo() {
673
    if (!isset($this->listItemInfo)) {
674
      if ($info = $this->getArgumentInfo('list')) {
675
        // Pass through the variable info keys like property info.
676
        $this->listItemInfo = array_intersect_key($info, array_flip(array('type', 'property info', 'bundle')));
677
        $this->listItemInfo['type'] = isset($info['type']) ? entity_property_list_extract_type($info['type']) : 'unknown';
678
      }
679
      else {
680
        $this->listItemInfo = array('type' => 'unknown');
681
      }
682
      $this->listItemInfo['label'] = $this->settings['item:label'];
683
    }
684
    return $this->listItemInfo;
685
  }
686

    
687
  public function evaluate(RulesState $state) {
688
    try {
689
      $param_info = $this->pluginParameterInfo();
690
      $list = $this->getArgument('list', $param_info['list'], $state);
691
      $item_var_info = $this->listItemInfo();
692
      $item_var_name = $this->settings['item:var'];
693

    
694
      if (isset($this->settings['list:select'])) {
695
        rules_log('Looping over the list items of %selector', array('%selector' => $this->settings['list:select']), RulesLog::INFO, $this);
696
      }
697

    
698
      // Loop over the list and evaluate the children for each list item.
699
      foreach ($list as $key => $item) {
700
        // Use a separate state so variables are available in the loop only.
701
        $state2 = clone $state;
702
        $state2->addVariable($item_var_name, $list[$key], $item_var_info);
703
        parent::evaluate($state2);
704

    
705
        // Update variables from parent scope.
706
        foreach ($state->variables as $var_key => &$var_value) {
707
          if (array_key_exists($var_key, $state2->variables)) {
708
            $var_value = $state2->variables[$var_key];
709
          }
710
        }
711
      }
712
    }
713
    catch (RulesEvaluationException $e) {
714
      rules_log($e->msg, $e->args, $e->severity);
715
      rules_log('Unable to evaluate %name.', array('%name' => $this->getPluginName()), RulesLog::WARN, $this);
716
    }
717
  }
718

    
719
  protected function stateVariables($element = NULL) {
720
    return array($this->settings['item:var'] => $this->listItemInfo()) + parent::stateVariables($element);
721
  }
722

    
723
  public function label() {
724
    return !empty($this->label) ? $this->label : t('Loop');
725
  }
726

    
727
  protected function exportChildren($key = 'DO') {
728
    return parent::exportChildren($key);
729
  }
730

    
731
  protected function importChildren($export, $key = 'DO') {
732
    parent::importChildren($export, $key);
733
  }
734

    
735
  protected function exportSettings() {
736
    $export = parent::exportSettings();
737
    $export['ITEM'][$this->settings['item:var']] = $this->settings['item:label'];
738
    return $export;
739
  }
740

    
741
  protected function importSettings($export) {
742
    parent::importSettings($export);
743
    if (isset($export['ITEM'])) {
744
      $this->settings['item:var'] = rules_array_key($export['ITEM']);
745
      $this->settings['item:label'] = reset($export['ITEM']);
746
    }
747
  }
748

    
749
}
750

    
751
/**
752
 * An action set component.
753
 */
754
class RulesActionSet extends RulesActionContainer {
755

    
756
  /**
757
   * @var string
758
   */
759
  protected $itemName = 'action set';
760

    
761
}
762

    
763
/**
764
 * A set of rules to execute upon defined variables.
765
 */
766
class RulesRuleSet extends RulesActionContainer {
767

    
768
  /**
769
   * @var string
770
   */
771
  protected $itemName = 'rule set';
772

    
773
  /**
774
   * @return RulesRuleSet
775
   */
776
  public function rule($rule) {
777
    return $this->action($rule);
778
  }
779

    
780
  protected function exportChildren($key = 'RULES') {
781
    return parent::exportChildren($key);
782
  }
783

    
784
  protected function importChildren($export, $key = 'RULES') {
785
    parent::importChildren($export, $key);
786
  }
787

    
788
}
789

    
790
/**
791
 * This class is used for caching the rules to be evaluated per event.
792
 */
793
class RulesEventSet extends RulesRuleSet {
794

    
795
  /**
796
   * @var string
797
   */
798
  protected $itemName = 'event set';
799

    
800
  /**
801
   * Event sets may recurse as we block recursions on rule-level.
802
   *
803
   * @var bool
804
   */
805
  public $recursion = TRUE;
806

    
807
  public function __construct($info = array()) {
808
    $this->setup();
809
    $this->info = $info;
810
  }
811

    
812
  public function executeByArgs($args = array()) {
813
    rules_log('Reacting on event %label.', array('%label' => $this->info['label']), RulesLog::INFO, NULL, TRUE);
814
    $state = $this->setUpState($args);
815
    module_invoke_all('rules_config_execute', $this);
816
    $this->evaluate($state);
817
    $state->cleanUp($this);
818
    rules_log('Finished reacting on event %label.', array('%label' => $this->info['label']), RulesLog::INFO, NULL, FALSE);
819
  }
820

    
821
  /**
822
   * Rebuilds the event cache.
823
   *
824
   * We cache event-sets per event in order to allow efficient usage via
825
   * rules_invoke_event().
826
   *
827
   * @see rules_get_cache()
828
   * @see rules_invoke_event()
829
   */
830
  public static function rebuildEventCache() {
831
    // Set up the per-event cache.
832
    $events = rules_fetch_data('event_info');
833
    $sets = array();
834
    // Add all rules associated with this event to an EventSet for caching.
835
    $rules = rules_config_load_multiple(FALSE, array('plugin' => 'reaction rule', 'active' => TRUE));
836

    
837
    foreach ($rules as $name => $rule) {
838
      foreach ($rule->events() as $event_name) {
839
        $event_base_name = rules_get_event_base_name($event_name);
840
        // Skip not defined events.
841
        if (empty($events[$event_base_name])) {
842
          continue;
843
        }
844
        // Create an event set if not yet done.
845
        if (!isset($sets[$event_name])) {
846
          $handler = rules_get_event_handler($event_name, $rule->getEventSettings($event_name));
847

    
848
          // Start the event dispatcher for this event, if any.
849
          if ($handler instanceof RulesEventDispatcherInterface && !$handler->isWatching()) {
850
            $handler->startWatching();
851
          }
852

    
853
          // Update the event info with the variables available based on the
854
          // event settings.
855
          $event_info = $events[$event_base_name];
856
          $event_info['variables'] = $handler->availableVariables();
857
          $sets[$event_name] = new RulesEventSet($event_info);
858
          $sets[$event_name]->name = $event_name;
859
        }
860

    
861
        // If a rule is marked as dirty, check if this still applies.
862
        if ($rule->dirty) {
863
          rules_config_update_dirty_flag($rule);
864
        }
865
        if (!$rule->dirty) {
866
          // Clone the rule to avoid modules getting the changed version from
867
          // the static cache.
868
          $sets[$event_name]->rule(clone $rule);
869
        }
870
      }
871
    }
872

    
873
    // Create cache items for all created sets.
874
    foreach ($sets as $event_name => $set) {
875
      $set->sortChildren();
876
      $set->optimize();
877
      // Allow modules to alter the cached event set.
878
      drupal_alter('rules_event_set', $event_name, $set);
879
      rules_set_cache('event_' . $event_name, $set);
880
    }
881
    // Cache a whitelist of configured events so we can use it to speed up later
882
    // calls. See rules_invoke_event().
883
    rules_set_cache('rules_event_whitelist', array_flip(array_keys($sets)));
884
  }
885

    
886
  protected function stateVariables($element = NULL) {
887
    return $this->availableVariables();
888
  }
889

    
890
  /**
891
   * Do not save since this class is for caching purposes only.
892
   *
893
   * @see RulesPlugin::save()
894
   */
895
  public function save($name = NULL, $module = 'rules') {
896
    return FALSE;
897
  }
898

    
899
}