Projet

Général

Profil

Paste
Télécharger (55,5 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / rules / rules.module @ a5ba142b

1
<?php
2

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

    
7
// The class autoloader may fail for classes added in 7.x-2.4 (Issue 2090511).
8
if (!drupal_autoload_class('RulesEventHandlerEntityBundle')) {
9
  require_once dirname(__FILE__) . '/includes/rules.event.inc';
10
}
11

    
12
// Include our hook implementations early, as they can be called even before
13
// hook_init().
14
require_once dirname(__FILE__) . '/modules/events.inc';
15

    
16
/**
17
 * Implements hook_module_implements_alter().
18
 */
19
function rules_module_implements_alter(&$implementations, $hook) {
20
  // Ensures the invocation of hook_menu_get_item_alter() triggers
21
  // rules_menu_get_item_alter() first so the rules invocation is ready for all
22
  // sub-sequent hook implementations.
23
  if ($hook == 'menu_get_item_alter' && array_key_exists('rules', $implementations)) {
24
    $group = $implementations['rules'];
25
    unset($implementations['rules']);
26
    $implementations = array_merge(array('rules' => $group), $implementations);
27
  }
28
}
29

    
30
/**
31
 * Implements hook_menu_get_item_alter().
32
 */
33
function rules_menu_get_item_alter() {
34
  // Make sure that event invocation is enabled before menu items are loaded.
35
  // But make sure later calls to menu_get_item() won't automatically re-enabled
36
  // the rules invocation.
37
  // Example: modules that implement hook_entity_ENTITY_TYPE_load() might want
38
  // to invoke Rules events in that load hook, which is also invoked for menu
39
  // item loading. Since this can happen even before hook_init() we need to make
40
  // sure that firing Rules events is enabled at that point. A typical use case
41
  // for this is Drupal Commerce with commerce_cart_commerce_order_load().
42
  if (!drupal_static('rules_init', FALSE)) {
43
    rules_event_invocation_enabled(TRUE);
44
  }
45
}
46

    
47
/**
48
 * Implements hook_init().
49
 */
50
function rules_init() {
51
  // See rules_menu_get_item_alter().
52
  $rules_init = &drupal_static(__FUNCTION__, FALSE);
53
  $rules_init = TRUE;
54
  // Enable event invocation once hook_init() was invoked for Rules.
55
  rules_event_invocation_enabled(TRUE);
56
  rules_invoke_event('init');
57
}
58

    
59
/**
60
 * Returns an instance of the rules UI controller, which eases re-using the Rules UI.
61
 *
62
 * See the rules_admin.module for example usage.
63
 *
64
 * @return RulesUIController
65
 */
66
function rules_ui() {
67
  $static = drupal_static(__FUNCTION__);
68
  if (!isset($static)) {
69
    $static = new RulesUIController();
70
  }
71
  return $static;
72
}
73

    
74
/**
75
 * Returns a new rules action.
76
 *
77
 * @param $name
78
 *   The action's name.
79
 * @param $settings
80
 *   The action's settings array.
81
 * @return RulesAction
82
 */
83
function rules_action($name, $settings = array()) {
84
  return rules_plugin_factory('action', $name, $settings);
85
}
86

    
87
/**
88
 * Returns a new rules condition.
89
 *
90
 * @param $name
91
 *   The condition's name.
92
 * @param $settings
93
 *   The condition's settings array.
94
 * @return RulesCondition
95
 */
96
function rules_condition($name, $settings = array()) {
97
  return rules_plugin_factory('condition', $name, $settings);
98
}
99

    
100
/**
101
 * Creates a new rule.
102
 *
103
 * @param $variables
104
 *   The array of variables to setup in the evaluation state, making them
105
 *   available for the configuraion elements. Values for the variables need to
106
 *   be passed as argument when the rule is executed. Only Rule instances with
107
 *   no variables can be embedded in other configurations, e.g. rule sets.
108
 *   The array has to be keyed by variable name and contain a sub-array for each
109
 *   variable that has the same structure as the arrays used for describing
110
 *   parameters of an action, see hook_rules_action_info(). However, in addition
111
 *   to that the following keys are supported:
112
 *    - parameter: (optional) If set to FALSE, no parameter for the variable
113
 *      is created - thus no argument needs to be passed to the rule for the
114
 *      variable upon execution. As a consequence no value will be set
115
 *      initially, but the "Set data value" action may be used to do so. This is
116
 *      in particular useful for defining variables which can be provided to the
117
 *      caller (see $provides argument) but need not be passed in as parameter.
118
 * @param $provides
119
 *   The names of variables which should be provided to the caller. Only
120
 *   variables contained in $variables may be specified.
121
 * @return Rule
122
 */
123
function rule($variables = NULL, $provides = array()) {
124
  return rules_plugin_factory('rule', $variables, $provides);
125
}
126

    
127
/**
128
 * Creates a new reaction rule.
129
 *
130
 * @return RulesReactionRule
131
 */
132
function rules_reaction_rule() {
133
  return rules_plugin_factory('reaction rule');
134
}
135

    
136
/**
137
 * Creates a logical OR condition container.
138
 *
139
 * @param $variables
140
 *   An optional array as for rule().
141
 * @return RulesOr
142
 */
143
function rules_or($variables = NULL) {
144
  return rules_plugin_factory('or', $variables);
145
}
146

    
147
/**
148
 * Creates a logical AND condition container.
149
 *
150
 * @param $variables
151
 *   An optional array as for rule().
152
 * @return RulesAnd
153
 */
154
function rules_and($variables = NULL) {
155
  return rules_plugin_factory('and', $variables);
156
}
157

    
158
/**
159
 * Creates a loop.
160
 *
161
 * @param $settings
162
 *   The loop settings, containing
163
 *     'list:select': The data selector for the list to loop over.
164
 *     'item:var': Optionally a name for the list item variable.
165
 *     'item:label': Optionally a lebel for the list item variable.
166
 * @param $variables
167
 *   An optional array as for rule().
168
 * @return RulesLoop
169
 */
170
function rules_loop($settings = array(), $variables = NULL) {
171
  return rules_plugin_factory('loop', $settings, $variables);
172
}
173

    
174
/**
175
 * Creates a rule set.
176
 *
177
 * @param $variables
178
 *   An array as for rule().
179
 * @param $provides
180
 *   The names of variables which should be provided to the caller. See rule().
181
 * @return RulesRuleSet
182
 */
183
function rules_rule_set($variables = array(), $provides = array()) {
184
  return rules_plugin_factory('rule set', $variables, $provides);
185
}
186

    
187
/**
188
 * Creates an action set.
189
 *
190
 * @param $variables
191
 *   An array as for rule().
192
 * @param $provides
193
 *   The names of variables which should be provided to the caller. See rule().
194
 * @return RulesActionSet
195
 */
196
function rules_action_set($variables = array(), $provides = array()) {
197
  return rules_plugin_factory('action set', $variables, $provides);
198
}
199

    
200
/**
201
 * Log a message to the rules logger.
202
 *
203
 * @param $msg
204
 *   The message to log.
205
 * @param $args
206
 *   An array of placeholder arguments as used by t().
207
 * @param $priority
208
 *   A priority as defined by the RulesLog class.
209
 * @param RulesPlugin $element
210
 *  (optional) The RulesElement causing the log entry.
211
 * @param boolean $scope
212
 *  (optional) This may be used to denote the beginning (TRUE) or the end
213
 *  (FALSE) of a new execution scope.
214
 */
215
function rules_log($msg, $args = array(), $priority = RulesLog::INFO, RulesPlugin $element = NULL, $scope = NULL) {
216
  static $logger, $settings;
217

    
218
  // Statically cache the variable settings as this is called very often.
219
  if (!isset($settings)) {
220
    $settings['rules_log_errors'] = variable_get('rules_log_errors', RulesLog::WARN);
221
    $settings['rules_debug_log'] = variable_get('rules_debug_log', FALSE);
222
    $settings['rules_debug'] = variable_get('rules_debug', FALSE);
223
  }
224

    
225
  if ($priority >= $settings['rules_log_errors']) {
226
    $link = NULL;
227
    if (isset($element) && isset($element->root()->name)) {
228
      $link = l(t('edit configuration'), RulesPluginUI::path($element->root()->name, 'edit', $element));
229
    }
230
    // Disabled rules invocation to avoid an endless loop when using
231
    // watchdog - which would trigger a rules event.
232
    rules_event_invocation_enabled(FALSE);
233
    watchdog('rules', $msg, $args, $priority == RulesLog::WARN ? WATCHDOG_WARNING : WATCHDOG_ERROR, $link);
234
    rules_event_invocation_enabled(TRUE);
235
  }
236
  // Do nothing in case debugging is totally disabled.
237
  if (!$settings['rules_debug_log'] && !$settings['rules_debug']) {
238
    return;
239
  }
240
  if (!isset($logger)) {
241
    $logger = RulesLog::logger();
242
  }
243
  $path = isset($element) && isset($element->root()->name) ? RulesPluginUI::path($element->root()->name, 'edit', $element) : NULL;
244
  $logger->log($msg, $args, $priority, $scope, $path);
245
}
246

    
247
/**
248
 * Fetches module definitions for the given hook name.
249
 *
250
 * Used for collecting events, rules, actions and condtions from other modules.
251
 *
252
 * @param $hook
253
 *   The hook of the definitions to get from invoking hook_rules_{$hook}.
254
 */
255
function rules_fetch_data($hook) {
256
  $data = &drupal_static(__FUNCTION__, array());
257
  static $discover = array(
258
    'action_info' => 'RulesActionHandlerInterface',
259
    'condition_info' => 'RulesConditionHandlerInterface',
260
    'event_info' => 'RulesEventHandlerInterface',
261
  );
262

    
263
  if (!isset($data[$hook])) {
264
    $data[$hook] = array();
265
    foreach (module_implements('rules_' . $hook) as $module) {
266
      $result = call_user_func($module . '_rules_' . $hook);
267
      if (isset($result) && is_array($result)) {
268
        foreach ($result as $name => $item) {
269
          $item += array('module' => $module);
270
          $data[$hook][$name] = $item;
271
        }
272
      }
273
    }
274
    // Support class discovery.
275
    if (isset($discover[$hook])) {
276
      $data[$hook] += rules_discover_plugins($discover[$hook]);
277
    }
278
    drupal_alter('rules_'. $hook, $data[$hook]);
279
  }
280
  return $data[$hook];
281
}
282

    
283
/**
284
 * Discover plugin implementations.
285
 *
286
 * Class based plugin handlers must be loaded when rules caches are rebuilt,
287
 * such that they get discovered properly. You have the following options:
288
 *  - Put it into a regular module file (discouraged)
289
 *  - Put it into your module.rules.inc file
290
 *  - Put it in any file and declare it using hook_rules_file_info()
291
 *  - Put it in any file and declare it using hook_rules_directory()
292
 *
293
 * In addition to that, the class must be loadable via regular class
294
 * auto-loading, thus put the file holding the class in your info file or use
295
 * another class-loader.
296
 *
297
 * @param string $class
298
 *   The class or interface the plugins must implement. For a plugin to be
299
 *   discovered it must have a static getInfo() method also.
300
 *
301
 * @return array
302
 *   An info-hook style array containing info about discovered plugins.
303
 *
304
 * @see RulesActionHandlerInterface
305
 * @see RulesConditionHandlerInterface
306
 * @see RulesEventHandlerInterface
307
 */
308
function rules_discover_plugins($class) {
309
  // Make sure all files possibly holding plugins are included.
310
  RulesAbstractPlugin::includeFiles();
311

    
312
  $items = array();
313
  foreach (get_declared_classes() as $plugin_class) {
314
    if (is_subclass_of($plugin_class, $class) && method_exists($plugin_class, 'getInfo')) {
315
      $info = call_user_func(array($plugin_class, 'getInfo'));
316
      $info['class'] = $plugin_class;
317
      $info['module'] = _rules_discover_module($plugin_class);
318
      $items[$info['name']] = $info;
319
    }
320
  }
321
  return $items;
322
}
323

    
324
/**
325
 * Determines the module providing the given class.
326
 */
327
function _rules_discover_module($class) {
328
  $paths = &drupal_static(__FUNCTION__);
329

    
330
  if (!isset($paths)) {
331
    // Build up a map of modules keyed by their directory.
332
    foreach (system_list('module_enabled') as $name => $module_info) {
333
      $paths[dirname($module_info->filename)] = $name;
334
    }
335
  }
336

    
337
  // Retrieve the class file and convert its absolute path to a regular Drupal
338
  // path relative to the installation root.
339
  $reflection = new ReflectionClass($class);
340
  $path = str_replace(realpath(DRUPAL_ROOT) . DIRECTORY_SEPARATOR, '', realpath(dirname($reflection->getFileName())));
341
  $path = DIRECTORY_SEPARATOR != '/' ? str_replace(DIRECTORY_SEPARATOR, '/', $path) : $path;
342

    
343
  // Go up the path until we match a module up.
344
  $parts = explode('/', $path);
345
  while (!isset($paths[$path]) && array_pop($parts)) {
346
    $path = dirname($path);
347
  }
348
  return isset($paths[$path]) ? $paths[$path] : FALSE;
349
}
350

    
351
/**
352
 * Gets a rules cache entry.
353
 */
354
function &rules_get_cache($cid = 'data') {
355
  // Make use of the fast, advanced drupal static pattern.
356
  static $drupal_static_fast;
357
  if (!isset($drupal_static_fast)) {
358
    $drupal_static_fast['cache'] = &drupal_static(__FUNCTION__, array());
359
  }
360
  $cache = &$drupal_static_fast['cache'];
361

    
362
  if (!isset($cache[$cid])) {
363
    // The main 'data' cache includes translated strings, so each language is
364
    // cached separately.
365
    $cid_suffix = $cid == 'data' ? ':' . $GLOBALS['language']->language : '';
366

    
367
    if ($get = cache_get($cid . $cid_suffix, 'cache_rules')) {
368
      $cache[$cid] = $get->data;
369
    }
370
    else {
371
      // Prevent stampeding by ensuring the cache is rebuilt just once at the
372
      // same time.
373
      while (!lock_acquire(__FUNCTION__ . $cid . $cid_suffix, 60)) {
374
        // Now wait until the lock is released.
375
        lock_wait(__FUNCTION__ . $cid . $cid_suffix, 30);
376
        // If the lock is released it's likely the cache was rebuild. Thus check
377
        // again if we can fetch it from the persistent cache.
378
        if ($get = cache_get($cid . $cid_suffix, 'cache_rules')) {
379
          $cache[$cid] = $get->data;
380
          return $cache[$cid];
381
        }
382
      }
383
      if ($cid === 'data') {
384
        // There is no 'data' cache so we need to rebuild it. Make sure subsequent
385
        // cache gets of the main 'data' cache during rebuild get the interim
386
        // cache by passing in the reference of the static cache variable.
387
        _rules_rebuild_cache($cache['data']);
388
      }
389
      elseif (strpos($cid, 'comp_') === 0) {
390
        $cache[$cid] = FALSE;
391
        _rules_rebuild_component_cache();
392
      }
393
      elseif (strpos($cid, 'event_') === 0 || $cid == 'rules_event_whitelist') {
394
        $cache[$cid] = FALSE;
395
        RulesEventSet::rebuildEventCache();
396
      }
397
      else {
398
        $cache[$cid] = FALSE;
399
      }
400
      // Ensure a set lock is released.
401
      lock_release(__FUNCTION__ . $cid . $cid_suffix);
402
    }
403
  }
404
  return $cache[$cid];
405
}
406

    
407
/**
408
 * Rebuilds the rules cache.
409
 *
410
 * This rebuilds the rules 'data' cache and invokes rebuildCache() methods on
411
 * all plugin classes, which allows plugins to add their own data to the cache.
412
 * The cache is rebuilt in the order the plugins are defined.
413
 *
414
 * Note that building the action/condition info cache triggers loading of all
415
 * components, thus depends on entity-loading and so syncing entities in code
416
 * to the database.
417
 *
418
 * @see rules_rules_plugin_info()
419
 * @see entity_defaults_rebuild()
420
 */
421
function _rules_rebuild_cache(&$cache) {
422
  foreach(array('data_info', 'plugin_info') as $hook) {
423
    $cache[$hook] = rules_fetch_data($hook);
424
  }
425
  foreach ($cache['plugin_info'] as $name => &$info) {
426
    // Let the items add something to the cache.
427
    $item = new $info['class']();
428
    $item->rebuildCache($info, $cache);
429
  }
430
  $cid_suffix = ':' . $GLOBALS['language']->language;
431
  cache_set('data' . $cid_suffix, $cache, 'cache_rules');
432
}
433

    
434
/**
435
 * Cache components to allow efficient usage via rules_invoke_component().
436
 *
437
 * @see rules_invoke_component()
438
 * @see rules_get_cache()
439
 */
440
function _rules_rebuild_component_cache() {
441
  $components = rules_get_components();
442

    
443
  foreach ($components as $id => $component) {
444
    // If a component is marked as dirty, check if this still applies.
445
    if ($component->dirty) {
446
      rules_config_update_dirty_flag($component);
447
    }
448
    if (!$component->dirty) {
449
      // Clone the component to avoid modules getting the to be cached
450
      // version from the static loading cache.
451
      $component = clone $component;
452
      $component->optimize();
453
      // Allow modules to alter the cached component.
454
      drupal_alter('rules_component', $component->plugin, $component);
455
      rules_set_cache('comp_' . $component->name, $component);
456
    }
457
  }
458
}
459

    
460
/**
461
 * Sets a rules cache item.
462
 *
463
 * In addition to calling cache_set(), this function makes sure the cache item
464
 * is immediately available via rules_get_cache() by keeping all cache items
465
 * in memory. That way we can guarantee rules_get_cache() is able to retrieve
466
 * any cache item, even if all cache gets fail.
467
 *
468
 * @see rules_get_cache()
469
 */
470
function rules_set_cache($cid, $data) {
471
  $cache = &drupal_static('rules_get_cache', array());
472
  $cache[$cid] = $data;
473
  cache_set($cid, $data, 'cache_rules');
474
}
475

    
476
/**
477
 * Implements hook_flush_caches().
478
 */
479
function rules_flush_caches() {
480
  return array('cache_rules');
481
}
482

    
483
/**
484
 * Clears the rule set cache
485
 */
486
function rules_clear_cache() {
487
  cache_clear_all('*', 'cache_rules', TRUE);
488
  drupal_static_reset('rules_get_cache');
489
  drupal_static_reset('rules_fetch_data');
490
  drupal_static_reset('rules_config_update_dirty_flag');
491
  entity_get_controller('rules_config')->resetCache();
492
}
493

    
494
/**
495
 * Imports the given export and returns the imported configuration.
496
 *
497
 * @param $export
498
 *   A serialized string in JSON format as produced by the RulesPlugin::export()
499
 *   method, or the PHP export as usual PHP array.
500
 * @return RulesPlugin
501
 */
502
function rules_import($export, &$error_msg = '') {
503
  return entity_get_controller('rules_config')->import($export, $error_msg);
504
}
505

    
506

    
507
/**
508
 * Wraps the given data.
509
 *
510
 * @param $data
511
 *   If available, the actual data, else NULL.
512
 * @param $info
513
 *   An array of info about this data.
514
 * @param $force
515
 *   Usually data is only wrapped if really needed. If set to TRUE, wrapping the
516
 *   data is forced, so primitive data types are also wrapped.
517
 * @return EntityMetadataWrapper
518
 *   An EntityMetadataWrapper or the unwrapped data.
519
 *
520
 * @see hook_rules_data_info()
521
 */
522
function &rules_wrap_data($data = NULL, $info, $force = FALSE) {
523
  // If the data is already wrapped, use the existing wrapper.
524
  if ($data instanceof EntityMetadataWrapper) {
525
    return $data;
526
  }
527
  $cache = rules_get_cache();
528
  // Define the keys to be passed through to the metadata wrapper.
529
  $wrapper_keys = array_flip(array('property info', 'property defaults'));
530
  if (isset($cache['data_info'][$info['type']])) {
531
    $info += array_intersect_key($cache['data_info'][$info['type']], $wrapper_keys);
532
  }
533
  // If a list is given, also add in the info of the item type.
534
  $list_item_type = entity_property_list_extract_type($info['type']);
535
  if ($list_item_type && isset($cache['data_info'][$list_item_type])) {
536
    $info += array_intersect_key($cache['data_info'][$list_item_type], $wrapper_keys);
537
  }
538
  // By default we do not wrap the data, except for completely unknown types.
539
  if (!empty($cache['data_info'][$info['type']]['wrap']) || $list_item_type || $force || empty($cache['data_info'][$info['type']])) {
540
    unset($info['handler']);
541
    // Allow data types to define custom wrapper classes.
542
    if (!empty($cache['data_info'][$info['type']]['wrapper class'])) {
543
      $class = $cache['data_info'][$info['type']]['wrapper class'];
544
      $wrapper = new $class($info['type'], $data, $info);
545
    }
546
    else {
547
      $wrapper = entity_metadata_wrapper($info['type'], $data, $info);
548
    }
549
    return $wrapper;
550
  }
551
  return $data;
552
}
553

    
554
/**
555
 * Unwraps the given data, if it's wrapped.
556
 *
557
 * @param $data
558
 *   An array of wrapped data.
559
 * @param $info
560
 *   Optionally an array of info about how to unwrap the data. Keyed as $data.
561
 * @return
562
 *   An array containing unwrapped or passed through data.
563
 */
564
function rules_unwrap_data(array $data, $info = array()) {
565
  $cache = rules_get_cache();
566
  foreach ($data as $key => $entry) {
567
    // If it's a wrapper, unwrap unless specified otherwise.
568
    if ($entry instanceof EntityMetadataWrapper) {
569
      if (!isset($info[$key]['allow null'])) {
570
        $info[$key]['allow null'] = FALSE;
571
      }
572
      if (!isset($info[$key]['wrapped'])) {
573
        // By default, do not unwrap special data types that are always wrapped.
574
        $info[$key]['wrapped'] = (isset($info[$key]['type']) && is_string($info[$key]['type']) && !empty($cache['data_info'][$info[$key]['type']]['is wrapped']));
575
      }
576
      // Activate the decode option by default if 'sanitize' is not enabled, so
577
      // any text is either sanitized or decoded.
578
      // @see EntityMetadataWrapper::value()
579
      $options = $info[$key] + array('decode' => empty($info[$key]['sanitize']));
580

    
581
      try {
582
        if (!($info[$key]['allow null'] && $info[$key]['wrapped'])) {
583
          $value = $entry->value($options);
584

    
585
          if (!$info[$key]['wrapped']) {
586
            $data[$key] = $value;
587
          }
588
          if (!$info[$key]['allow null'] && !isset($value)) {
589
            throw new RulesEvaluationException('The variable or parameter %name is empty.', array('%name' => $key));
590
          }
591
        }
592
      }
593
      catch (EntityMetadataWrapperException $e) {
594
        throw new RulesEvaluationException('Unable to get the data value for the variable or parameter %name. Error: !error', array('%name' => $key, '!error' => $e->getMessage()));
595
      }
596
    }
597
  }
598
  return $data;
599
}
600

    
601
/**
602
 * Gets event info for a given event.
603
 *
604
 * @param string $event_name
605
 *   A (configured) event name.
606
 *
607
 * @return array
608
 *   An array of event info. If the event is unknown, a suiting info array is
609
 *   generated and returned
610
 */
611
function rules_get_event_info($event_name) {
612
  $base_event_name = rules_get_event_base_name($event_name);
613
  $events = rules_fetch_data('event_info');
614
  if (isset($events[$base_event_name])) {
615
    return $events[$base_event_name] + array('name' => $base_event_name);
616
  }
617
  return array(
618
    'label' => t('Unknown event "!event_name"', array('!event_name' => $base_event_name)),
619
    'name' => $base_event_name,
620
  );
621
}
622

    
623
/**
624
 * Returns the base name of a configured event name.
625
 *
626
 * For a configured event name like node_view--article the base event name
627
 * node_view is returned.
628
 *
629
 * @return string
630
 *   The event base name.
631
 */
632
function rules_get_event_base_name($event_name) {
633
  // Cut off any suffix from a configured event name.
634
  if (strpos($event_name, '--') !== FALSE) {
635
    $parts = explode('--', $event_name, 2);
636
    return $parts[0];
637
  }
638
  return $event_name;
639
}
640

    
641
/**
642
 * Returns the rule event handler for the given event.
643
 *
644
 * Events having no settings are handled via the class RulesEventSettingsNone.
645
 *
646
 * @param string $event_name
647
 *   The event name (base or configured).
648
 * @param array $settings
649
 *   (optional) An array of event settings to set on the handler.
650
 *
651
 * @return RulesEventHandlerInterface
652
 *   The event handler.
653
 */
654
function rules_get_event_handler($event_name, array $settings = NULL) {
655
  $event_name = rules_get_event_base_name($event_name);
656
  $event_info = rules_get_event_info($event_name);
657
  $class = !empty($event_info['class']) ? $event_info['class'] : 'RulesEventDefaultHandler';
658
  $handler = new $class($event_name, $event_info);
659
  return isset($settings) ? $handler->setSettings($settings) : $handler;
660
}
661

    
662
/**
663
 * Creates a new instance of a the given rules plugin.
664
 *
665
 * @return RulesPlugin
666
 */
667
function rules_plugin_factory($plugin_name, $arg1 = NULL, $arg2 = NULL) {
668
  $cache = rules_get_cache();
669
  if (isset($cache['plugin_info'][$plugin_name]['class'])) {
670
    return new $cache['plugin_info'][$plugin_name]['class']($arg1, $arg2);
671
  }
672
}
673

    
674
/**
675
 * Implementation of hook_rules_plugin_info().
676
 *
677
 * Note that the cache is rebuilt in the order of the plugins. Therefore the
678
 * condition and action plugins must be at the top, so that any components
679
 * re-building their cache can create configurations including properly setup-ed
680
 * actions and conditions.
681
 */
682
function rules_rules_plugin_info() {
683
  return array(
684
    'condition' => array(
685
      'class' => 'RulesCondition',
686
      'embeddable' => 'RulesConditionContainer',
687
      'extenders' => array (
688
        'RulesPluginImplInterface' => array(
689
          'class' => 'RulesAbstractPluginDefaults',
690
        ),
691
        'RulesPluginFeaturesIntegrationInterace' => array(
692
          'methods' => array(
693
            'features_export' => 'rules_features_abstract_default_features_export',
694
          ),
695
        ),
696
        'RulesPluginUIInterface' => array(
697
          'class' => 'RulesAbstractPluginUI',
698
        ),
699
      ),
700
    ),
701
    'action' => array(
702
      'class' => 'RulesAction',
703
      'embeddable' => 'RulesActionContainer',
704
      'extenders' => array (
705
        'RulesPluginImplInterface' => array(
706
          'class' => 'RulesAbstractPluginDefaults',
707
        ),
708
        'RulesPluginFeaturesIntegrationInterace' => array(
709
          'methods' => array(
710
            'features_export' => 'rules_features_abstract_default_features_export',
711
          ),
712
        ),
713
        'RulesPluginUIInterface' => array(
714
          'class' => 'RulesAbstractPluginUI',
715
        ),
716
      ),
717
    ),
718
    'or' => array(
719
      'label' => t('Condition set (OR)'),
720
      'class' => 'RulesOr',
721
      'embeddable' => 'RulesConditionContainer',
722
      'component' => TRUE,
723
      'extenders' => array(
724
        'RulesPluginUIInterface' => array(
725
          'class' => 'RulesConditionContainerUI',
726
        ),
727
      ),
728
    ),
729
    'and' => array(
730
      'label' => t('Condition set (AND)'),
731
      'class' => 'RulesAnd',
732
      'embeddable' => 'RulesConditionContainer',
733
      'component' => TRUE,
734
      'extenders' => array(
735
        'RulesPluginUIInterface' => array(
736
          'class' => 'RulesConditionContainerUI',
737
        ),
738
      ),
739
    ),
740
    'action set' => array(
741
      'label' => t('Action set'),
742
      'class' => 'RulesActionSet',
743
      'embeddable' => FALSE,
744
      'component' => TRUE,
745
      'extenders' => array(
746
        'RulesPluginUIInterface' => array(
747
          'class' => 'RulesActionContainerUI',
748
        ),
749
      ),
750
    ),
751
    'rule' => array(
752
      'label' => t('Rule'),
753
      'class' => 'Rule',
754
      'embeddable' => 'RulesRuleSet',
755
      'component' => TRUE,
756
      'extenders' => array(
757
        'RulesPluginUIInterface' => array(
758
          'class' => 'RulesRuleUI',
759
        ),
760
      ),
761
    ),
762
    'loop' => array(
763
      'class' => 'RulesLoop',
764
      'embeddable' => 'RulesActionContainer',
765
      'extenders' => array(
766
        'RulesPluginUIInterface' => array(
767
          'class' => 'RulesLoopUI',
768
        ),
769
      ),
770
    ),
771
    'reaction rule' => array(
772
      'class' => 'RulesReactionRule',
773
      'embeddable' => FALSE,
774
      'extenders' => array(
775
        'RulesPluginUIInterface' => array(
776
          'class' => 'RulesReactionRuleUI',
777
        ),
778
      ),
779
    ),
780
    'event set' => array(
781
      'class' => 'RulesEventSet',
782
      'embeddable' => FALSE,
783
    ),
784
    'rule set' => array(
785
      'label' => t('Rule set'),
786
      'class' => 'RulesRuleSet',
787
      'component' => TRUE,
788
      // Rule sets don't get embedded - we use a separate action to execute.
789
      'embeddable' => FALSE,
790
      'extenders' => array(
791
        'RulesPluginUIInterface' => array(
792
          'class' => 'RulesRuleSetUI',
793
        ),
794
      ),
795
    ),
796
  );
797
}
798

    
799
/**
800
 * Implementation of hook_entity_info().
801
 */
802
function rules_entity_info() {
803
  return array(
804
    'rules_config' => array(
805
      'label' => t('Rules configuration'),
806
      'controller class' => 'RulesEntityController',
807
      'base table' => 'rules_config',
808
      'fieldable' => TRUE,
809
      'entity keys' => array(
810
        'id' => 'id',
811
        'name' => 'name',
812
        'label' => 'label',
813
      ),
814
      'module' => 'rules',
815
      'static cache' => TRUE,
816
      'bundles' => array(),
817
      'configuration' => TRUE,
818
      'exportable' => TRUE,
819
      'export' => array(
820
        'default hook' => 'default_rules_configuration',
821
      ),
822
      'access callback' => 'rules_config_access',
823
      'features controller class' => 'RulesFeaturesController',
824
    ),
825
  );
826
}
827

    
828
/**
829
 * Implementation of hook_hook_info().
830
 */
831
function rules_hook_info() {
832
  foreach(array('plugin_info', 'rules_directory', 'data_info', 'condition_info', 'action_info', 'event_info', 'file_info', 'evaluator_info', 'data_processor_info') as $hook) {
833
    $hooks['rules_' . $hook] = array(
834
      'group' => 'rules',
835
    );
836
    $hooks['rules_' . $hook . '_alter'] = array(
837
      'group' => 'rules',
838
    );
839
  }
840
  $hooks['default_rules_configuration'] = array(
841
    'group' => 'rules_defaults',
842
  );
843
  $hooks['default_rules_configuration_alter'] = array(
844
    'group' => 'rules_defaults',
845
  );
846
  return $hooks;
847
}
848

    
849
/**
850
 * Load rule configurations from the database.
851
 *
852
 * This function should be used whenever you need to load more than one entity
853
 * from the database. The entities are loaded into memory and will not require
854
 * database access if loaded again during the same page request.
855
 *
856
 * @see hook_entity_info()
857
 * @see RulesEntityController
858
 *
859
 * @param $names
860
 *   An array of rules configuration names or FALSE to load all.
861
 * @param $conditions
862
 *   An array of conditions in the form 'field' => $value.
863
 *
864
 * @return
865
 *   An array of rule configurations indexed by their ids.
866
 */
867
function rules_config_load_multiple($names = array(), $conditions = array()) {
868
  return entity_load_multiple_by_name('rules_config', $names, $conditions);
869
}
870

    
871
/**
872
 * Loads a single rule configuration from the database.
873
 *
874
 * @see rules_config_load_multiple()
875
 *
876
 * @return RulesPlugin
877
 */
878
function rules_config_load($name) {
879
  return entity_load_single('rules_config', $name);
880
}
881

    
882
/**
883
 * Returns an array of configured components.
884
 *
885
 * For actually executing a component use rules_invoke_component(), as this
886
 * retrieves the component from cache instead.
887
 *
888
 * @param $label
889
 *   Whether to return only the label or the whole component object.
890
 * @param $type
891
 *   Optionally filter for 'action' or 'condition' components.
892
 * @param $conditions
893
 *   An array of additional conditions as required by rules_config_load().
894
 *
895
 * @return
896
 *   An array keyed by component name containing either the label or the config.
897
 */
898
function rules_get_components($label = FALSE, $type = NULL, $conditions = array()) {
899
  $cache = rules_get_cache();
900
  $plugins = array_keys(rules_filter_array($cache['plugin_info'], 'component', TRUE));
901
  $conditions = $conditions + array('plugin' => $plugins);
902
  $faces = array(
903
    'action' => 'RulesActionInterface',
904
    'condition' => 'RulesConditionInterface',
905
  );
906
  $items = array();
907
  foreach (rules_config_load_multiple(FALSE, $conditions) as $name => $config) {
908
    if (!isset($type) || $config instanceof $faces[$type]) {
909
      $items[$name] = $label ? $config->label() : $config;
910
    }
911
  }
912
  return $items;
913
}
914

    
915
/**
916
 * Delete rule configurations from database.
917
 *
918
 * @param $ids
919
 *   An array of entity IDs.
920
 */
921
function rules_config_delete(array $ids) {
922
  return entity_get_controller('rules_config')->delete($ids);
923
}
924

    
925
/**
926
 * Ensures the configuration's 'dirty' flag is up to date by running an integrity check.
927
 *
928
 * @param $update
929
 *   (optional) Whether the dirty flag is also updated in the database if
930
 *   necessary. Defaults to TRUE.
931
 */
932
function rules_config_update_dirty_flag($rules_config, $update = TRUE) {
933
  // Keep a log of already check configurations to avoid repetitive checks on
934
  // oftent used components.
935
  // @see rules_element_invoke_component_validate()
936
  $checked = &drupal_static(__FUNCTION__, array());
937
  if (!empty($checked[$rules_config->name])) {
938
    return;
939
  }
940
  $checked[$rules_config->name] = TRUE;
941

    
942
  $was_dirty = !empty($rules_config->dirty);
943
  try {
944
    // First set the rule to dirty, so any repetitive checks give green light
945
    // for this configuration.
946
    $rules_config->dirty = FALSE;
947
    $rules_config->integrityCheck();
948
    if ($was_dirty) {
949
      $variables = array('%label' => $rules_config->label(), '%name' => $rules_config->name, '@plugin' => $rules_config->plugin());
950
      watchdog('rules', 'The @plugin %label (%name) was marked dirty, but passes the integrity check now and is active again.', $variables, WATCHDOG_INFO);
951
    }
952
  }
953
  catch (RulesIntegrityException $e) {
954
    $rules_config->dirty = TRUE;
955
    if (!$was_dirty) {
956
      $variables = array('%label' => $rules_config->label(), '%name' => $rules_config->name, '!message' => $e->getMessage(), '@plugin' => $rules_config->plugin());
957
      watchdog('rules', 'The @plugin %label (%name) fails the integrity check and cannot be executed. Error: !message', $variables, WATCHDOG_ERROR);
958
    }
959
  }
960
  // Save the updated dirty flag to the database.
961
  if ($was_dirty != $rules_config->dirty) {
962
    db_update('rules_config')
963
      ->fields(array('dirty' => (int) $rules_config->dirty))
964
      ->condition('id', $rules_config->id)
965
      ->execute();
966
  }
967
}
968

    
969
/**
970
 * Invokes a hook and the associated rules event.
971
 *
972
 * Calling this function does the same as calling module_invoke_all() and
973
 * rules_invoke_event() separately, however merges both functions into one in
974
 * order to ease usage and to work efficiently.
975
 *
976
 * @param $hook
977
 *   The name of the hook / event to invoke.
978
 * @param ...
979
 *   Arguments to pass to the hook / event.
980
 *
981
 * @return
982
 *   An array of return values of the hook implementations. If modules return
983
 *   arrays from their implementations, those are merged into one array.
984
 */
985
function rules_invoke_all() {
986
  // Copied code from module_invoke_all().
987
  $args = func_get_args();
988
  $hook = $args[0];
989
  unset($args[0]);
990
  $return = array();
991
  foreach (module_implements($hook) as $module) {
992
    $function = $module . '_' . $hook;
993
    if (function_exists($function)) {
994
      $result = call_user_func_array($function, $args);
995
      if (isset($result) && is_array($result)) {
996
        $return = array_merge_recursive($return, $result);
997
      }
998
      elseif (isset($result)) {
999
        $return[] = $result;
1000
      }
1001
    }
1002
  }
1003
  // Invoke the event.
1004
  rules_invoke_event_by_args($hook, $args);
1005

    
1006
  return $return;
1007
}
1008

    
1009
/**
1010
 * Invokes configured rules for the given event.
1011
 *
1012
 * @param $event_name
1013
 *   The event's name.
1014
 * @param ...
1015
 *   Pass parameters for the variables provided by this event, as defined in
1016
 *   hook_rules_event_info(). Example given:
1017
 *   @code
1018
 *     rules_invoke_event('node_view', $node, $view_mode);
1019
 *   @endcode
1020
 *
1021
 * @see rules_invoke_event_by_args()
1022
 */
1023
function rules_invoke_event() {
1024
  $args = func_get_args();
1025
  $event_name = $args[0];
1026
  unset($args[0]);
1027
  // We maintain a whitelist of configured events to reduces the number of cache
1028
  // reads. If the whitelist is not in the cache we proceed and it is rebuilt.
1029
  if (rules_event_invocation_enabled()) {
1030
    $whitelist = rules_get_cache('rules_event_whitelist');
1031
    if ((($whitelist === FALSE) || isset($whitelist[$event_name])) && $event = rules_get_cache('event_' . $event_name)) {
1032
      $event->executeByArgs($args);
1033
    }
1034
  }
1035
}
1036

    
1037
/**
1038
 * Invokes configured rules for the given event.
1039
 *
1040
 * @param $event_name
1041
 *   The event's name.
1042
 * @param $args
1043
 *   An array of parameters for the variables provided by the event, as defined
1044
 *   in hook_rules_event_info(). Either pass an array keyed by the variable
1045
 *   names or a numerically indexed array, in which case the ordering of the
1046
 *   passed parameters has to match the order of the specified variables.
1047
 *   Example given:
1048
 *   @code
1049
 *     rules_invoke_event_by_args('node_view', array('node' => $node, 'view_mode' => $view_mode));
1050
 *   @endcode
1051
 *
1052
 * @see rules_invoke_event()
1053
 */
1054
function rules_invoke_event_by_args($event_name, $args = array()) {
1055
  // We maintain a whitelist of configured events to reduces the number of cache
1056
  // reads. If the whitelist is empty we proceed and it is rebuilt.
1057
  if (rules_event_invocation_enabled()) {
1058
    $whitelist = rules_get_cache('rules_event_whitelist');
1059
    if ((empty($whitelist) || isset($whitelist[$event_name])) && $event = rules_get_cache('event_' . $event_name)) {
1060
      $event->executeByArgs($args);
1061
    }
1062
  }
1063
}
1064

    
1065
/**
1066
 * Invokes a rule component, e.g. a rule set.
1067
 *
1068
 * @param $component_name
1069
 *   The component's name.
1070
 * @param $args
1071
 *   Pass further parameters as required for the invoked component.
1072
 *
1073
 * @return
1074
 *   An array of variables as provided by the component, or FALSE in case the
1075
 *   component could not be executed.
1076
 */
1077
function rules_invoke_component() {
1078
  $args = func_get_args();
1079
  $name = array_shift($args);
1080
  if ($component = rules_get_cache('comp_' . $name)) {
1081
    return $component->executeByArgs($args);
1082
  }
1083
  return FALSE;
1084
}
1085

    
1086
/**
1087
 * Filters the given array of arrays by keeping only entries which have $key set
1088
 * to the value of $value.
1089
 *
1090
 * @param $array
1091
 *   The array of arrays to filter.
1092
 * @param $key
1093
 *   The key used for the comparison.
1094
 * @param $value
1095
 *   The value to compare the array's entry to.
1096
 *
1097
 * @return array
1098
 *   The filtered array.
1099
 */
1100
function rules_filter_array($array, $key, $value) {
1101
  $return = array();
1102
  foreach ($array as $i => $entry) {
1103
    $entry += array($key => NULL);
1104
    if ($entry[$key] == $value) {
1105
      $return[$i] = $entry;
1106
    }
1107
  }
1108
  return $return;
1109
}
1110

    
1111
/**
1112
 * Merges the $update array into $array making sure no values of $array not
1113
 * appearing in $update are lost.
1114
 *
1115
 * @return
1116
 *   The updated array.
1117
 */
1118
function rules_update_array(array $array, array $update) {
1119
  foreach ($update as $key => $data) {
1120
    if (isset($array[$key]) && is_array($array[$key]) && is_array($data)) {
1121
      $array[$key] = rules_update_array($array[$key], $data);
1122
    }
1123
    else {
1124
      $array[$key] = $data;
1125
    }
1126
  }
1127
  return $array;
1128
}
1129

    
1130
/**
1131
 * Extracts the property with the given name.
1132
 *
1133
 * @param $arrays
1134
 *   An array of arrays from which a property is to be extracted.
1135
 * @param $key
1136
 *   The name of the property to extract.
1137
 *
1138
 * @return An array of extracted properties, keyed as in $arrays-
1139
 */
1140
function rules_extract_property($arrays, $key) {
1141
  $data = array();
1142
  foreach ($arrays as $name => $item) {
1143
    $data[$name] = $item[$key];
1144
  }
1145
  return $data;
1146
}
1147

    
1148
/**
1149
 * Returns the first key of the array.
1150
 */
1151
function rules_array_key($array) {
1152
  reset($array);
1153
  return key($array);
1154
}
1155

    
1156
/**
1157
 * Clean replacements so they are URL friendly.
1158
 *
1159
 * Can be used as 'cleaning callback' for action or condition parameters.
1160
 *
1161
 * @param $replacements
1162
 *   An array of token replacements that need to be "cleaned" for use in the URL.
1163
 * @param $data
1164
 *   An array of objects used to generate the replacements.
1165
 * @param $options
1166
 *   An array of options used to generate the replacements.
1167
 *
1168
 * @see rules_path_action_info()
1169
 */
1170
function rules_path_clean_replacement_values(&$replacements, $data = array(), $options = array()) {
1171
  // Include path.eval.inc which contains path cleaning functions.
1172
  module_load_include('inc', 'rules', 'modules/path.eval');
1173
  foreach ($replacements as $token => $value) {
1174
    $replacements[$token] = rules_clean_path($value);
1175
  }
1176
}
1177

    
1178
/**
1179
 * Implements hook_theme().
1180
 */
1181
function rules_theme() {
1182
  return array(
1183
    'rules_elements' => array(
1184
      'render element' => 'element',
1185
      'file' => 'ui/ui.theme.inc',
1186
    ),
1187
    'rules_content_group' => array(
1188
      'render element' => 'element',
1189
      'file' => 'ui/ui.theme.inc',
1190
    ),
1191
    'rules_parameter_configuration' => array(
1192
      'render element' => 'element',
1193
      'file' => 'ui/ui.theme.inc',
1194
    ),
1195
    'rules_variable_view' => array(
1196
      'render element' => 'element',
1197
      'file' => 'ui/ui.theme.inc',
1198
    ),
1199
    'rules_data_selector_help' => array(
1200
      'variables' => array('parameter' => NULL, 'variables' => NULL),
1201
      'file' => 'ui/ui.theme.inc',
1202
    ),
1203
    'rules_ui_variable_form' => array(
1204
      'render element' => 'element',
1205
      'file' => 'ui/ui.theme.inc',
1206
    ),
1207
    'rules_log' => array(
1208
      'render element' => 'element',
1209
      'file' => 'ui/ui.theme.inc',
1210
    ),
1211
    'rules_autocomplete' => array(
1212
      'render element' => 'element',
1213
      'file' => 'ui/ui.theme.inc',
1214
    ),
1215
    'rules_debug_element' => array(
1216
      'render element' => 'element',
1217
      'file' => 'ui/ui.theme.inc',
1218
    ),
1219
    'rules_settings_help' => array(
1220
      'variables' => array('text' => '', 'heading' => ''),
1221
      'file' => 'ui/ui.theme.inc',
1222
    ),
1223
  );
1224
}
1225

    
1226
/**
1227
 * Implements hook_permission().
1228
 */
1229
function rules_permission() {
1230
  $perms = array(
1231
    'administer rules' => array(
1232
      'title' => t('Administer rule configurations'),
1233
      'description' => t('Administer rule configurations including events, conditions and actions for which the user has sufficient access permissions.'),
1234
    ),
1235
    'bypass rules access' => array(
1236
      'title' => t('Bypass Rules access control'),
1237
      'description' => t('Control all configurations regardless of permission restrictions of events, conditions or actions.'),
1238
      'restrict access' => TRUE,
1239
    ),
1240
    'access rules debug' => array(
1241
      'title' => t('Access the Rules debug log'),
1242
    ),
1243
  );
1244

    
1245
  // Fetch all components to generate the access keys.
1246
  $conditions['plugin'] = array_keys(rules_filter_array(rules_fetch_data('plugin_info'), 'component', TRUE));
1247
  $conditions['access_exposed'] = 1;
1248
  $components = entity_load('rules_config', FALSE, $conditions);
1249
  $perms += rules_permissions_by_component($components);
1250

    
1251
  return $perms;
1252
}
1253

    
1254
/**
1255
 * Helper function to get all the permissions for components that have access exposed.
1256
 */
1257
function rules_permissions_by_component(array $components = array()) {
1258
  $perms = array();
1259
  foreach ($components as $component) {
1260
    $perms += array(
1261
      "use Rules component $component->name" => array(
1262
        'title' => t('Use Rules component %component', array('%component' => $component->label())),
1263
        '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)))),
1264
      ),
1265
    );
1266
  }
1267
  return $perms;
1268
}
1269

    
1270
/**
1271
 * Menu callback for loading rules configuration elements.
1272
 * @see RulesUIController::config_menu()
1273
 */
1274
function rules_element_load($element_id, $config_name) {
1275
  $config = rules_config_load($config_name);
1276
  return $config->elementMap()->lookup($element_id);
1277
}
1278

    
1279
/**
1280
 * Menu callback for getting the title as configured.
1281
 * @see RulesUIController::config_menu()
1282
 */
1283
function rules_get_title($text, $element) {
1284
  if ($element instanceof RulesPlugin) {
1285
    $cache = rules_get_cache();
1286
    $plugin = $element->plugin();
1287
    $plugin = isset($cache['plugin_info'][$plugin]['label']) ? $cache['plugin_info'][$plugin]['label'] : $plugin;
1288
    $plugin = drupal_strtolower(drupal_substr($plugin, 0, 1)) . drupal_substr($plugin, 1);
1289
    return t($text, array('!label' => $element->label(), '!plugin' => $plugin));
1290
  }
1291
  // As fallback treat $element as simple string.
1292
  return t($text, array('!plugin' => $element));
1293
}
1294

    
1295
/**
1296
 * Menu callback for getting the title for the add element page.
1297
 *
1298
 * Uses a work-a-round for accessing the plugin name.
1299
 * @see RulesUIController::config_menu()
1300
 */
1301
function rules_menu_add_element_title($array) {
1302
  $plugin_name = arg($array[0]);
1303
  $cache = rules_get_cache();
1304
  if (isset($cache['plugin_info'][$plugin_name]['class'])) {
1305
    $info = $cache['plugin_info'][$plugin_name] + array('label' => $plugin_name);
1306
    $label = drupal_strtolower(drupal_substr($info['label'], 0, 1)) . drupal_substr($info['label'], 1);
1307
    return t('Add a new !plugin', array('!plugin' => $label));
1308
  }
1309
}
1310

    
1311
/**
1312
 * Returns the current region for the debug log.
1313
 */
1314
function rules_debug_log_region() {
1315
  // If there is no setting for the current theme use the default theme setting.
1316
  global $theme_key;
1317
  $theme_default = variable_get('theme_default', 'bartik');
1318
  return variable_get('rules_debug_region_' . $theme_key, variable_get('rules_debug_region_' . $theme_default, 'help'));
1319
}
1320

    
1321
/**
1322
 * Implements hook_page_build() to add the rules debug log to the page bottom.
1323
 */
1324
function rules_page_build(&$page) {
1325
  // Invoke a the page redirect, in case the action has been executed.
1326
  // @see rules_action_drupal_goto()
1327
  if (isset($GLOBALS['_rules_action_drupal_goto_do'])) {
1328
    list($url, $force) = $GLOBALS['_rules_action_drupal_goto_do'];
1329
    drupal_goto($url);
1330
  }
1331

    
1332
  if (isset($_SESSION['rules_debug'])) {
1333
    $region = rules_debug_log_region();
1334
    foreach ($_SESSION['rules_debug'] as $log) {
1335
      $page[$region]['rules_debug'][] = array(
1336
        '#markup' => $log,
1337
      );
1338
      $page[$region]['rules_debug']['#theme_wrappers'] = array('rules_log');
1339
    }
1340
    unset($_SESSION['rules_debug']);
1341
  }
1342

    
1343
  if (rules_show_debug_output()) {
1344
    $region = rules_debug_log_region();
1345
    $page[$region]['rules_debug']['#pre_render'] = array('rules_debug_log_pre_render');
1346
  }
1347
}
1348

    
1349
/**
1350
 * Pre-render callback for the debug log, which renders and then clears it.
1351
 */
1352
function rules_debug_log_pre_render($elements) {
1353
  $logger = RulesLog::logger();
1354
  if ($log = $logger->render()) {
1355
    $logger = RulesLog::logger();
1356
    $logger->clear();
1357
    $elements[] = array('#markup' => $log);
1358
    $elements['#theme_wrappers'] = array('rules_log');
1359
    // Log the rules log to the system log if enabled.
1360
    if (variable_get('rules_debug_log', FALSE)) {
1361
      watchdog('rules', 'Rules debug information: !log', array('!log' => $log), WATCHDOG_NOTICE);
1362
    }
1363
  }
1364
  return $elements;
1365
}
1366

    
1367
/**
1368
 * Implements hook_drupal_goto_alter().
1369
 *
1370
 * @see rules_action_drupal_goto()
1371
 */
1372
function rules_drupal_goto_alter(&$path, &$options, &$http_response_code) {
1373
  // Invoke a the page redirect, in case the action has been executed.
1374
  if (isset($GLOBALS['_rules_action_drupal_goto_do'])) {
1375
    list($url, $force) = $GLOBALS['_rules_action_drupal_goto_do'];
1376

    
1377
    if ($force || !isset($_GET['destination'])) {
1378
      $url = drupal_parse_url($url);
1379
      $path = $url['path'];
1380
      $options['query'] = $url['query'];
1381
      $options['fragment'] = $url['fragment'];
1382
      $http_response_code = 302;
1383
    }
1384
  }
1385
}
1386

    
1387
/**
1388
 * Returns whether the debug log should be shown.
1389
 */
1390
function rules_show_debug_output() {
1391
  if (variable_get('rules_debug', FALSE) == RulesLog::INFO && user_access('access rules debug')) {
1392
    return TRUE;
1393
  }
1394
  // For performance avoid unnecessary auto-loading of the RulesLog class.
1395
  return variable_get('rules_debug', FALSE) == RulesLog::WARN && user_access('access rules debug') && class_exists('RulesLog', FALSE) && RulesLog::logger()->hasErrors();
1396
}
1397

    
1398
/**
1399
 * Implements hook_exit().
1400
 */
1401
function rules_exit() {
1402
  // Bail out if this is cached request and modules are not loaded.
1403
  if (!module_exists('rules') || !module_exists('user')) {
1404
    return;
1405
  }
1406
  if (rules_show_debug_output()) {
1407
    if ($log = RulesLog::logger()->render()) {
1408
      // Keep the log in the session so we can show it on the next page.
1409
      $_SESSION['rules_debug'][] = $log;
1410
    }
1411
  }
1412
  // Log the rules log to the system log if enabled.
1413
  if (variable_get('rules_debug_log', FALSE) && $log = RulesLog::logger()->render()) {
1414
    watchdog('rules', 'Rules debug information: !log', array('!log' => $log), WATCHDOG_NOTICE);
1415
  }
1416
}
1417

    
1418
/**
1419
 * Implements hook_element_info().
1420
 */
1421
function rules_element_info() {
1422
  // A duration form element for rules. Needs ui.forms.inc included.
1423
  $types['rules_duration'] = array(
1424
    '#input' => TRUE,
1425
    '#tree' => TRUE,
1426
    '#default_value' => 0,
1427
    '#value_callback' => 'rules_ui_element_duration_value',
1428
    '#process' => array('rules_ui_element_duration_process', 'ajax_process_form'),
1429
    '#after_build' => array('rules_ui_element_duration_after_build'),
1430
    '#pre_render' => array('form_pre_render_conditional_form_element'),
1431
  );
1432
  $types['rules_data_selection'] = array(
1433
    '#input' => TRUE,
1434
    '#pre_render' => array('form_pre_render_conditional_form_element'),
1435
    '#process' => array('rules_data_selection_process', 'ajax_process_form'),
1436
    '#theme' => 'rules_autocomplete',
1437
  );
1438
  return $types;
1439
}
1440

    
1441
/**
1442
 * Implements hook_modules_enabled().
1443
 */
1444
function rules_modules_enabled($modules) {
1445
  // Re-enable Rules configurations that are dirty, because they require one of
1446
  // the enabled the modules.
1447
  $query = db_select('rules_dependencies', 'rd');
1448
  $query->join('rules_config', 'rc', 'rd.id = rc.id');
1449
  $query->fields('rd', array('id'))
1450
        ->condition('rd.module', $modules, 'IN')
1451
        ->condition('rc.dirty', 1);
1452
  $ids = $query->execute()->fetchCol();
1453

    
1454
  // If there are some configurations that might work again, re-check all dirty
1455
  // configurations as others might work again too, e.g. consider a rule that is
1456
  // dirty because it requires a dirty component.
1457
  if ($ids) {
1458
    $rules_configs = rules_config_load_multiple(FALSE, array('dirty' => 1));
1459
    foreach ($rules_configs as $rules_config) {
1460
      try {
1461
        $rules_config->integrityCheck();
1462
        // If no exceptions were thrown we can set the configuration back to OK.
1463
        db_update('rules_config')
1464
          ->fields(array('dirty' => 0))
1465
          ->condition('id', $rules_config->id)
1466
          ->execute();
1467
        if ($rules_config->active) {
1468
          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())));
1469
        }
1470
      }
1471
      catch (RulesIntegrityException $e) {
1472
        // The rule is still dirty, so do nothing.
1473
      }
1474
    }
