Projet

Général

Profil

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

root / drupal7 / sites / all / modules / rules / rules.module @ 384fc62a

1
<?php
2

    
3
/**
4
 * @file Rules engine module
5
 */
6

    
7
// Include our hook implementations early, as they can be called even before
8
// hook_init().
9
require_once dirname(__FILE__) . '/modules/events.inc';
10

    
11
/**
12
 * Implements hook_init().
13
 */
14
function rules_init() {
15
  // Enable event invocation once hook_init() was invoked for Rules.
16
  rules_event_invocation_enabled(TRUE);
17
  rules_invoke_event('init');
18
}
19

    
20
/**
21
 * Returns an instance of the rules UI controller, which eases re-using the Rules UI.
22
 *
23
 * See the rules_admin.module for example usage.
24
 *
25
 * @return RulesUIController
26
 */
27
function rules_ui() {
28
  $static = drupal_static(__FUNCTION__);
29
  if (!isset($static)) {
30
    $static = new RulesUIController();
31
  }
32
  return $static;
33
}
34

    
35
/**
36
 * Returns a new rules action.
37
 *
38
 * @param $name
39
 *   The action's name.
40
 * @param $settings
41
 *   The action's settings array.
42
 * @return RulesAction
43
 */
44
function rules_action($name, $settings = array()) {
45
  return rules_plugin_factory('action', $name, $settings);
46
}
47

    
48
/**
49
 * Returns a new rules condition.
50
 *
51
 * @param $name
52
 *   The condition's name.
53
 * @param $settings
54
 *   The condition's settings array.
55
 * @return RulesCondition
56
 */
57
function rules_condition($name, $settings = array()) {
58
  return rules_plugin_factory('condition', $name, $settings);
59
}
60

    
61
/**
62
 * Creates a new rule.
63
 *
64
 * @param $variables
65
 *   The array of variables to setup in the evaluation state, making them
66
 *   available for the configuraion elements. Values for the variables need to
67
 *   be passed as argument when the rule is executed. Only Rule instances with
68
 *   no variables can be embedded in other configurations, e.g. rule sets.
69
 *   The array has to be keyed by variable name and contain a sub-array for each
70
 *   variable that has the same structure as the arrays used for describing
71
 *   parameters of an action, see hook_rules_action_info(). However, in addition
72
 *   to that the following keys are supported:
73
 *    - parameter: (optional) If set to FALSE, no parameter for the variable
74
 *      is created - thus no argument needs to be passed to the rule for the
75
 *      variable upon execution. As a consequence no value will be set
76
 *      initially, but the "Set data value" action may be used to do so. This is
77
 *      in particular useful for defining variables which can be provided to the
78
 *      caller (see $provides argument) but need not be passed in as parameter.
79
 * @param $provides
80
 *   The names of variables which should be provided to the caller. Only
81
 *   variables contained in $variables may be specified.
82
 * @return Rule
83
 */
84
function rule($variables = NULL, $provides = array()) {
85
  return rules_plugin_factory('rule', $variables, $provides);
86
}
87

    
88
/**
89
 * Creates a new reaction rule.
90
 *
91
 * @return RulesReactionRule
92
 */
93
function rules_reaction_rule() {
94
  return rules_plugin_factory('reaction rule');
95
}
96

    
97
/**
98
 * Creates a logical OR condition container.
99
 *
100
 * @param $variables
101
 *   An optional array as for rule().
102
 * @return RulesOr
103
 */
104
function rules_or($variables = NULL) {
105
  return rules_plugin_factory('or', $variables);
106
}
107

    
108
/**
109
 * Creates a logical AND condition container.
110
 *
111
 * @param $variables
112
 *   An optional array as for rule().
113
 * @return RulesAnd
114
 */
115
function rules_and($variables = NULL) {
116
  return rules_plugin_factory('and', $variables);
117
}
118

    
119
/**
120
 * Creates a loop.
121
 *
122
 * @param $settings
123
 *   The loop settings, containing
124
 *     'list:select': The data selector for the list to loop over.
125
 *     'item:var': Optionally a name for the list item variable.
126
 *     'item:label': Optionally a lebel for the list item variable.
127
 * @param $variables
128
 *   An optional array as for rule().
129
 * @return RulesLoop
130
 */
131
function rules_loop($settings = array(), $variables = NULL) {
132
  return rules_plugin_factory('loop', $settings, $variables);
133
}
134

    
135
/**
136
 * Creates a rule set.
137
 *
138
 * @param $variables
139
 *   An array as for rule().
140
 * @param $provides
141
 *   The names of variables which should be provided to the caller. See rule().
142
 * @return RulesRuleSet
143
 */
144
function rules_rule_set($variables = array(), $provides = array()) {
145
  return rules_plugin_factory('rule set', $variables, $provides);
146
}
147

    
148
/**
149
 * Creates an action set.
150
 *
151
 * @param $variables
152
 *   An array as for rule().
153
 * @param $provides
154
 *   The names of variables which should be provided to the caller. See rule().
155
 * @return RulesActionSet
156
 */
157
function rules_action_set($variables = array(), $provides = array()) {
158
  return rules_plugin_factory('action set', $variables, $provides);
159
}
160

    
161
/**
162
 * Log a message to the rules logger.
163
 *
164
 * @param $msg
165
 *   The message to log.
166
 * @param $args
167
 *   An array of placeholder arguments as used by t().
168
 * @param $priority
169
 *   A priority as defined by the RulesLog class.
170
 * @param RulesPlugin $element
171
 *  (optional) The RulesElement causing the log entry.
172
 * @param boolean $scope
173
 *  (optional) This may be used to denote the beginning (TRUE) or the end
174
 *  (FALSE) of a new execution scope.
175
 */
176
function rules_log($msg, $args = array(), $priority = RulesLog::INFO, RulesPlugin $element = NULL, $scope = NULL) {
177
  static $logger, $settings;
178

    
179
  // Statically cache the variable settings as this is called very often.
180
  if (!isset($settings)) {
181
    $settings['rules_log_errors'] = variable_get('rules_log_errors', RulesLog::WARN);
182
    $settings['rules_debug_log'] = variable_get('rules_debug_log', FALSE);
183
    $settings['rules_debug'] = variable_get('rules_debug', FALSE);
184
  }
185

    
186
  if ($priority >= $settings['rules_log_errors']) {
187
    $link = NULL;
188
    if (isset($element) && isset($element->root()->name)) {
189
      $link = l(t('edit configuration'), RulesPluginUI::path($element->root()->name, 'edit', $element));
190
    }
191
    // Disabled rules invocation to avoid an endless loop when using
192
    // watchdog - which would trigger a rules event.
193
    rules_event_invocation_enabled(FALSE);
194
    watchdog('rules', $msg, $args, $priority == RulesLog::WARN ? WATCHDOG_WARNING : WATCHDOG_ERROR, $link);
195
    rules_event_invocation_enabled(TRUE);
196
  }
197
  // Do nothing in case debugging is totally disabled.
198
  if (!$settings['rules_debug_log'] && !$settings['rules_debug']) {
199
    return;
200
  }
201
  if (!isset($logger)) {
202
    $logger = RulesLog::logger();
203
  }
204
  $path = isset($element) && isset($element->root()->name) ? RulesPluginUI::path($element->root()->name, 'edit', $element) : NULL;
205
  $logger->log($msg, $args, $priority, $scope, $path);
206
}
207

    
208
/**
209
 * Fetches module definitions for the given hook name.
210
 *
211
 * Used for collecting events, rules, actions and condtions from other modules.
212
 *
213
 * @param $hook
214
 *   The hook of the definitions to get from invoking hook_rules_{$hook}.
215
 */
