Projet

Général

Profil

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

root / drupal7 / sites / all / modules / rules / rules.module @ 76df55b7

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_module_implements_alter().
13
 */
14
function rules_module_implements_alter(&$implementations, $hook) {
15
  // Ensures the invocation of hook_menu_get_item_alter() triggers
16
  // rules_menu_get_item_alter() first so the rules invocation is ready for all
17
  // sub-sequent hook implementations.
18
  if ($hook == 'menu_get_item_alter' && array_key_exists('rules', $implementations)) {
19
    $group = $implementations['rules'];
20
    unset($implementations['rules']);
21
    $implementations = array_merge(array('rules' => $group), $implementations);
22
  }
23
}
24

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

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

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

    
69
/**
70
 * Returns a new rules action.
71
 *
72
 * @param $name
73
 *   The action's name.
74
 * @param $settings
75
 *   The action's settings array.
76
 * @return RulesAction
77
 */
78
function rules_action($name, $settings = array()) {
79
  return rules_plugin_factory('action', $name, $settings);
80
}
81

    
82
/**
83
 * Returns a new rules condition.
84
 *
85
 * @param $name
86
 *   The condition's name.
87
 * @param $settings
88
 *   The condition's settings array.
89
 * @return RulesCondition
90
 */
91
function rules_condition($name, $settings = array()) {
92
  return rules_plugin_factory('condition', $name, $settings);
93
}
94

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

    
122
/**
123
 * Creates a new reaction rule.
124
 *
125
 * @return RulesReactionRule
126
 */
127
function rules_reaction_rule() {
128
  return rules_plugin_factory('reaction rule');
129
}
130

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

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

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

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

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

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

    
213
  // Statically cache the variable settings as this is called very often.
214
  if (!isset($settings)) {
215
    $settings['rules_log_errors'] = variable_get('rules_log_errors', RulesLog::WARN);
216
    $settings['rules_debug_log'] = variable_get('rules_debug_log', FALSE);
217
    $settings['rules_debug'] = variable_get('rules_debug', FALSE);
218
  }
219

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

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

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

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

    
307
  $items = array();
308
  foreach (get_declared_classes() as $plugin_class) {
309
    if (is_subclass_of($plugin_class, $class) && method_exists($plugin_class, 'getInfo')) {
310
      $info = call_user_func(array($plugin_class, 'getInfo'));
311
      $info['class'] = $plugin_class;
312
      $info['module'] = _rules_discover_module($plugin_class);
313
      $items[$info['name']] = $info;
314
    }
315
  }
316
  return $items;
317
}
318

    
319
/**
320
 * Determines the module providing the given class.
321
 */
322
function _rules_discover_module($class) {
323
  $paths = &drupal_static(__FUNCTION__);
324

    
325
  if (!isset($paths)) {
326
    // Build up a map of modules keyed by their directory.
327
    foreach (system_list('module_enabled') as $name => $module_info) {
328
      $paths[dirname($module_info->filename)] = $name;
329
    }
330
  }
331

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

    
338
  // Go up the path until we match a module up.
339
  $parts = explode('/', $path);
340
  while (!isset($paths[$path]) && array_pop($parts)) {
341
    $path = dirname($path);
342
  }
343
  return isset($paths[$path]) ? $paths[$path] : FALSE;
344
}
345

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

    
357
  if (!isset($cache[$cid])) {
358
    // The main 'data' cache includes translated strings, so each language is
359
    // cached separately.
360
    $cid_suffix = $cid == 'data' ? ':' . $GLOBALS['language']->language : '';
361

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

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

    
430
/**
431
 * Cache components to allow efficient usage via rules_invoke_component().
432
 *
433
 * @see rules_invoke_component()
434
 * @see rules_get_cache()
435
 */
436
function _rules_rebuild_component_cache() {
437
  $components = rules_get_components();
438

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

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

    
472
/**
473
 * Implements hook_flush_caches().
474
 */
475
function rules_flush_caches() {
476
  return array('cache_rules');
477
}
478

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

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

    
502

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

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

    
577
      try {
578
        if (!($info[$key]['allow null'] && $info[$key]['wrapped'])) {
579
          $value = $entry->value($options);
580

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1002
  return $return;
1003
}
1004

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

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

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

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

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

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

    
1144
/**
1145
 * Returns the first key of the array.
1146
 */
1147
function rules_array_key($array) {
1148
  reset($array);
1149
  return key($array);
1150
}
1151

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

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

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

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

    
1247
  return $perms;
1248
}
1249

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

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

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

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

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

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

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

    
1339
  if (rules_show_debug_output()) {
1340
    $region = rules_debug_log_region();
1341
    $page[$region]['rules_debug']['#pre_render'] = array('rules_debug_log_pre_render');
1342
  }
1343
}
1344

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

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

    
1373
    if ($force || !isset($_GET['destination'])) {
1374
      $url = drupal_parse_url($url);
1375
      $path = $url['path'];
1376
      $options['query'] = $url['query'];
1377
      $options['fragment'] = $url['fragment'];
1378
      $http_response_code = 302;
1379
    }
1380
  }
1381
}
1382

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

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

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

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

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

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

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

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

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

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

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

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

    
1604
  if (isset($topic)) {
1605
    return isset($help[$topic]) ? $help[$topic] : FALSE;
1606
  }
1607
  return $help;
1608
}
1609

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

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

    
1626
    $output['topic-list'] = array(
1627
      '#markup' => theme('item_list', array('items' => $link_list)),
1628
    );
1629
    return render($output);
1630
  }
1631
}
1632

    
1633
/**
1634
 * Implements hook_token_info().
1635
 */
1636
function rules_token_info() {
1637
  $cache = rules_get_cache();
1638
  $data_info = $cache['data_info'];
1639

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

    
1642
  foreach ($types as $type) {
1643
    $token_type = $data_info[$type]['token type'];
1644

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

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

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

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

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