1475
  }
1476
  rules_clear_cache();
1477
}
1478

    
1479
/**
1480
 * Implements hook_modules_disabled().
1481
 */
1482
function rules_modules_disabled($modules) {
1483
  // Disable Rules configurations that depend on one of the disabled modules.
1484
  $query = db_select('rules_dependencies', 'rd');
1485
  $query->join('rules_config', 'rc', 'rd.id = rc.id');
1486
  $query->fields('rd', array('id'))
1487
        ->distinct()
1488
        ->condition('rd.module', $modules, 'IN')
1489
        ->condition('rc.dirty', 0);
1490
  $ids = $query->execute()->fetchCol();
1491

    
1492
  if (!empty($ids)) {
1493
    db_update('rules_config')
1494
      ->fields(array('dirty' => 1))
1495
      ->condition('id', $ids, 'IN')
1496
      ->execute();
1497
    // Tell the user about enabled rules that have been marked as dirty.
1498
    $count = db_select('rules_config', 'r')
1499
      ->fields('r')
1500
      ->condition('id', $ids, 'IN')
1501
      ->condition('active', 1)
1502
      ->execute()->rowCount();
1503
    if ($count > 0) {
1504
      $message = format_plural($count,
1505
        '1 Rules configuration requires some of the disabled modules to function and cannot be executed any more.',
1506
        '@count Rules configuration require some of the disabled modules to function and cannot be executed any more.'
1507
      );
1508
      drupal_set_message($message, 'warning');
1509
    }
1510
  }
1511
  rules_clear_cache();
1512
}
1513

    
1514
/**
1515
 * Access callback for dealing with Rules configurations.
1516
 *
1517
 * @see entity_access()
1518
 */