216
function rules_fetch_data($hook) {
217
  $data = &drupal_static(__FUNCTION__, array());
218
  static $discover = array(
219
    'action_info' => 'RulesActionHandlerInterface',
220
    'condition_info' => 'RulesConditionHandlerInterface',
221
    'event_info' => 'RulesEventHandlerInterface',
222
  );
223

    
224
  if (!isset($data[$hook])) {
225
    $data[$hook] = array();
226
    foreach (module_implements('rules_' . $hook) as $module) {
227
      $result = call_user_func($module . '_rules_' . $hook);
228
      if (isset($result) && is_array($result)) {
229
        foreach ($result as $name => $item) {
230
          $item += array('module' => $module);
231
          $data[$hook][$name] = $item;
232
        }
233
      }
234
    }
235
    // Support class discovery.
236
    if (isset($discover[$hook])) {
237
      $data[$hook] += rules_discover_plugins($discover[$hook]);
238
    }
239
    drupal_alter('rules_'. $hook, $data[$hook]);
240
  }
241
  return $data[$hook];
242
}
243

    
244
/**
245
 * Discover plugin implementations.
246
 *
247
 * Class based plugin handlers must be loaded when rules caches are rebuilt,
248
 * such that they get discovered properly. You have the following options:
249
 *  - Put it into a regular module file (discouraged)
250
 *  - Put it into your module.rules.inc file
251
 *  - Put it in any file and declare it using hook_rules_file_info()
252
 *  - Put it in any file and declare it using hook_rules_directory()
253
 *
254
 * In addition to that, the class must be loadable via regular class
255
 * auto-loading, thus put the file holding the class in your info file or use
256
 * another class-loader.
257
 *
258
 * @param string $class
259
 *   The class or interface the plugins must implement. For a plugin to be
260
 *   discovered it must have a static getInfo() method also.
261
 *
262
 * @return array
263
 *   An info-hook style array containing info about discovered plugins.
264
 *
265
 * @see RulesActionHandlerInterface
266
 * @see RulesConditionHandlerInterface
267
 * @see RulesEventHandlerInterface
268
 */
269
function rules_discover_plugins($class) {
270
  // Make sure all files possibly holding plugins are included.
271
  RulesAbstractPlugin::includeFiles();
272

    
273
  $items = array();
274
  foreach (get_declared_classes() as $plugin_class) {
275
    if (is_subclass_of($plugin_class, $class) && method_exists($plugin_class, 'getInfo')) {
276
      $info = call_user_func(array($plugin_class, 'getInfo'));
277
      $info['class'] = $plugin_class;
278
      $info['module'] = _rules_discover_module($plugin_class);
279
      $items[$info['name']] = $info;
280
    }
281
  }
282
  return $items;
283
}
284

    
285
/**
286
 * Determines the module providing the given class.
287
 */
288
function _rules_discover_module($class) {
289
  $paths = &drupal_static(__FUNCTION__);
290

    
291
  if (!isset($paths)) {
292
    // Build up a map of modules keyed by their directory.
293
    foreach (system_list('module_enabled') as $name => $module_info) {
294
      $paths[dirname($module_info->filename)] = $name;
295
    }
296
  }
297

    
298
  // Retrieve the class file and convert its absolute path to a regular Drupal
299
  // path relative to the installation root.
300
  $reflection = new ReflectionClass($class);
301
  $path = str_replace(realpath(DRUPAL_ROOT) . DIRECTORY_SEPARATOR, '', realpath(dirname($reflection->getFileName())));
302
  $path = DIRECTORY_SEPARATOR != '/' ? str_replace(DIRECTORY_SEPARATOR, '/', $path) : $path;
303

    
304
  // Go up the path until we match a module up.
305
  $parts = explode('/', $path);
306
  while (!isset($paths[$path]) && array_pop($parts)) {
307
    $path = dirname($path);
308
  }
309
  return isset($paths[$path]) ? $paths[$path] : FALSE;
310
}
311

    
312
/**
313
 * Gets a rules cache entry.
314
 */
315
function &rules_get_cache($cid = 'data') {
316
  // Make use of the fast, advanced drupal static pattern.
317
  static $drupal_static_fast;
318
  if (!isset($drupal_static_fast)) {
319
    $drupal_static_fast['cache'] = &drupal_static(__FUNCTION__, array());
320
  }
321
  $cache = &$drupal_static_fast['cache'];
322

    
323
  if (!isset($cache[$cid])) {
324
    // The main 'data' cache includes translated strings, so each language is
325
    // cached separately.
326
    $cid_suffix = $cid == 'data' ? ':' . $GLOBALS['language']->language : '';
327

    
328
    if ($get = cache_get($cid . $cid_suffix, 'cache_rules')) {
329
      $cache[$cid] = $get->data;
330
    }
331
    else {
332
      // Prevent stampeding by ensuring the cache is rebuilt just once at the
333
      // same time.
334
      while (!lock_acquire(__FUNCTION__ . $cid . $cid_suffix, 60)) {
335
        rules_log('Cache rebuild lock hit: !cid', array('!cid' => $cid), RulesLog::WARN);
336
        // Now wait until the lock is released.
337
        lock_wait(__FUNCTION__ . $cid . $cid_suffix, 10);
338
        // If the lock is released it's likely the cache was rebuild. Thus check
339
        // again if we can fetch it from the persistent cache.
340
        if ($get = cache_get($cid . $cid_suffix, 'cache_rules')) {
341
          $cache[$cid] = $get->data;
342
          return $cache[$cid];
343
        }
344
      }
345
      if ($cid === 'data') {
346
        // There is no 'data' cache so we need to rebuild it. Make sure subsequent
347
        // cache gets of the main 'data' cache during rebuild get the interim
348
        // cache by passing in the reference of the static cache variable.
349
        _rules_rebuild_cache($cache['data']);
350
      }
351
      elseif (strpos($cid, 'comp_') === 0) {
352
        $cache[$cid] = FALSE;
353
        _rules_rebuild_component_cache();
354
      }
355
      elseif (strpos($cid, 'event_') === 0) {
356
        $cache[$cid] = FALSE;
357
        RulesEventSet::rebuildEventCache();
358
      }
359
      else {
360
        $cache[$cid] = FALSE;
361
      }
362
      // Ensure a set lock is released.
363
      lock_release(__FUNCTION__ . $cid . $cid_suffix);
364
    }
365
  }
366
  return $cache[$cid];
367
}
368

    
369
/**
370
 * Rebuilds the rules cache.
371
 *
372
 * This rebuilds the rules 'data' cache and invokes rebuildCache() methods on
373
 * all plugin classes, which allows plugins to add their own data to the cache.
374
 * The cache is rebuilt in the order the plugins are defined.
375
 *
376
 * Note that building the action/condition info cache triggers loading of all
377
 * components, thus depends on entity-loading and so syncing entities in code
378
 * to the database.
379
 *
380
 * @see rules_rules_plugin_info()
381
 * @see entity_defaults_rebuild()
382
 */
383
function _rules_rebuild_cache(&$cache) {
384
  foreach(array('data_info', 'plugin_info') as $hook) {
385
    $cache[$hook] = rules_fetch_data($hook);
386
  }
387
  foreach ($cache['plugin_info'] as $name => &$info) {
388
    // Let the items add something to the cache.
389
    $item = new $info['class']();
390
    $item->rebuildCache($info, $cache);
391
  }
392
  $cid_suffix = ':' . $GLOBALS['language']->language;
393
  cache_set('data' . $cid_suffix, $cache, 'cache_rules');
394
}
395

    
396
/**
397
 * Cache components to allow efficient usage via rules_invoke_component().
398
 *
399
 * @see rules_invoke_component()
400
 * @see rules_get_cache()
401
 */
402
function _rules_rebuild_component_cache() {
403
  $components = rules_get_components();
404

    
405
  foreach ($components as $id => $component) {
406
    // If a component is marked as dirty, check if this still applies.
407
    if ($component->dirty) {
408
      rules_config_update_dirty_flag($component);
409
    }
410
    if (!$component->dirty) {
411
      // Clone the component to avoid modules getting the to be cached
412
      // version from the static loading cache.
413
      $component = clone $component;
414
      $component->optimize();
415
      // Allow modules to alter the cached component.
416
      drupal_alter('rules_component', $component->plugin, $component);
417
      rules_set_cache('comp_' . $component->name, $component);
418
    }
419
  }
420
}
421

    
422
/**
423
 * Sets a rules cache item.
424
 *
425
 * In addition to calling cache_set(), this function makes sure the cache item
426
 * is immediately available via rules_get_cache() by keeping all cache items
427
 * in memory. That way we can guarantee rules_get_cache() is able to retrieve
428
 * any cache item, even if all cache gets fail.
429
 *
430
 * @see rules_get_cache()
431
 */