1519
function rules_config_access($op, $rules_config = NULL, $account = NULL) {
1520
  if (user_access('bypass rules access', $account)) {
1521
    return TRUE;
1522
  }
1523
  // Allow modules to grant / deny access.
1524
  $access = module_invoke_all('rules_config_access', $op, $rules_config, $account);
1525

    
1526
  // Only grant access if at least one module granted access and no one denied
1527
  // access.
1528
  if (in_array(FALSE, $access, TRUE)) {
1529
    return FALSE;
1530
  }
1531
  elseif (in_array(TRUE, $access, TRUE)) {
1532
    return TRUE;
1533
  }
1534
  return FALSE;
1535
}
1536

    
1537
/**
1538
 * Implements hook_rules_config_access().
1539
 */
1540
function rules_rules_config_access($op, $rules_config = NULL, $account = NULL) {
1541
  // Instead of returning FALSE return nothing, so others still can grant
1542
  // access.
1543
  if (!isset($rules_config) || (isset($account) && $account->uid != $GLOBALS['user']->uid)) {
1544
    return;
1545
  }
1546
  if (user_access('administer rules', $account) && ($op == 'view' || $rules_config->access())) {
1547
    return TRUE;
1548
  }
1549
}
1550

    
1551
/**
1552
 * Implements hook_menu().
1553
 */