432
function rules_set_cache($cid, $data) {
433
  $cache = &drupal_static('rules_get_cache', array());
434
  $cache[$cid] = $data;
435
  cache_set($cid, $data, 'cache_rules');
436
}
437

    
438
/**
439
 * Implements hook_flush_caches().
440
 */
441
function rules_flush_caches() {
442
  return array('cache_rules');
443
}
444

    
445
/**
446
 * Clears the rule set cache
447
 */
448
function rules_clear_cache() {
449
  cache_clear_all('*', 'cache_rules', TRUE);
450
  variable_del('rules_event_whitelist');
451
  drupal_static_reset('rules_get_cache');
452
  drupal_static_reset('rules_fetch_data');
453
  drupal_static_reset('rules_config_update_dirty_flag');
454
  entity_get_controller('rules_config')->resetCache();
455
}
456

    
457
/**
458
 * Imports the given export and returns the imported configuration.
459
 *
460
 * @param $export
461
 *   A serialized string in JSON format as produced by the RulesPlugin::export()
462
 *   method, or the PHP export as usual PHP array.
463
 * @return RulesPlugin
464
 */
465
function rules_import($export, &$error_msg = '') {
466
  return entity_get_controller('rules_config')->import($export, $error_msg);
467
}
468

    
469

    
470
/**
471
 * Wraps the given data.
472
 *
473
 * @param $data
474
 *   If available, the actual data, else NULL.
475
 * @param $info
476
 *   An array of info about this data.
477
 * @param $force
478
 *   Usually data is only wrapped if really needed. If set to TRUE, wrapping the
479
 *   data is forced, so primitive data types are also wrapped.
480
 * @return EntityMetadataWrapper
481
 *   An EntityMetadataWrapper or the unwrapped data.
482
 *
483
 * @see hook_rules_data_info()
484
 */
485
function &rules_wrap_data($data = NULL, $info, $force = FALSE) {
486
  // If the data is already wrapped, use the existing wrapper.
487
  if ($data instanceof EntityMetadataWrapper) {
488
    return $data;
489
  }
490
  $cache = rules_get_cache();
491
  // Define the keys to be passed through to the metadata wrapper.
492
  $wrapper_keys = array_flip(array('property info', 'property defaults'));
493
  if (isset($cache['data_info'][$info['type']])) {
494
    $info += array_intersect_key($cache['data_info'][$info['type']], $wrapper_keys);
495
  }
496
  // If a list is given, also add in the info of the item type.
497
  $list_item_type = entity_property_list_extract_type($info['type']);
498
  if ($list_item_type && isset($cache['data_info'][$list_item_type])) {
499
    $info += array_intersect_key($cache['data_info'][$list_item_type], $wrapper_keys);
500
  }
501
  // By default we do not wrap the data, except for completely unknown types.
502
  if (!empty($cache['data_info'][$info['type']]['wrap']) || $list_item_type || $force || empty($cache['data_info'][$info['type']])) {
503
    unset($info['handler']);
504
    // Allow data types to define custom wrapper classes.
505
    if (!empty($cache['data_info'][$info['type']]['wrapper class'])) {
506
      $class = $cache['data_info'][$info['type']]['wrapper class'];
507
      $wrapper = new $class($info['type'], $data, $info);
508
    }
509
    else {
510
      $wrapper = entity_metadata_wrapper($info['type'], $data, $info);
511
    }
512
    return $wrapper;
513
  }
514
  return $data;
515
}
516

    
517
/**
518
 * Unwraps the given data, if it's wrapped.
519
 *
520
 * @param $data
521
 *   An array of wrapped data.
522
 * @param $info
523
 *   Optionally an array of info about how to unwrap the data. Keyed as $data.
524
 * @return
525
 *   An array containing unwrapped or passed through data.
526
 */
527
function rules_unwrap_data(array $data, $info = array()) {
528
  $cache = rules_get_cache();
529
  foreach ($data as $key => $entry) {
530
    // If it's a wrapper, unwrap unless specified otherwise.
531
    if ($entry instanceof EntityMetadataWrapper) {
532
      if (!isset($info[$key]['allow null'])) {
533
        $info[$key]['allow null'] = FALSE;
534
      }
535
      if (!isset($info[$key]['wrapped'])) {
536
        // By default, do not unwrap special data types that are always wrapped.
537
        $info[$key]['wrapped'] = (isset($info[$key]['type']) && is_string($info[$key]['type']) && !empty($cache['data_info'][$info[$key]['type']]['is wrapped']));
538
      }
539
      // Activate the decode option by default if 'sanitize' is not enabled, so
540
      // any text is either sanitized or decoded.
541
      // @see EntityMetadataWrapper::value()
542
      $options = $info[$key] + array('decode' => empty($info[$key]['sanitize']));
543

    
544
      try {
545
        if (!($info[$key]['allow null'] && $info[$key]['wrapped'])) {
546
          $value = $entry->value($options);
547

    
548
          if (!$info[$key]['wrapped']) {
549
            $data[$key] = $value;
550
          }
551
          if (!$info[$key]['allow null'] && !isset($value)) {
552
            throw new RulesEvaluationException('The variable or parameter %name is empty.', array('%name' => $key));
553
          }
554
        }
555
      }
556
      catch (EntityMetadataWrapperException $e) {
557
        throw new RulesEvaluationException('Unable to get the data value for the variable or parameter %name. Error: !error', array('%name' => $key, '!error' => $e->getMessage()));
558
      }
559
    }
560
  }
561
  return $data;
562
}
563

    
564
/**
565
 * Gets event info for a given event.
566
 *
567
 * @param string $event_name
568
 *   A (configured) event name.
569
 *
570
 * @return array
571
 *   An array of event info. If the event is unknown, a suiting info array is
572
 *   generated and returned
573
 */
574
function rules_get_event_info($event_name) {
575
  $base_event_name = rules_get_event_base_name($event_name);
576
  $events = rules_fetch_data('event_info');
577
  if (isset($events[$base_event_name])) {
578
    return $events[$base_event_name] + array('name' => $base_event_name);
579
  }
580
  return array(
581
    'label' => t('Unknown event "!event_name"', array('!event_name' => $base_event_name)),
582
    'name' => $base_event_name,
583
  );
584
}
585

    
586
/**
587
 * Returns the base name of a configured event name.
588
 *
589
 * For a configured event name like node_view--article the base event name
590
 * node_view is returned.
591
 *
592
 * @return string
593
 *   The event base name.
594
 */
595
function rules_get_event_base_name($event_name) {
596
  // Cut off any suffix from a configured event name.
597
  if (strpos($event_name, '--') !== FALSE) {
598
    $parts = explode('--', $event_name, 2);
599
    return $parts[0];
600
  }
601
  return $event_name;
602
}
603

    
604
/**
605
 * Returns the rule event handler for the given event.
606
 *
607
 * Events having no settings are handled via the class RulesEventSettingsNone.
608
 *
609
 * @param string $event_name
610
 *   The event name (base or configured).
611
 * @param array $settings
612
 *   (optional) An array of event settings to set on the handler.
613
 *
614
 * @return RulesEventHandlerInterface
615
 *   The event handler.
616
 */
617
function rules_get_event_handler($event_name, array $settings = NULL) {
618
  $event_name = rules_get_event_base_name($event_name);
619
  $event_info = rules_get_event_info($event_name);
620
  $class = !empty($event_info['class']) ? $event_info['class'] : 'RulesEventDefaultHandler';
621
  $handler = new $class($event_name, $event_info);
622
  return isset($settings) ? $handler->setSettings($settings) : $handler;
623
}
624

    
625
/**
626
 * Creates a new instance of a the given rules plugin.
627
 *
628
 * @return RulesPlugin
629
 */
630
function rules_plugin_factory($plugin_name, $arg1 = NULL, $arg2 = NULL) {
631
  $cache = rules_get_cache();
632
  if (isset($cache['plugin_info'][$plugin_name]['class'])) {
633
    return new $cache['plugin_info'][$plugin_name]['class']($arg1, $arg2);
634
  }
635
}
636

    
637
/**
638
 * Implementation of hook_rules_plugin_info().
639
 *
640
 * Note that the cache is rebuilt in the order of the plugins. Therefore the
641
 * condition and action plugins must be at the top, so that any components
642
 * re-building their cache can create configurations including properly setup-ed
643
 * actions and conditions.
644
 */
645
function rules_rules_plugin_info() {
646
  return array(
647
    'condition' => array(
648
      'class' => 'RulesCondition',
649
      'embeddable' => 'RulesConditionContainer',
650
      'extenders' => array (
651
        'RulesPluginImplInterface' => array(
652
          'class' => 'RulesAbstractPluginDefaults',
653
        ),
654
        'RulesPluginFeaturesIntegrationInterace' => array(
655
          'methods' => array(
656
            'features_export' => 'rules_features_abstract_default_features_export',
657
          ),
658
        ),
659
        'RulesPluginUIInterface' => array(
660
          'class' => 'RulesAbstractPluginUI',
661
        ),
662
      ),
663
    ),
664
    'action' => array(
665
      'class' => 'RulesAction',
666
      'embeddable' => 'RulesActionContainer',
667
      'extenders' => array (
668
        'RulesPluginImplInterface' => array(
669
          'class' => 'RulesAbstractPluginDefaults',
670
        ),
671
        'RulesPluginFeaturesIntegrationInterace' => array(
672
          'methods' => array(
673
            'features_export' => 'rules_features_abstract_default_features_export',
674
          ),
675
        ),
676
        'RulesPluginUIInterface' => array(
677
          'class' => 'RulesAbstractPluginUI',
678
        ),
679
      ),
680
    ),
681
    'or' => array(
682
      'label' => t('Condition set (OR)'),
683
      'class' => 'RulesOr',
684
      'embeddable' => 'RulesConditionContainer',
685
      'component' => TRUE,
686
      'extenders' => array(
687
        'RulesPluginUIInterface' => array(
688
          'class' => 'RulesConditionContainerUI',
689
        ),
690
      ),
691
    ),
692
    'and' => array(
693
      'label' => t('Condition set (AND)'),
694
      'class' => 'RulesAnd',
695
      'embeddable' => 'RulesConditionContainer',
696
      'component' => TRUE,
697
      'extenders' => array(
698
        'RulesPluginUIInterface' => array(
699
          'class' => 'RulesConditionContainerUI',
700
        ),
701
      ),
702
    ),
703
    'action set' => array(
704
      'label' => t('Action set'),
705
      'class' => 'RulesActionSet',
706
      'embeddable' => FALSE,
707
      'component' => TRUE,
708
      'extenders' => array(
709
        'RulesPluginUIInterface' => array(
710
          'class' => 'RulesActionContainerUI',
711
        ),
712
      ),
713
    ),
714
    'rule' => array(
715
      'label' => t('Rule'),
716
      'class' => 'Rule',
717
      'embeddable' => 'RulesRuleSet',
718
      'component' => TRUE,
719
      'extenders' => array(
720
        'RulesPluginUIInterface' => array(
721
          'class' => 'RulesRuleUI',
722
        ),
723
      ),
724
    ),
725
    'loop' => array(
726
      'class' => 'RulesLoop',
727
      'embeddable' => 'RulesActionContainer',
728
      'extenders' => array(
729
        'RulesPluginUIInterface' => array(
730
          'class' => 'RulesLoopUI',
731
        ),
732
      ),
733
    ),
734
    'reaction rule' => array(
735
      'class' => 'RulesReactionRule',
736
      'embeddable' => FALSE,
737
      'extenders' => array(
738
        'RulesPluginUIInterface' => array(
739
          'class' => 'RulesReactionRuleUI',
740
        ),
741
      ),
742
    ),
743
    'event set' => array(
744
      'class' => 'RulesEventSet',
745
      'embeddable' => FALSE,
746
    ),
747
    'rule set' => array(
748
      'label' => t('Rule set'),
749
      'class' => 'RulesRuleSet',
750
      'component' => TRUE,
751
      // Rule sets don't get embedded - we use a separate action to execute.
752
      'embeddable' => FALSE,
753
      'extenders' => array(
754
        'RulesPluginUIInterface' => array(
755
          'class' => 'RulesRuleSetUI',
756
        ),
757
      ),
758
    ),
759
  );
760
}
761

    
762
/**
763
 * Implementation of hook_entity_info().
764
 */
765
function rules_entity_info() {
766
  return array(
767
    'rules_config' => array(
768
      'label' => t('Rules configuration'),
769
      'controller class' => 'RulesEntityController',
770
      'base table' => 'rules_config',
771
      'fieldable' => TRUE,
772
      'entity keys' => array(
773
        'id' => 'id',
774
        'name' => 'name',
775
        'label' => 'label',
776
      ),
777
      'module' => 'rules',
778
      'static cache' => TRUE,
779
      'bundles' => array(),
780
      'configuration' => TRUE,
781
      'exportable' => TRUE,
782
      'export' => array(
783
        'default hook' => 'default_rules_configuration',
784
      ),
785
      'access callback' => 'rules_config_access',
786
      'features controller class' => 'RulesFeaturesController',
787
    ),
788
  );
789
}
790

    
791
/**
792
 * Implementation of hook_hook_info().
793
 */
794
function rules_hook_info() {
795
  foreach(array('plugin_info', 'rules_directory', 'data_info', 'condition_info', 'action_info', 'event_info', 'file_info', 'evaluator_info', 'data_processor_info') as $hook) {
796
    $hooks['rules_' . $hook] = array(
797
      'group' => 'rules',
798
    );
799
    $hooks['rules_' . $hook . '_alter'] = array(
800
      'group' => 'rules',
801
    );
802
  }
803
  $hooks['default_rules_configuration'] = array(
804
    'group' => 'rules_defaults',
805
  );
806
  $hooks['default_rules_configuration_alter'] = array(
807
    'group' => 'rules_defaults',
808
  );
809
  return $hooks;
810
}
811

    
812
/**
813
 * Load rule configurations from the database.
814
 *
815
 * This function should be used whenever you need to load more than one entity
816
 * from the database. The entities are loaded into memory and will not require
817
 * database access if loaded again during the same page request.
818
 *
819
 * @see hook_entity_info()
820
 * @see RulesEntityController
821
 *
822
 * @param $names
823
 *   An array of rules configuration names or FALSE to load all.
824
 * @param $conditions
825
 *   An array of conditions in the form 'field' => $value.
826
 *
827
 * @return
828
 *   An array of rule configurations indexed by their ids.
829
 */
830
function rules_config_load_multiple($names = array(), $conditions = array()) {
831
  return entity_load_multiple_by_name('rules_config', $names, $conditions);
832
}
833

    
834
/**
835
 * Loads a single rule configuration from the database.
836
 *
837
 * @see rules_config_load_multiple()
838
 *
839
 * @return RulesPlugin
840
 */
841
function rules_config_load($name) {
842
  return entity_load_single('rules_config', $name);
843
}
844

    
845
/**
846
 * Returns an array of configured components.
847
 *
848
 * For actually executing a component use rules_invoke_component(), as this
849
 * retrieves the component from cache instead.
850
 *
851
 * @param $label
852
 *   Whether to return only the label or the whole component object.
853
 * @param $type
854
 *   Optionally filter for 'action' or 'condition' components.
855
 * @param $conditions
856
 *   An array of additional conditions as required by rules_config_load().
857
 *
858
 * @return
859
 *   An array keyed by component name containing either the label or the config.
860
 */
861
function rules_get_components($label = FALSE, $type = NULL, $conditions = array()) {
862
  $cache = rules_get_cache();
863
  $plugins = array_keys(rules_filter_array($cache['plugin_info'], 'component', TRUE));
864
  $conditions = $conditions + array('plugin' => $plugins);
865
  $faces = array(
866
    'action' => 'RulesActionInterface',
867
    'condition' => 'RulesConditionInterface',
868
  );
869
  $items = array();
870
  foreach (rules_config_load_multiple(FALSE, $conditions) as $name => $config) {
871
    if (!isset($type) || $config instanceof $faces[$type]) {
872
      $items[$name] = $label ? $config->label() : $config;
873
    }
874
  }
875
  return $items;
876
}
877

    
878
/**
879
 * Delete rule configurations from database.
880
 *
881
 * @param $ids
882
 *   An array of entity IDs.
883
 */