1554
function rules_menu() {
1555
  $items['admin/config/workflow/rules/upgrade'] = array(
1556
    'title' => 'Upgrade',
1557
    'page callback' => 'drupal_get_form',
1558
    'page arguments' => array('rules_upgrade_form'),
1559
    'access arguments' => array('administer rules'),
1560
    'file' => 'includes/rules.upgrade.inc',
1561
    'file path' => drupal_get_path('module', 'rules'),
1562
    'type' => MENU_CALLBACK,
1563
  );
1564
  $items['admin/config/workflow/rules/upgrade/clear'] = array(
1565
    'title' => 'Clear',
1566
    'page callback' => 'drupal_get_form',
1567
    'page arguments' => array('rules_upgrade_confirm_clear_form'),
1568
    'access arguments' => array('administer rules'),
1569
    'file' => 'includes/rules.upgrade.inc',
1570
    'file path' => drupal_get_path('module', 'rules'),
1571
    'type' => MENU_CALLBACK,
1572
  );
1573
  $items['admin/config/workflow/rules/autocomplete_tags'] = array(
1574
    'title' => 'Rules tags autocomplete',
1575
    'page callback' => 'rules_autocomplete_tags',
1576
    'page arguments' => array(5),
1577
    'access arguments' => array('administer rules'),
1578
    'file' => 'ui/ui.forms.inc',
1579
    'type' => MENU_CALLBACK,
1580
  );
1581
  return $items;
1582
}
1583

    
1584
/**
1585
 * Helper function to keep track of external documentation pages for Rules.
1586
 *
1587
 * @param $topic
1588
 *   The topic key for used for identifying help pages.
1589
 *
1590
 * @return
1591
 *   Either a URL for the given page, or the full list of external help pages.
1592
 */