884
function rules_config_delete(array $ids) {
885
  return entity_get_controller('rules_config')->delete($ids);
886
}
887

    
888
/**
889
 * Ensures the configuration's 'dirty' flag is up to date by running an integrity check.
890
 *
891
 * @param $update
892
 *   (optional) Whether the dirty flag is also updated in the database if
893
 *   necessary. Defaults to TRUE.
894
 */
895
function rules_config_update_dirty_flag($rules_config, $update = TRUE) {
896
  // Keep a log of already check configurations to avoid repetitive checks on
897
  // oftent used components.
898
  // @see rules_element_invoke_component_validate()
899
  $checked = &drupal_static(__FUNCTION__, array());
900
  if (!empty($checked[$rules_config->name])) {
901
    return;
902
  }
903
  $checked[$rules_config->name] = TRUE;
904

    
905
  $was_dirty = !empty($rules_config->dirty);
906
  try {
907
    // First set the rule to dirty, so any repetitive checks give green light
908
    // for this configuration.
909
    $rules_config->dirty = FALSE;
910
    $rules_config->integrityCheck();
911
    if ($was_dirty) {
912
      $variables = array('%label' => $rules_config->label(), '%name' => $rules_config->name, '@plugin' => $rules_config->plugin());
913
      watchdog('rules', 'The @plugin %label (%name) was marked dirty, but passes the integrity check now and is active again.', $variables, WATCHDOG_INFO);
914
    }
915
  }
916
  catch (RulesIntegrityException $e) {
917
    $rules_config->dirty = TRUE;
918
    if (!$was_dirty) {
919
      $variables = array('%label' => $rules_config->label(), '%name' => $rules_config->name, '!message' => $e->getMessage(), '@plugin' => $rules_config->plugin());
920
      watchdog('rules', 'The @plugin %label (%name) fails the integrity check and cannot be executed. Error: !message', $variables, WATCHDOG_ERROR);
921
    }
922
  }
923
  // Save the updated dirty flag to the database.
924
  if ($was_dirty != $rules_config->dirty) {
925
    db_update('rules_config')
926
      ->fields(array('dirty' => (int) $rules_config->dirty))
927
      ->condition('id', $rules_config->id)
928
      ->execute();
929
  }
930
}
931

    
932
/**
933
 * Invokes a hook and the associated rules event.
934
 *
935
 * Calling this function does the same as calling module_invoke_all() and
936
 * rules_invoke_event() separately, however merges both functions into one in
937
 * order to ease usage and to work efficiently.
938
 *
939
 * @param $hook
940
 *   The name of the hook / event to invoke.
941
 * @param ...
942
 *   Arguments to pass to the hook / event.
943
 *
944
 * @return
945
 *   An array of return values of the hook implementations. If modules return
946
 *   arrays from their implementations, those are merged into one array.
947
 */
948
function rules_invoke_all() {
949
  // Copied code from module_invoke_all().
950
  $args = func_get_args();
951
  $hook = $args[0];
952
  unset($args[0]);
953
  $return = array();
954
  foreach (module_implements($hook) as $module) {
955
    $function = $module . '_' . $hook;
956
    if (function_exists($function)) {
957
      $result = call_user_func_array($function, $args);
958
      if (isset($result) && is_array($result)) {
959
        $return = array_merge_recursive($return, $result);
960
      }
961
      elseif (isset($result)) {
962
        $return[] = $result;
963
      }
964
    }
965
  }
966
  // Invoke the event.
967
  rules_invoke_event_by_args($hook, $args);
968

    
969
  return $return;
970
}
971

    
972
/**
973
 * Invokes configured rules for the given event.
974
 *
975
 * @param $event_name
976
 *   The event's name.
977
 * @param ...
978
 *   Pass parameters for the variables provided by this event, as defined in
979
 *   hook_rules_event_info(). Example given:
980
 *   @code
981
 *     rules_invoke_event('node_view', $node, $view_mode);
982
 *   @endcode
983
 *
984
 * @see rules_invoke_event_by_args()
985
 */
986
function rules_invoke_event() {
987
  global $conf;
988

    
989
  $args = func_get_args();
990
  $event_name = $args[0];
991
  unset($args[0]);
992
  // We maintain a whitelist of configured events to reduces the number of cache
993
  // reads. We access it directly via the global $conf as this is fast without
994
  // having to introduce another static cache. Then, if the whitelist is unset,
995
  // we ignore it so cache rebuilding is triggered.
996
  if (rules_event_invocation_enabled() && (!isset($conf['rules_event_whitelist']) || isset($conf['rules_event_whitelist'][$event_name])) && $event = rules_get_cache('event_' . $event_name)) {
997
    $event->executeByArgs($args);
998
  }
999
}
1000

    
1001
/**
1002
 * Invokes configured rules for the given event.
1003
 *
1004
 * @param $event_name
1005
 *   The event's name.
1006
 * @param $args
1007
 *   An array of parameters for the variables provided by the event, as defined
1008
 *   in hook_rules_event_info(). Either pass an array keyed by the variable
1009
 *   names or a numerically indexed array, in which case the ordering of the
1010
 *   passed parameters has to match the order of the specified variables.
1011
 *   Example given:
1012
 *   @code
1013
 *     rules_invoke_event_by_args('node_view', array('node' => $node, 'view_mode' => $view_mode));
1014
 *   @endcode
1015
 *
1016
 * @see rules_invoke_event()
1017
 */
1018
function rules_invoke_event_by_args($event_name, $args = array()) {
1019
  global $conf;
1020

    
1021
  // We maintain a whitelist of configured events to reduces the number of cache
1022
  // reads. We access it directly via the global $conf as this is fast without
1023
  // having to introduce another static cache. Then, if the whitelist is unset,
1024
  // we ignore it so cache rebuilding is triggered.
1025
  if (rules_event_invocation_enabled() && (!isset($conf['rules_event_whitelist']) || isset($conf['rules_event_whitelist'][$event_name])) && $event = rules_get_cache('event_' . $event_name)) {
1026
    $event->executeByArgs($args);
1027
  }
1028
}
1029

    
1030
/**
1031
 * Invokes a rule component, e.g. a rule set.
1032
 *
1033
 * @param $component_name
1034
 *   The component's name.
1035
 * @param $args
1036
 *   Pass further parameters as required for the invoked component.
1037
 *
1038
 * @return
1039
 *   An array of variables as provided by the component, or FALSE in case the
1040
 *   component could not be executed.
1041
 */
1042
function rules_invoke_component() {
1043
  $args = func_get_args();
1044
  $name = array_shift($args);
1045
  if ($component = rules_get_cache('comp_' . $name)) {
1046
    return $component->executeByArgs($args);
1047
  }
1048
  return FALSE;
1049
}
1050

    
1051
/**
1052
 * Filters the given array of arrays by keeping only entries which have $key set
1053
 * to the value of $value.
1054
 *
1055
 * @param $array
1056
 *   The array of arrays to filter.
1057
 * @param $key
1058
 *   The key used for the comparison.
1059
 * @param $value
1060
 *   The value to compare the array's entry to.
1061
 *
1062
 * @return array
1063
 *   The filtered array.
1064
 */
1065
function rules_filter_array($array, $key, $value) {
1066
  $return = array();
1067
  foreach ($array as $i => $entry) {
1068
    $entry += array($key => NULL);
1069
    if ($entry[$key] == $value) {
1070
      $return[$i] = $entry;
1071
    }
1072
  }
1073
  return $return;
1074
}
1075

    
1076
/**
1077
 * Merges the $update array into $array making sure no values of $array not
1078
 * appearing in $update are lost.
1079
 *
1080
 * @return
1081
 *   The updated array.
1082
 */
1083
function rules_update_array(array $array, array $update) {
1084
  foreach ($update as $key => $data) {
1085
    if (isset($array[$key]) && is_array($array[$key]) && is_array($data)) {
1086
      $array[$key] = rules_update_array($array[$key], $data);
1087
    }
1088
    else {
1089
      $array[$key] = $data;
1090
    }
1091
  }
1092
  return $array;
1093
}
1094

    
1095
/**
1096
 * Extracts the property with the given name.
1097
 *
1098
 * @param $arrays
1099
 *   An array of arrays from which a property is to be extracted.
1100
 * @param $key
1101
 *   The name of the property to extract.
1102
 *
1103
 * @return An array of extracted properties, keyed as in $arrays-
1104
 */
1105
function rules_extract_property($arrays, $key) {
1106
  $data = array();
1107
  foreach ($arrays as $name => $item) {
1108
    $data[$name] = $item[$key];
1109
  }
1110
  return $data;
1111
}
1112

    
1113
/**
1114
 * Returns the first key of the array.
1115
 */
1116
function rules_array_key($array) {
1117
  reset($array);
1118
  return key($array);
1119
}
1120

    
1121
/**
1122
 * Clean replacements so they are URL friendly.
1123
 *
1124
 * Can be used as 'cleaning callback' for action or condition parameters.
1125
 *
1126
 * @param $replacements
1127
 *   An array of token replacements that need to be "cleaned" for use in the URL.
1128
 * @param $data
1129
 *   An array of objects used to generate the replacements.
1130
 * @param $options
1131
 *   An array of options used to generate the replacements.
1132
 *
1133
 * @see rules_path_action_info()
1134
 */
1135
function rules_path_clean_replacement_values(&$replacements, $data = array(), $options = array()) {
1136
  // Include path.eval.inc which contains path cleaning functions.
1137
  module_load_include('inc', 'rules', 'modules/path.eval');
1138
  foreach ($replacements as $token => $value) {
1139
    $replacements[$token] = rules_clean_path($value);
1140
  }
1141
}
1142

    
1143
/**
1144
 * Implements hook_theme().
1145
 */
1146
function rules_theme() {
1147
  return array(
1148
    'rules_elements' => array(
1149
      'render element' => 'element',
1150
      'file' => 'ui/ui.theme.inc',
1151
    ),
1152
    'rules_content_group' => array(
1153
      'render element' => 'element',
1154
      'file' => 'ui/ui.theme.inc',
1155
    ),
1156
    'rules_parameter_configuration' => array(
1157
      'render element' => 'element',
1158
      'file' => 'ui/ui.theme.inc',
1159
    ),
1160
    'rules_variable_view' => array(
1161
      'render element' => 'element',
1162
      'file' => 'ui/ui.theme.inc',
1163
    ),
1164
    'rules_data_selector_help' => array(
1165
      'variables' => array('parameter' => NULL, 'variables' => NULL),
1166
      'file' => 'ui/ui.theme.inc',
1167
    ),
1168
    'rules_ui_variable_form' => array(
1169
      'render element' => 'element',
1170
      'file' => 'ui/ui.theme.inc',
1171
    ),
1172
    'rules_log' => array(
1173
      'render element' => 'element',
1174
      'file' => 'ui/ui.theme.inc',
1175
    ),
1176
    'rules_autocomplete' => array(
1177
      'render element' => 'element',
1178
      'file' => 'ui/ui.theme.inc',
1179
    ),
1180
    'rules_debug_element' => array(
1181
      'render element' => 'element',
1182
      'file' => 'ui/ui.theme.inc',
1183
    ),
1184
    'rules_settings_help' => array(
1185
      'variables' => array('text' => '', 'heading' => ''),
1186
      'file' => 'ui/ui.theme.inc',
1187
    ),
1188
  );
1189
}
1190

    
1191
/**
1192
 * Implements hook_permission().
1193
 */
1194
function rules_permission() {
1195
  $perms = array(
1196
    'administer rules' => array(
1197
      'title' => t('Administer rule configurations'),
1198
      'description' => t('Administer rule configurations including events, conditions and actions for which the user has sufficient access permissions.'),
1199
    ),
1200
    'bypass rules access' => array(
1201
      'title' => t('Bypass Rules access control'),
1202
      'description' => t('Control all configurations regardless of permission restrictions of events, conditions or actions.'),
1203
      'restrict access' => TRUE,
1204
    ),
1205
    'access rules debug' => array(
1206
      'title' => t('Access the Rules debug log'),
1207
    ),
1208
  );
1209

    
1210
  // Fetch all components to generate the access keys.
1211
  $conditions['plugin'] = array_keys(rules_filter_array(rules_fetch_data('plugin_info'), 'component', TRUE));
1212
  $conditions['access_exposed'] = 1;
1213
  $components = entity_load('rules_config', FALSE, $conditions);
1214
  $perms += rules_permissions_by_component($components);
1215

    
1216
  return $perms;
1217
}
1218

    
1219
/**
1220
 * Helper function to get all the permissions for components that have access exposed.
1221
 */
1222
function rules_permissions_by_component(array $components = array()) {
1223
  $perms = array();
1224
  foreach ($components as $component) {
1225
    $perms += array(
1226
      "use Rules component $component->name" => array(
1227
        'title' => t('Use Rules component %component', array('%component' => $component->label())),
1228
        'description' => t('Controls access for using the component %component via the provided action or condition. <a href="@component-edit-url">Edit this component.</a>', array('%component' => $component->label(), '@component-edit-url' => url(RulesPluginUI::path($component->name)))),
1229
      ),
1230
    );
1231
  }
1232
  return $perms;
1233
}
1234

    
1235
/**
1236
 * Menu callback for loading rules configuration elements.
1237
 * @see RulesUIController::config_menu()
1238
 */
1239
function rules_element_load($element_id, $config_name) {
1240
  $config = rules_config_load($config_name);
1241
  return $config->elementMap()->lookup($element_id);
1242
}
1243

    
1244
/**
1245
 * Menu callback for getting the title as configured.
1246
 * @see RulesUIController::config_menu()
1247
 */
1248
function rules_get_title($text, $element) {
1249
  if ($element instanceof RulesPlugin) {
1250
    $cache = rules_get_cache();
1251
    $plugin = $element->plugin();
1252
    $plugin = isset($cache['plugin_info'][$plugin]['label']) ? $cache['plugin_info'][$plugin]['label'] : $plugin;
1253
    $plugin = drupal_strtolower(drupal_substr($plugin, 0, 1)) . drupal_substr($plugin, 1);
1254
    return t($text, array('!label' => $element->label(), '!plugin' => $plugin));
1255
  }
1256
  // As fallback treat $element as simple string.
1257
  return t($text, array('!plugin' => $element));
1258
}
1259

    
1260
/**
1261
 * Menu callback for getting the title for the add element page.
1262
 *
1263
 * Uses a work-a-round for accessing the plugin name.
1264
 * @see RulesUIController::config_menu()
1265
 */
1266
function rules_menu_add_element_title($array) {
1267
  $plugin_name = arg($array[0]);
1268
  $cache = rules_get_cache();
1269
  if (isset($cache['plugin_info'][$plugin_name]['class'])) {
1270
    $info = $cache['plugin_info'][$plugin_name] + array('label' => $plugin_name);
1271
    $label = drupal_strtolower(drupal_substr($info['label'], 0, 1)) . drupal_substr($info['label'], 1);
1272
    return t('Add a new !plugin', array('!plugin' => $label));
1273
  }
1274
}
1275

    
1276
/**
1277
 * Returns the current region for the debug log.
1278
 */
1279
function rules_debug_log_region() {
1280
  // If there is no setting for the current theme use the default theme setting.
1281
  global $theme_key;
1282
  $theme_default = variable_get('theme_default', 'bartik');
1283
  return variable_get('rules_debug_region_' . $theme_key, variable_get('rules_debug_region_' . $theme_default, 'help'));
1284
}
1285

    
1286
/**
1287
 * Implements hook_page_build() to add the rules debug log to the page bottom.
1288
 */
1289
function rules_page_build(&$page) {
1290
  // Invoke a the page redirect, in case the action has been executed.
1291
  // @see rules_action_drupal_goto()
1292
  if (isset($GLOBALS['_rules_action_drupal_goto_do'])) {
1293
    list($url, $force) = $GLOBALS['_rules_action_drupal_goto_do'];
1294
    drupal_goto($url);
1295
  }
1296

    
1297
  if (isset($_SESSION['rules_debug'])) {
1298
    $region = rules_debug_log_region();
1299
    foreach ($_SESSION['rules_debug'] as $log) {
1300
      $page[$region]['rules_debug'][] = array(
1301
        '#markup' => $log,
1302
      );
1303
      $page[$region]['rules_debug']['#theme_wrappers'] = array('rules_log');
1304
    }
1305
    unset($_SESSION['rules_debug']);
1306
  }
1307

    
1308
  if (rules_show_debug_output()) {
1309
    $region = rules_debug_log_region();
1310
    $page[$region]['rules_debug']['#pre_render'] = array('rules_debug_log_pre_render');
1311
  }
1312
}
1313

    
1314
/**
1315
 * Pre-render callback for the debug log, which renders and then clears it.
1316
 */