1593
function rules_external_help($topic = NULL) {
1594
  $help = array(
1595
    'rules' =>                'http://drupal.org/node/298480',
1596
    'terminology' =>          'http://drupal.org/node/1299990',
1597
    'condition-components' => 'http://drupal.org/node/1300034',
1598
    'data-selection' =>       'http://drupal.org/node/1300042',
1599
    'chained-tokens' =>       'http://drupal.org/node/1300042',
1600
    'loops' =>                'http://drupal.org/node/1300058',
1601
    'components' =>           'http://drupal.org/node/1300024',
1602
    'component-types' =>      'http://drupal.org/node/1300024',
1603
    'variables' =>            'http://drupal.org/node/1300024',
1604
    'scheduler' =>            'http://drupal.org/node/1300068',
1605
    'coding' =>               'http://drupal.org/node/878720',
1606
  );
1607

    
1608
  if (isset($topic)) {
1609
    return isset($help[$topic]) ? $help[$topic] : FALSE;
1610
  }
1611
  return $help;
1612
}
1613

    
1614
/**
1615
 * Implements hook_help().
1616
 */
1617
function rules_help($path, $arg) {
1618
  // Only enable the help if the admin module is active.
1619
  if ($path == 'admin/help#rules' && module_exists('rules_admin')) {
1620

    
1621
    $output['header'] = array(
1622
      '#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!'),
1623
    );
1624
    // Build a list of essential Rules help pages, formatted as a bullet list.
1625
    $link_list['rules'] = l(t('Rules introduction'), rules_external_help('rules'));
1626
    $link_list['terminology'] = l(t('Rules terminology'), rules_external_help('terminology'));
1627
    $link_list['scheduler'] = l(t('Rules Scheduler'), rules_external_help('scheduler'));
1628
    $link_list['coding'] = l(t('Coding for Rules'), rules_external_help('coding'));
1629

    
1630
    $output['topic-list'] = array(
1631
      '#markup' => theme('item_list', array('items' => $link_list)),
1632
    );
1633
    return render($output);
1634
  }
1635
}
1636

    
1637
/**
1638
 * Implements hook_token_info().
1639
 */
1640
function rules_token_info() {
1641
  $cache = rules_get_cache();
1642
  $data_info = $cache['data_info'];
1643

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

    
1646
  foreach ($types as $type) {
1647
    $token_type = $data_info[$type]['token type'];
1648

    
1649
    $token_info['types'][$token_type] = array(
1650
      'name' => $data_info[$type]['label'],
1651
      'description' => t('Tokens related to %label Rules variables.', array('%label' => $data_info[$type]['label'])),
1652
      'needs-data' => $token_type,
1653
    );
1654
    $token_info['tokens'][$token_type]['value'] = array(
1655
      'name' => t("Value"),
1656
      'description' => t('The value of the variable.'),
1657
    );
1658
  }
1659
  return $token_info;
1660
}
1661

    
1662
/**
1663
 * Implements hook_tokens().
1664
 */
1665
function rules_tokens($type, $tokens, $data, $options = array()) {
1666
  // Handle replacements of primitive variable types.
1667
  if (substr($type, 0, 6) == 'rules_' && !empty($data[$type])) {
1668
    // Leverage entity tokens token processor by passing on as struct.
1669
    $info['property info']['value'] = array(
1670
      'type' => substr($type, 6),
1671
      'label' => '',
1672
    );
1673
    // Entity tokens uses metadata wrappers as values for 'struct' types.
1674
    $wrapper = entity_metadata_wrapper('struct', array('value' => $data[$type]), $info);
1675
    return entity_token_tokens('struct', $tokens, array('struct' => $wrapper), $options);
1676
  }
1677
}
1678

    
1679
/**
1680
 * Helper function that retrieves a metadata wrapper with all properties.
1681
 *
1682
 * Note that without this helper, bundle-specific properties aren't added.
1683
 */