1317
function rules_debug_log_pre_render($elements) {
1318
  $logger = RulesLog::logger();
1319
  if ($log = $logger->render()) {
1320
    $logger = RulesLog::logger();
1321
    $logger->clear();
1322
    $elements[] = array('#markup' => $log);
1323
    $elements['#theme_wrappers'] = array('rules_log');
1324
    // Log the rules log to the system log if enabled.
1325
    if (variable_get('rules_debug_log', FALSE)) {
1326
      watchdog('rules', 'Rules debug information: !log', array('!log' => $log), WATCHDOG_NOTICE);
1327
    }
1328
  }
1329
  return $elements;
1330
}
1331

    
1332
/**
1333
 * Implements hook_drupal_goto_alter().
1334
 *
1335
 * @see rules_action_drupal_goto()
1336
 */
1337
function rules_drupal_goto_alter(&$path, &$options, &$http_response_code) {
1338
  // Invoke a the page redirect, in case the action has been executed.
1339
  if (isset($GLOBALS['_rules_action_drupal_goto_do'])) {
1340
    list($url, $force) = $GLOBALS['_rules_action_drupal_goto_do'];
1341

    
1342
    if ($force || !isset($_GET['destination'])) {
1343
      $url = drupal_parse_url($url);
1344
      $path = $url['path'];
1345
      $options['query'] = $url['query'];
1346
      $options['fragment'] = $url['fragment'];
1347
      $http_response_code = 302;
1348
    }
1349
  }
1350
}
1351

    
1352
/**
1353
 * Returns whether the debug log should be shown.
1354
 */
1355
function rules_show_debug_output() {
1356
  if (variable_get('rules_debug', FALSE) == RulesLog::INFO && user_access('access rules debug')) {
1357
    return TRUE;
1358
  }
1359
  // For performance avoid unnecessary auto-loading of the RulesLog class.
1360
  return variable_get('rules_debug', FALSE) == RulesLog::WARN && user_access('access rules debug') && class_exists('RulesLog', FALSE) && RulesLog::logger()->hasErrors();
1361
}
1362

    
1363
/**
1364
 * Implements hook_exit().
1365
 */
1366
function rules_exit() {
1367
  // Bail out if this is cached request and modules are not loaded.
1368
  if (!module_exists('rules') || !module_exists('user')) {
1369
    return;
1370
  }
1371
  if (rules_show_debug_output()) {
1372
    if ($log = RulesLog::logger()->render()) {
1373
      // Keep the log in the session so we can show it on the next page.
1374
      $_SESSION['rules_debug'][] = $log;
1375
    }
1376
  }
1377
  // Log the rules log to the system log if enabled.
1378
  if (variable_get('rules_debug_log', FALSE) && $log = RulesLog::logger()->render()) {
1379
    watchdog('rules', 'Rules debug information: !log', array('!log' => $log), WATCHDOG_NOTICE);
1380
  }
1381
}
1382

    
1383
/**
1384
 * Implements hook_element_info().
1385
 */
1386
function rules_element_info() {
1387
  // A duration form element for rules. Needs ui.forms.inc included.
1388
  $types['rules_duration'] = array(
1389
    '#input' => TRUE,
1390
    '#tree' => TRUE,
1391
    '#default_value' => 0,
1392
    '#value_callback' => 'rules_ui_element_duration_value',
1393
    '#process' => array('rules_ui_element_duration_process', 'ajax_process_form'),
1394
    '#after_build' => array('rules_ui_element_duration_after_build'),
1395
    '#pre_render' => array('form_pre_render_conditional_form_element'),
1396
  );
1397
  $types['rules_data_selection'] = array(
1398
    '#input' => TRUE,
1399
    '#pre_render' => array('form_pre_render_conditional_form_element'),
1400
    '#process' => array('rules_data_selection_process', 'ajax_process_form'),
1401
    '#theme' => 'rules_autocomplete',
1402
  );
1403
  return $types;
1404
}
1405

    
1406
/**
1407
 * Implements hook_modules_enabled().
1408
 */
1409
function rules_modules_enabled($modules) {
1410
  // Re-enable Rules configurations that are dirty, because they require one of
1411
  // the enabled the modules.
1412
  $query = db_select('rules_dependencies', 'rd');
1413
  $query->join('rules_config', 'rc', 'rd.id = rc.id');
1414
  $query->fields('rd', array('id'))
1415
        ->condition('rd.module', $modules, 'IN')
1416
        ->condition('rc.dirty', 1);
1417
  $ids = $query->execute()->fetchCol();
1418

    
1419
  // If there are some configurations that might work again, re-check all dirty
1420
  // configurations as others might work again too, e.g. consider a rule that is
1421
  // dirty because it requires a dirty component.
1422
  if ($ids) {
1423
    $rules_configs = rules_config_load_multiple(FALSE, array('dirty' => 1));
1424
    foreach ($rules_configs as $rules_config) {
1425
      try {
1426
        $rules_config->integrityCheck();
1427
        // If no exceptions were thrown we can set the configuration back to OK.
1428
        db_update('rules_config')
1429
          ->fields(array('dirty' => 0))
1430
          ->condition('id', $rules_config->id)
1431
          ->execute();
1432
        if ($rules_config->active) {
1433
          drupal_set_message(t('All dependencies for the Rules configuration %config are met again, so it has been re-activated.', array('%config' => $rules_config->label())));
1434
        }
1435
      }
1436
      catch (RulesIntegrityException $e) {
1437
        // The rule is still dirty, so do nothing.
1438
      }
1439
    }
1440
  }
1441
  rules_clear_cache();
1442
}
1443

    
1444
/**
1445
 * Implements hook_modules_disabled().
1446
 */
1447
function rules_modules_disabled($modules) {
1448
  // Disable Rules configurations that depend on one of the disabled modules.
1449
  $query = db_select('rules_dependencies', 'rd');
1450
  $query->join('rules_config', 'rc', 'rd.id = rc.id');
1451
  $query->fields('rd', array('id'))
1452
        ->distinct()
1453
        ->condition('rd.module', $modules, 'IN')
1454
        ->condition('rc.dirty', 0);
1455
  $ids = $query->execute()->fetchCol();
1456

    
1457
  if (!empty($ids)) {
1458
    db_update('rules_config')
1459
      ->fields(array('dirty' => 1))
1460
      ->condition('id', $ids, 'IN')
1461
      ->execute();
1462
    // Tell the user about enabled rules that have been marked as dirty.
1463
    $count = db_select('rules_config', 'r')
1464
      ->fields('r')
1465
      ->condition('id', $ids, 'IN')
1466
      ->condition('active', 1)
1467
      ->execute()->rowCount();
1468
    if ($count > 0) {
1469
      $message = format_plural($count,
1470
        '1 Rules configuration requires some of the disabled modules to function and cannot be executed any more.',
1471
        '@count Rules configuration require some of the disabled modules to function and cannot be executed any more.'
1472
      );
1473
      drupal_set_message($message, 'warning');
1474
    }
1475
  }
1476
  rules_clear_cache();
1477
}
1478

    
1479
/**
1480
 * Access callback for dealing with Rules configurations.
1481
 *
1482
 * @see entity_access()
1483
 */
1484
function rules_config_access($op, $rules_config = NULL, $account = NULL) {
1485
  if (user_access('bypass rules access', $account)) {
1486
    return TRUE;
1487
  }
1488
  // Allow modules to grant / deny access.
1489
  $access = module_invoke_all('rules_config_access', $op, $rules_config, $account);
1490

    
1491
  // Only grant access if at least one module granted access and no one denied
1492
  // access.
1493
  if (in_array(FALSE, $access, TRUE)) {
1494
    return FALSE;
1495
  }
1496
  elseif (in_array(TRUE, $access, TRUE)) {
1497
    return TRUE;
1498
  }
1499
  return FALSE;
1500
}
1501

    
1502
/**
1503
 * Implements hook_rules_config_access().
1504
 */