1684
function rules_get_entity_metadata_wrapper_all_properties(RulesAbstractPlugin $element) {
1685
  return entity_metadata_wrapper($element->settings['type'], NULL, array(
1686
    'property info alter' => 'rules_entity_metadata_wrapper_all_properties_callback',
1687
  ));
1688
}
1689

    
1690
/**
1691
 * Callback that returns a metadata wrapper with all properties.
1692
 */
1693
function rules_entity_metadata_wrapper_all_properties_callback(EntityMetadataWrapper $wrapper, $property_info) {
1694
  $info = $wrapper->info();
1695
  $properties = entity_get_all_property_info($info['type']);
1696
  $property_info['properties'] += $properties;
1697
  return $property_info;
1698
}
1699

    
1700
/**
1701
 * Helper to enable or disable the invocation of rules events.
1702
 *
1703
 * Rules invocation is disabled by default, such that Rules does not operate
1704
 * when Drupal is not fully bootstrapped. It gets enabled in rules_init() and
1705
 * rules_enable().
1706
 *
1707
 * @param bool|NULL $enable
1708
 *   NULL to leave the setting as is and TRUE / FALSE to change the behaviour.
1709
 *
1710
 * @return bool
1711
 *   Whether the rules invocation is enabled or disabled.
1712
 */
1713
function rules_event_invocation_enabled($enable = NULL) {
1714
  static $invocation_enabled = FALSE;
1715
  if (isset($enable)) {
1716
    $invocation_enabled = (bool) $enable;
1717
  }
1718
  // Disable invocation if configured or if site runs in maintenance mode.
1719
  return $invocation_enabled && !defined('MAINTENANCE_MODE');
1720
}