1505
function rules_rules_config_access($op, $rules_config = NULL, $account = NULL) {
1506
  // Instead of returning FALSE return nothing, so others still can grant
1507
  // access.
1508
  if (!isset($rules_config) || (isset($account) && $account->uid != $GLOBALS['user']->uid)) {
1509
    return;
1510
  }
1511
  if (user_access('administer rules', $account) && ($op == 'view' || $rules_config->access())) {
1512
    return TRUE;
1513
  }
1514
}
1515

    
1516
/**
1517
 * Implements hook_menu().
1518
 */
1519
function rules_menu() {
1520
  $items['admin/config/workflow/rules/upgrade'] = array(
1521
    'title' => 'Upgrade',
1522
    'page callback' => 'drupal_get_form',
1523
    'page arguments' => array('rules_upgrade_form'),
1524
    'access arguments' => array('administer rules'),
1525
    'file' => 'includes/rules.upgrade.inc',
1526
    'file path' => drupal_get_path('module', 'rules'),
1527
    'type' => MENU_CALLBACK,
1528
  );
1529
  $items['admin/config/workflow/rules/upgrade/clear'] = array(
1530
    'title' => 'Clear',
1531
    'page callback' => 'drupal_get_form',
1532
    'page arguments' => array('rules_upgrade_confirm_clear_form'),
1533
    'access arguments' => array('administer rules'),
1534
    'file' => 'includes/rules.upgrade.inc',
1535
    'file path' => drupal_get_path('module', 'rules'),
1536
    'type' => MENU_CALLBACK,
1537
  );
1538
  $items['admin/config/workflow/rules/autocomplete_tags'] = array(
1539
    'title' => 'Rules tags autocomplete',
1540
    'page callback' => 'rules_autocomplete_tags',
1541
    'page arguments' => array(5),
1542
    'access arguments' => array('administer rules'),
1543
    'file' => 'ui/ui.forms.inc',
1544
    'type' => MENU_CALLBACK,
1545
  );
1546
  return $items;
1547
}
1548

    
1549
/**
1550
 * Helper function to keep track of external documentation pages for Rules.
1551
 *
1552
 * @param $topic
1553
 *   The topic key for used for identifying help pages.
1554
 *
1555
 * @return
1556
 *   Either a URL for the given page, or the full list of external help pages.
1557
 */
1558
function rules_external_help($topic = NULL) {
1559
  $help = array(
1560
    'rules' =>                'http://drupal.org/node/298480',
1561
    'terminology' =>          'http://drupal.org/node/1299990',
1562
    'condition-components' => 'http://drupal.org/node/1300034',
1563
    'data-selection' =>       'http://drupal.org/node/1300042',
1564
    'chained-tokens' =>       'http://drupal.org/node/1300042',
1565
    'loops' =>                'http://drupal.org/node/1300058',
1566
    'components' =>           'http://drupal.org/node/1300024',
1567
    'component-types' =>      'http://drupal.org/node/1300024',
1568
    'variables' =>            'http://drupal.org/node/1300024',
1569
    'scheduler' =>            'http://drupal.org/node/1300068',
1570
    'coding' =>               'http://drupal.org/node/878720',
1571
  );
1572

    
1573
  if (isset($topic)) {
1574
    return isset($help[$topic]) ? $help[$topic] : FALSE;
1575
  }
1576
  return $help;
1577
}
1578

    
1579
/**
1580
 * Implements hook_help().
1581
 */
1582
function rules_help($path, $arg) {
1583
  // Only enable the help if the admin module is active.
1584
  if ($path == 'admin/help#rules' && module_exists('rules_admin')) {
1585

    
1586
    $output['header'] = array(
1587
      '#markup' => t('Rules documentation is kept online. Please use the links below for more information about Rules. Feel free to contribute to improving the online documentation!'),
1588
    );
1589
    // Build a list of essential Rules help pages, formatted as a bullet list.
1590
    $link_list['rules'] = l(t('Rules introduction'), rules_external_help('rules'));
1591
    $link_list['terminology'] = l(t('Rules terminology'), rules_external_help('terminology'));
1592
    $link_list['scheduler'] = l(t('Rules Scheduler'), rules_external_help('scheduler'));
1593
    $link_list['coding'] = l(t('Coding for Rules'), rules_external_help('coding'));
1594

    
1595
    $output['topic-list'] = array(
1596
      '#markup' => theme('item_list', array('items' => $link_list)),
1597
    );
1598
    return render($output);
1599
  }
1600
}
1601

    
1602
/**
1603
 * Implements hook_token_info().
1604
 */
1605
function rules_token_info() {
1606
  $cache = rules_get_cache();
1607
  $data_info = $cache['data_info'];
1608

    
1609
  $types = array('text', 'integer', 'uri', 'token', 'decimal', 'date', 'duration');
1610

    
1611
  foreach ($types as $type) {
1612
    $token_type = $data_info[$type]['token type'];
1613

    
1614
    $token_info['types'][$token_type] = array(
1615
      'name' => $data_info[$type]['label'],
1616
      'description' => t('Tokens related to %label Rules variables.', array('%label' => $data_info[$type]['label'])),
1617
      'needs-data' => $token_type,
1618
    );
1619
    $token_info['tokens'][$token_type]['value'] = array(
1620
      'name' => t("Value"),
1621
      'description' => t('The value of the variable.'),
1622
    );
1623
  }
1624
  return $token_info;
1625
}
1626

    
1627
/**
1628
 * Implements hook_tokens().
1629
 */
1630
function rules_tokens($type, $tokens, $data, $options = array()) {
1631
  // Handle replacements of primitive variable types.
1632
  if (substr($type, 0, 6) == 'rules_' && !empty($data[$type])) {
1633
    // Leverage entity tokens token processor by passing on as struct.
1634
    $info['property info']['value'] = array(
1635
      'type' => substr($type, 6),
1636
      'label' => '',
1637
    );
1638
    // Entity tokens uses metadata wrappers as values for 'struct' types.
1639
    $wrapper = entity_metadata_wrapper('struct', array('value' => $data[$type]), $info);
1640
    return entity_token_tokens('struct', $tokens, array('struct' => $wrapper), $options);
1641
  }
1642
}
1643

    
1644
/**
1645
 * Helper function that retrieves a metadata wrapper with all properties.
1646
 *
1647
 * Note that without this helper, bundle-specific properties aren't added.
1648
 */
1649
function rules_get_entity_metadata_wrapper_all_properties(RulesAbstractPlugin $element) {
1650
  return entity_metadata_wrapper($element->settings['type'], NULL, array(
1651
    'property info alter' => 'rules_entity_metadata_wrapper_all_properties_callback',
1652
  ));
1653
}
1654

    
1655
/**
1656
 * Callback that returns a metadata wrapper with all properties.
1657
 */
1658
function rules_entity_metadata_wrapper_all_properties_callback(EntityMetadataWrapper $wrapper, $property_info) {
1659
  $info = $wrapper->info();
1660
  $properties = entity_get_all_property_info($info['type']);
1661
  $property_info['properties'] += $properties;
1662
  return $property_info;
1663
}
1664

    
1665
/**
1666
 * Helper to enable or disable the invocation of rules events.
1667
 *
1668
 * Rules invocation is disabled by default, such that Rules does not operate
1669
 * when Drupal is not fully bootstrapped. It gets enabled in rules_init() and
1670
 * rules_enable().
1671
 *
1672
 * @param bool|NULL $enable
1673
 *   NULL to leave the setting as is and TRUE / FALSE to change the behaviour.
1674
 *
1675
 * @return bool
1676
 *   Whether the rules invocation is enabled or disabled.
1677
 */
1678
function rules_event_invocation_enabled($enable = NULL) {
1679
  static $invocation_enabled = FALSE;
1680
  if (isset($enable)) {
1681
    $invocation_enabled = (bool) $enable;
1682
  }
1683
  // Disable invocation if configured or if site runs in maintenance mode.
1684
  return $invocation_enabled && !defined('MAINTENANCE_MODE');
1685
}