Projet

Général

Profil

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

root / drupal7 / sites / all / modules / rules / rules.module @ 950416da

1
<?php
2

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

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

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

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

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

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

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

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

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

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

    
132
/**
133
 * Creates a new reaction rule.
134
 *
135
 * @return RulesReactionRule
136
 */
137
function rules_reaction_rule() {
138
  return rules_plugin_factory('reaction rule');
139
}
140

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

    
153
/**
154
 * Creates a logical AND condition container.
155
 *
156
 * @param array $variables
157
 *   An optional array as for rule().
158
 *
159
 * @return RulesAnd
160
 */
161
function rules_and($variables = NULL) {
162
  return rules_plugin_factory('and', $variables);
163
}
164

    
165
/**
166
 * Creates a loop.
167
 *
168
 * @param array $settings
169
 *   The loop settings, containing
170
 *     'list:select': The data selector for the list to loop over.
171
 *     'item:var': Optionally a name for the list item variable.
172
 *     'item:label': Optionally a label for the list item variable.
173
 * @param array $variables
174
 *   An optional array as for rule().
175
 *
176
 * @return RulesLoop
177
 */
178
function rules_loop($settings = array(), $variables = NULL) {
179
  return rules_plugin_factory('loop', $settings, $variables);
180
}
181

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

    
196
/**
197
 * Creates an action set.
198
 *
199
 * @param array $variables
200
 *   An array as for rule().
201
 * @param array $provides
202
 *   The names of variables which should be provided to the caller. See rule().
203
 *
204
 * @return RulesActionSet
205
 */
206
function rules_action_set($variables = array(), $provides = array()) {
207
  return rules_plugin_factory('action set', $variables, $provides);
208
}
209

    
210
/**
211
 * Log a message to the rules logger.
212
 *
213
 * @param $msg
214
 *   The message to log.
215
 * @param array $args
216
 *   An array of placeholder arguments as used by t().
217
 * @param $priority
218
 *   A priority as defined by the RulesLog class.
219
 * @param RulesPlugin $element
220
 *   (optional) The RulesElement causing the log entry.
221
 * @param bool $scope
222
 *   (optional) This may be used to denote the beginning (TRUE) or the end
223
 *   (FALSE) of a new execution scope.
224
 */
225
function rules_log($msg, $args = array(), $priority = RulesLog::INFO, RulesPlugin $element = NULL, $scope = NULL) {
226
  static $logger, $settings;
227

    
228
  // Statically cache the variable settings as this is called very often.
229
  if (!isset($settings)) {
230
    $settings['rules_log_errors'] = variable_get('rules_log_errors', RulesLog::WARN);
231
    $settings['rules_debug_log'] = variable_get('rules_debug_log', FALSE);
232
    $settings['rules_debug'] = variable_get('rules_debug', FALSE);
233
  }
234

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

    
257
/**
258
 * Fetches module definitions for the given hook name.
259
 *
260
 * Used for collecting events, rules, actions and condition from other modules.
261
 *
262
 * @param $hook
263
 *   The hook of the definitions to get from invoking hook_rules_{$hook}.
264
 */
265
function rules_fetch_data($hook) {
266
  $data = &drupal_static(__FUNCTION__, array());
267
  static $discover = array(
268
    'action_info' => 'RulesActionHandlerInterface',
269
    'condition_info' => 'RulesConditionHandlerInterface',
270
    'event_info' => 'RulesEventHandlerInterface',
271
  );
272

    
273
  if (!isset($data[$hook])) {
274
    $data[$hook] = array();
275
    foreach (module_implements('rules_' . $hook) as $module) {
276
      $result = call_user_func($module . '_rules_' . $hook);
277
      if (isset($result) && is_array($result)) {
278
        foreach ($result as $name => $item) {
279
          $item += array('module' => $module);
280
          $data[$hook][$name] = $item;
281
        }
282
      }
283
    }
284
    // Support class discovery.
285
    if (isset($discover[$hook])) {
286
      $data[$hook] += rules_discover_plugins($discover[$hook]);
287
    }
288
    drupal_alter('rules_' . $hook, $data[$hook]);
289
  }
290
  return $data[$hook];
291
}
292

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

    
322
  $items = array();
323
  foreach (get_declared_classes() as $plugin_class) {
324
    if (is_subclass_of($plugin_class, $class) && method_exists($plugin_class, 'getInfo')) {
325
      $info = call_user_func(array($plugin_class, 'getInfo'));
326
      $info['class'] = $plugin_class;
327
      $info['module'] = _rules_discover_module($plugin_class);
328
      $items[$info['name']] = $info;
329
    }
330
  }
331
  return $items;
332
}
333

    
334
/**
335
 * Determines the module providing the given class.
336
 *
337
 * @param string $class
338
 *   The name of the class or interface plugins to discover.
339
 *
340
 * @return string|false
341
 *   The path of the class, relative to the Drupal installation root,
342
 *   or FALSE if not discovered.
343
 */
344
function _rules_discover_module($class) {
345
  $paths = &drupal_static(__FUNCTION__);
346

    
347
  if (!isset($paths)) {
348
    // Build up a map of modules keyed by their directory.
349
    foreach (system_list('module_enabled') as $name => $module_info) {
350
      $paths[dirname($module_info->filename)] = $name;
351
    }
352
  }
353

    
354
  // Retrieve the class file and convert its absolute path to a regular Drupal
355
  // path relative to the installation root.
356
  $reflection = new ReflectionClass($class);
357
  $path = str_replace(realpath(DRUPAL_ROOT) . DIRECTORY_SEPARATOR, '', realpath(dirname($reflection->getFileName())));
358
  $path = DIRECTORY_SEPARATOR != '/' ? str_replace(DIRECTORY_SEPARATOR, '/', $path) : $path;
359

    
360
  // Go up the path until we match a module.
361
  $parts = explode('/', $path);
362
  while (!isset($paths[$path]) && array_pop($parts)) {
363
    $path = dirname($path);
364
  }
365
  return isset($paths[$path]) ? $paths[$path] : FALSE;
366
}
367

    
368
/**
369
 * Gets a rules cache entry.
370
 */
371
function &rules_get_cache($cid = 'data') {
372
  // Make use of the fast, advanced drupal static pattern.
373
  static $drupal_static_fast;
374
  if (!isset($drupal_static_fast)) {
375
    $drupal_static_fast['cache'] = &drupal_static(__FUNCTION__, array());
376
  }
377
  $cache = &$drupal_static_fast['cache'];
378

    
379
  if (!isset($cache[$cid])) {
380
    // The main 'data' cache includes translated strings, so each language is
381
    // cached separately.
382
    $cid_suffix = $cid == 'data' ? ':' . $GLOBALS['language']->language : '';
383

    
384
    if ($get = cache_get($cid . $cid_suffix, 'cache_rules')) {
385
      $cache[$cid] = $get->data;
386
    }
387
    else {
388
      // Prevent stampeding by ensuring the cache is rebuilt just once at the
389
      // same time.
390
      while (!lock_acquire(__FUNCTION__ . $cid . $cid_suffix, 60)) {
391
        // Now wait until the lock is released.
392
        lock_wait(__FUNCTION__ . $cid . $cid_suffix, 30);
393
        // If the lock is released it's likely the cache was rebuild. Thus check
394
        // again if we can fetch it from the persistent cache.
395
        if ($get = cache_get($cid . $cid_suffix, 'cache_rules')) {
396
          $cache[$cid] = $get->data;
397
          return $cache[$cid];
398
        }
399
      }
400
      if ($cid === 'data') {
401
        // There is no 'data' cache so we need to rebuild it. Make sure
402
        // subsequent cache gets of the main 'data' cache during rebuild get
403
        // the interim cache by passing in the reference of the static cache
404
        // variable.
405
        _rules_rebuild_cache($cache['data']);
406
      }
407
      elseif (strpos($cid, 'comp_') === 0) {
408
        $cache[$cid] = FALSE;
409
        _rules_rebuild_component_cache();
410
      }
411
      elseif (strpos($cid, 'event_') === 0 || $cid == 'rules_event_whitelist') {
412
        $cache[$cid] = FALSE;
413
        RulesEventSet::rebuildEventCache();
414
      }
415
      else {
416
        $cache[$cid] = FALSE;
417
      }
418
      // Ensure a set lock is released.
419
      lock_release(__FUNCTION__ . $cid . $cid_suffix);
420
    }
421
  }
422
  return $cache[$cid];
423
}
424

    
425
/**
426
 * Rebuilds the rules cache.
427
 *
428
 * This rebuilds the rules 'data' cache and invokes rebuildCache() methods on
429
 * all plugin classes, which allows plugins to add their own data to the cache.
430
 * The cache is rebuilt in the order the plugins are defined.
431
 *
432
 * Note that building the action/condition info cache triggers loading of all
433
 * components, thus depends on entity-loading and so syncing entities in code
434
 * to the database.
435
 *
436
 * @see rules_rules_plugin_info()
437
 * @see entity_defaults_rebuild()
438
 */
439
function _rules_rebuild_cache(&$cache) {
440
  foreach (array('data_info', 'plugin_info') as $hook) {
441
    $cache[$hook] = rules_fetch_data($hook);
442
  }
443
  foreach ($cache['plugin_info'] as $name => &$info) {
444
    // Let the items add something to the cache.
445
    $item = new $info['class']();
446
    $item->rebuildCache($info, $cache);
447
  }
448
  $cid_suffix = ':' . $GLOBALS['language']->language;
449
  cache_set('data' . $cid_suffix, $cache, 'cache_rules');
450
}
451

    
452
/**
453
 * Cache components to allow efficient usage via rules_invoke_component().
454
 *
455
 * @see rules_invoke_component()
456
 * @see rules_get_cache()
457
 */
458
function _rules_rebuild_component_cache() {
459
  $components = rules_get_components();
460

    
461
  foreach ($components as $id => $component) {
462
    // If a component is marked as dirty, check if this still applies.
463
    if ($component->dirty) {
464
      rules_config_update_dirty_flag($component);
465
    }
466
    if (!$component->dirty) {
467
      // Clone the component to avoid modules getting the to be cached
468
      // version from the static loading cache.
469
      $component = clone $component;
470
      $component->optimize();
471
      // Allow modules to alter the cached component.
472
      drupal_alter('rules_component', $component->plugin, $component);
473
      rules_set_cache('comp_' . $component->name, $component);
474
    }
475
  }
476
}
477

    
478
/**
479
 * Sets a rules cache item.
480
 *
481
 * In addition to calling cache_set(), this function makes sure the cache item
482
 * is immediately available via rules_get_cache() by keeping all cache items
483
 * in memory. That way we can guarantee rules_get_cache() is able to retrieve
484
 * any cache item, even if all cache gets fail.
485
 *
486
 * @see rules_get_cache()
487
 */
488
function rules_set_cache($cid, $data) {
489
  $cache = &drupal_static('rules_get_cache', array());
490
  $cache[$cid] = $data;
491
  cache_set($cid, $data, 'cache_rules');
492
}
493

    
494
/**
495
 * Implements hook_flush_caches().
496
 */
497
function rules_flush_caches() {
498
  return array('cache_rules');
499
}
500

    
501
/**
502
 * Clears the rule set cache.
503
 */
504
function rules_clear_cache() {
505
  cache_clear_all('*', 'cache_rules', TRUE);
506
  drupal_static_reset('rules_get_cache');
507
  drupal_static_reset('rules_fetch_data');
508
  drupal_static_reset('rules_config_update_dirty_flag');
509
  entity_get_controller('rules_config')->resetCache();
510
}
511

    
512
/**
513
 * Imports the given export and returns the imported configuration.
514
 *
515
 * @param string $export
516
 *   A serialized string in JSON format as produced by the RulesPlugin::export()
517
 *   method, or the PHP export as usual PHP array.
518
 * @param string $error_msg
519
 *
520
 * @return RulesPlugin
521
 */
522
function rules_import($export, &$error_msg = '') {
523
  return entity_get_controller('rules_config')->import($export, $error_msg);
524
}
525

    
526
/**
527
 * Wraps the given data.
528
 *
529
 * @param $data
530
 *   If available, the actual data, else NULL.
531
 * @param $info
532
 *   An array of info about this data.
533
 * @param bool $force
534
 *   Usually data is only wrapped if really needed. If set to TRUE, wrapping the
535
 *   data is forced, so primitive data types are also wrapped.
536
 *
537
 * @return EntityMetadataWrapper
538
 *   An EntityMetadataWrapper or the unwrapped data.
539
 *
540
 * @see hook_rules_data_info()
541
 */
542
function &rules_wrap_data($data = NULL, $info, $force = FALSE) {
543
  // If the data is already wrapped, use the existing wrapper.
544
  if ($data instanceof EntityMetadataWrapper) {
545
    return $data;
546
  }
547
  $cache = rules_get_cache();
548
  // Define the keys to be passed through to the metadata wrapper.
549
  $wrapper_keys = array_flip(array('property info', 'property defaults'));
550
  if (isset($cache['data_info'][$info['type']])) {
551
    $info += array_intersect_key($cache['data_info'][$info['type']], $wrapper_keys);
552
  }
553
  // If a list is given, also add in the info of the item type.
554
  $list_item_type = entity_property_list_extract_type($info['type']);
555
  if ($list_item_type && isset($cache['data_info'][$list_item_type])) {
556
    $info += array_intersect_key($cache['data_info'][$list_item_type], $wrapper_keys);
557
  }
558
  // By default we do not wrap the data, except for completely unknown types.
559
  if (!empty($cache['data_info'][$info['type']]['wrap']) || $list_item_type || $force || empty($cache['data_info'][$info['type']])) {
560
    unset($info['handler']);
561
    // Allow data types to define custom wrapper classes.
562
    if (!empty($cache['data_info'][$info['type']]['wrapper class'])) {
563
      $class = $cache['data_info'][$info['type']]['wrapper class'];
564
      $wrapper = new $class($info['type'], $data, $info);
565
    }
566
    else {
567
      $wrapper = entity_metadata_wrapper($info['type'], $data, $info);
568
    }
569
    return $wrapper;
570
  }
571
  return $data;
572
}
573

    
574
/**
575
 * Unwraps the given data, if it's wrapped.
576
 *
577
 * @param array $data
578
 *   An array of wrapped data.
579
 * @param array $info
580
 *   Optionally an array of info about how to unwrap the data. Keyed as $data.
581
 *
582
 * @return array
583
 *   An array containing unwrapped or passed through data.
584
 */
585
function rules_unwrap_data(array $data, $info = array()) {
586
  $cache = rules_get_cache();
587
  foreach ($data as $key => $entry) {
588
    // If it's a wrapper, unwrap unless specified otherwise.
589
    if ($entry instanceof EntityMetadataWrapper) {
590
      if (!isset($info[$key]['allow null'])) {
591
        $info[$key]['allow null'] = FALSE;
592
      }
593
      if (!isset($info[$key]['wrapped'])) {
594
        // By default, do not unwrap special data types that are always wrapped.
595
        $info[$key]['wrapped'] = (isset($info[$key]['type']) && is_string($info[$key]['type']) && !empty($cache['data_info'][$info[$key]['type']]['is wrapped']));
596
      }
597
      // Activate the decode option by default if 'sanitize' is not enabled, so
598
      // any text is either sanitized or decoded.
599
      // @see EntityMetadataWrapper::value()
600
      $options = $info[$key] + array('decode' => empty($info[$key]['sanitize']));
601

    
602
      try {
603
        if (!($info[$key]['allow null'] && $info[$key]['wrapped'])) {
604
          $value = $entry->value($options);
605

    
606
          if (!$info[$key]['wrapped']) {
607
            $data[$key] = $value;
608
          }
609
          if (!$info[$key]['allow null'] && !isset($value)) {
610
            throw new RulesEvaluationException('The variable or parameter %name is empty.', array('%name' => $key));
611
          }
612
        }
613
      }
614
      catch (EntityMetadataWrapperException $e) {
615
        throw new RulesEvaluationException('Unable to get the data value for the variable or parameter %name. Error: !error', array('%name' => $key, '!error' => $e->getMessage()));
616
      }
617
    }
618
  }
619
  return $data;
620
}
621

    
622
/**
623
 * Gets event info for a given event.
624
 *
625
 * @param string $event_name
626
 *   A (configured) event name.
627
 *
628
 * @return array
629
 *   An array of event info. If the event is unknown, a suiting info array is
630
 *   generated and returned
631
 */
632
function rules_get_event_info($event_name) {
633
  $base_event_name = rules_get_event_base_name($event_name);
634
  $events = rules_fetch_data('event_info');
635
  if (isset($events[$base_event_name])) {
636
    return $events[$base_event_name] + array('name' => $base_event_name);
637
  }
638
  return array(
639
    'label' => t('Unknown event "!event_name"', array('!event_name' => $base_event_name)),
640
    'name' => $base_event_name,
641
  );
642
}
643

    
644
/**
645
 * Returns the base name of a configured event name.
646
 *
647
 * For a configured event name like node_view--article the base event name
648
 * node_view is returned.
649
 *
650
 * @param string $event_name
651
 *   A (configured) event name.
652
 *
653
 * @return string
654
 *   The event base name.
655
 */
656
function rules_get_event_base_name($event_name) {
657
  // Cut off any suffix from a configured event name.
658
  if (strpos($event_name, '--') !== FALSE) {
659
    $parts = explode('--', $event_name, 2);
660
    return $parts[0];
661
  }
662
  return $event_name;
663
}
664

    
665
/**
666
 * Returns the rule event handler for the given event.
667
 *
668
 * Events having no settings are handled via the class RulesEventSettingsNone.
669
 *
670
 * @param string $event_name
671
 *   The event name (base or configured).
672
 * @param array $settings
673
 *   (optional) An array of event settings to set on the handler.
674
 *
675
 * @return RulesEventHandlerInterface
676
 *   The event handler.
677
 */
678
function rules_get_event_handler($event_name, array $settings = NULL) {
679
  $event_name = rules_get_event_base_name($event_name);
680
  $event_info = rules_get_event_info($event_name);
681
  $class = !empty($event_info['class']) ? $event_info['class'] : 'RulesEventDefaultHandler';
682
  $handler = new $class($event_name, $event_info);
683
  return isset($settings) ? $handler->setSettings($settings) : $handler;
684
}
685

    
686
/**
687
 * Creates a new instance of a the given rules plugin.
688
 *
689
 * @return RulesPlugin
690
 */
691
function rules_plugin_factory($plugin_name, $arg1 = NULL, $arg2 = NULL) {
692
  $cache = rules_get_cache();
693
  if (isset($cache['plugin_info'][$plugin_name]['class'])) {
694
    return new $cache['plugin_info'][$plugin_name]['class']($arg1, $arg2);
695
  }
696
}
697

    
698
/**
699
 * Implements hook_rules_plugin_info().
700
 *
701
 * Note that the cache is rebuilt in the order of the plugins. Therefore the
702
 * condition and action plugins must be at the top, so that any components
703
 * re-building their cache can create configurations including properly setup-ed
704
 * actions and conditions.
705
 */
706
function rules_rules_plugin_info() {
707
  return array(
708
    'condition' => array(
709
      'class' => 'RulesCondition',
710
      'embeddable' => 'RulesConditionContainer',
711
      'extenders' => array(
712
        'RulesPluginImplInterface' => array(
713
          'class' => 'RulesAbstractPluginDefaults',
714
        ),
715
        'RulesPluginFeaturesIntegrationInterface' => array(
716
          'methods' => array(
717
            'features_export' => 'rules_features_abstract_default_features_export',
718
          ),
719
        ),
720
        'RulesPluginUIInterface' => array(
721
          'class' => 'RulesAbstractPluginUI',
722
        ),
723
      ),
724
    ),
725
    'action' => array(
726
      'class' => 'RulesAction',
727
      'embeddable' => 'RulesActionContainer',
728
      'extenders' => array(
729
        'RulesPluginImplInterface' => array(
730
          'class' => 'RulesAbstractPluginDefaults',
731
        ),
732
        'RulesPluginFeaturesIntegrationInterface' => array(
733
          'methods' => array(
734
            'features_export' => 'rules_features_abstract_default_features_export',
735
          ),
736
        ),
737
        'RulesPluginUIInterface' => array(
738
          'class' => 'RulesAbstractPluginUI',
739
        ),
740
      ),
741
    ),
742
    'or' => array(
743
      'label' => t('Condition set (OR)'),
744
      'class' => 'RulesOr',
745
      'embeddable' => 'RulesConditionContainer',
746
      'component' => TRUE,
747
      'extenders' => array(
748
        'RulesPluginUIInterface' => array(
749
          'class' => 'RulesConditionContainerUI',
750
        ),
751
      ),
752
    ),
753
    'and' => array(
754
      'label' => t('Condition set (AND)'),
755
      'class' => 'RulesAnd',
756
      'embeddable' => 'RulesConditionContainer',
757
      'component' => TRUE,
758
      'extenders' => array(
759
        'RulesPluginUIInterface' => array(
760
          'class' => 'RulesConditionContainerUI',
761
        ),
762
      ),
763
    ),
764
    'action set' => array(
765
      'label' => t('Action set'),
766
      'class' => 'RulesActionSet',
767
      'embeddable' => FALSE,
768
      'component' => TRUE,
769
      'extenders' => array(
770
        'RulesPluginUIInterface' => array(
771
          'class' => 'RulesActionContainerUI',
772
        ),
773
      ),
774
    ),
775
    'rule' => array(
776
      'label' => t('Rule'),
777
      'class' => 'Rule',
778
      'embeddable' => 'RulesRuleSet',
779
      'component' => TRUE,
780
      'extenders' => array(
781
        'RulesPluginUIInterface' => array(
782
          'class' => 'RulesRuleUI',
783
        ),
784
      ),
785
    ),
786
    'loop' => array(
787
      'class' => 'RulesLoop',
788
      'embeddable' => 'RulesActionContainer',
789
      'extenders' => array(
790
        'RulesPluginUIInterface' => array(
791
          'class' => 'RulesLoopUI',
792
        ),
793
      ),
794
    ),
795
    'reaction rule' => array(
796
      'class' => 'RulesReactionRule',
797
      'embeddable' => FALSE,
798
      'extenders' => array(
799
        'RulesPluginUIInterface' => array(
800
          'class' => 'RulesReactionRuleUI',
801
        ),
802
      ),
803
    ),
804
    'event set' => array(
805
      'class' => 'RulesEventSet',
806
      'embeddable' => FALSE,
807
    ),
808
    'rule set' => array(
809
      'label' => t('Rule set'),
810
      'class' => 'RulesRuleSet',
811
      'component' => TRUE,
812
      // Rule sets don't get embedded - we use a separate action to execute.
813
      'embeddable' => FALSE,
814
      'extenders' => array(
815
        'RulesPluginUIInterface' => array(
816
          'class' => 'RulesRuleSetUI',
817
        ),
818
      ),
819
    ),
820
  );
821
}
822

    
823
/**
824
 * Implements hook_entity_info().
825
 */
826
function rules_entity_info() {
827
  return array(
828
    'rules_config' => array(
829
      'label' => t('Rules configuration'),
830
      'controller class' => 'RulesEntityController',
831
      'base table' => 'rules_config',
832
      'fieldable' => TRUE,
833
      'entity keys' => array(
834
        'id' => 'id',
835
        'name' => 'name',
836
        'label' => 'label',
837
      ),
838
      'module' => 'rules',
839
      'static cache' => TRUE,
840
      'bundles' => array(),
841
      'configuration' => TRUE,
842
      'exportable' => TRUE,
843
      'export' => array(
844
        'default hook' => 'default_rules_configuration',
845
      ),
846
      'access callback' => 'rules_config_access',
847
      'features controller class' => 'RulesFeaturesController',
848
    ),
849
  );
850
}
851

    
852
/**
853
 * Implements hook_hook_info().
854
 */
855
function rules_hook_info() {
856
  foreach (array('plugin_info', 'rules_directory', 'data_info', 'condition_info', 'action_info', 'event_info', 'file_info', 'evaluator_info', 'data_processor_info') as $hook) {
857
    $hooks['rules_' . $hook] = array(
858
      'group' => 'rules',
859
    );
860
    $hooks['rules_' . $hook . '_alter'] = array(
861
      'group' => 'rules',
862
    );
863
  }
864
  $hooks['default_rules_configuration'] = array(
865
    'group' => 'rules_defaults',
866
  );
867
  $hooks['default_rules_configuration_alter'] = array(
868
    'group' => 'rules_defaults',
869
  );
870
  return $hooks;
871
}
872

    
873
/**
874
 * Load rule configurations from the database.
875
 *
876
 * This function should be used whenever you need to load more than one entity
877
 * from the database. The entities are loaded into memory and will not require
878
 * database access if loaded again during the same page request.
879
 *
880
 * @see hook_entity_info()
881
 * @see RulesEntityController
882
 *
883
 * @param array|false $names
884
 *   An array of rules configuration names or FALSE to load all.
885
 * @param array $conditions
886
 *   An array of conditions in the form 'field' => $value.
887
 *
888
 * @return array
889
 *   An array of rule configurations indexed by their ids.
890
 */
891
function rules_config_load_multiple($names = array(), $conditions = array()) {
892
  return entity_load_multiple_by_name('rules_config', $names, $conditions);
893
}
894

    
895
/**
896
 * Loads a single rule configuration from the database.
897
 *
898
 * @see rules_config_load_multiple()
899
 *
900
 * @return RulesPlugin
901
 */
902
function rules_config_load($name) {
903
  return entity_load_single('rules_config', $name);
904
}
905

    
906
/**
907
 * Returns an array of configured components.
908
 *
909
 * For actually executing a component use rules_invoke_component(), as this
910
 * retrieves the component from cache instead.
911
 *
912
 * @param $label
913
 *   Whether to return only the label or the whole component object.
914
 * @param $type
915
 *   Optionally filter for 'action' or 'condition' components.
916
 * @param array $conditions
917
 *   An array of additional conditions as required by rules_config_load().
918
 *
919
 * @return array
920
 *   An array keyed by component name containing either the label or the config.
921
 */
922
function rules_get_components($label = FALSE, $type = NULL, $conditions = array()) {
923
  $cache = rules_get_cache();
924
  $plugins = array_keys(rules_filter_array($cache['plugin_info'], 'component', TRUE));
925
  $conditions = $conditions + array('plugin' => $plugins);
926
  $faces = array(
927
    'action' => 'RulesActionInterface',
928
    'condition' => 'RulesConditionInterface',
929
  );
930
  $items = array();
931
  foreach (rules_config_load_multiple(FALSE, $conditions) as $name => $config) {
932
    if (!isset($type) || $config instanceof $faces[$type]) {
933
      $items[$name] = $label ? $config->label() : $config;
934
    }
935
  }
936
  return $items;
937
}
938

    
939
/**
940
 * Delete rule configurations from database.
941
 *
942
 * @param array $ids
943
 *   An array of entity IDs.
944
 */
945
function rules_config_delete(array $ids) {
946
  return entity_get_controller('rules_config')->delete($ids);
947
}
948

    
949
/**
950
 * Ensures the configuration's 'dirty' flag is up to date by running an integrity check.
951
 *
952
 * @param bool $update
953
 *   (optional) Whether the dirty flag is also updated in the database if
954
 *   necessary. Defaults to TRUE.
955
 */
956
function rules_config_update_dirty_flag($rules_config, $update = TRUE) {
957
  // Keep a log of already check configurations to avoid repetitive checks on
958
  // often used components.
959
  // @see rules_element_invoke_component_validate()
960
  $checked = &drupal_static(__FUNCTION__, array());
961
  if (!empty($checked[$rules_config->name])) {
962
    return;
963
  }
964
  $checked[$rules_config->name] = TRUE;
965

    
966
  $was_dirty = !empty($rules_config->dirty);
967
  try {
968
    // First set the rule to dirty, so any repetitive checks give green light
969
    // for this configuration.
970
    $rules_config->dirty = FALSE;
971
    $rules_config->integrityCheck();
972
    if ($was_dirty) {
973
      $variables = array('%label' => $rules_config->label(), '%name' => $rules_config->name, '@plugin' => $rules_config->plugin());
974
      watchdog('rules', 'The @plugin %label (%name) was marked dirty, but passes the integrity check now and is active again.', $variables, WATCHDOG_INFO);
975
    }
976
  }
977
  catch (RulesIntegrityException $e) {
978
    $rules_config->dirty = TRUE;
979
    if (!$was_dirty) {
980
      $variables = array('%label' => $rules_config->label(), '%name' => $rules_config->name, '!message' => $e->getMessage(), '@plugin' => $rules_config->plugin());
981
      watchdog('rules', 'The @plugin %label (%name) fails the integrity check and cannot be executed. Error: !message', $variables, WATCHDOG_ERROR);
982
    }
983
  }
984
  // Save the updated dirty flag to the database.
985
  if ($was_dirty != $rules_config->dirty) {
986
    db_update('rules_config')
987
      ->fields(array('dirty' => (int) $rules_config->dirty))
988
      ->condition('id', $rules_config->id)
989
      ->execute();
990
  }
991
}
992

    
993
/**
994
 * Invokes a hook and the associated rules event.
995
 *
996
 * Calling this function does the same as calling module_invoke_all() and
997
 * rules_invoke_event() separately, however merges both functions into one in
998
 * order to ease usage and to work efficiently.
999
 *
1000
 * @param $hook
1001
 *   The name of the hook / event to invoke.
1002
 * @param ...
1003
 *   Arguments to pass to the hook / event.
1004
 *
1005
 * @return array
1006
 *   An array of return values of the hook implementations. If modules return
1007
 *   arrays from their implementations, those are merged into one array.
1008
 */
1009
function rules_invoke_all() {
1010
  // Copied code from module_invoke_all().
1011
  $args = func_get_args();
1012
  $hook = $args[0];
1013
  unset($args[0]);
1014
  $return = array();
1015
  foreach (module_implements($hook) as $module) {
1016
    $function = $module . '_' . $hook;
1017
    if (function_exists($function)) {
1018
      $result = call_user_func_array($function, $args);
1019
      if (isset($result) && is_array($result)) {
1020
        $return = array_merge_recursive($return, $result);
1021
      }
1022
      elseif (isset($result)) {
1023
        $return[] = $result;
1024
      }
1025
    }
1026
  }
1027
  // Invoke the event.
1028
  rules_invoke_event_by_args($hook, $args);
1029

    
1030
  return $return;
1031
}
1032

    
1033
/**
1034
 * Invokes configured rules for the given event.
1035
 *
1036
 * @param $event_name
1037
 *   The event's name.
1038
 * @param ...
1039
 *   Pass parameters for the variables provided by this event, as defined in
1040
 *   hook_rules_event_info(). Example given:
1041
 *   @code
1042
 *     rules_invoke_event('node_view', $node, $view_mode);
1043
 *   @endcode
1044
 *
1045
 * @see rules_invoke_event_by_args()
1046
 */
1047
function rules_invoke_event() {
1048
  $args = func_get_args();
1049
  $event_name = $args[0];
1050
  unset($args[0]);
1051
  // We maintain a whitelist of configured events to reduces the number of cache
1052
  // reads. If the whitelist is not in the cache we proceed and it is rebuilt.
1053
  if (rules_event_invocation_enabled()) {
1054
    $whitelist = rules_get_cache('rules_event_whitelist');
1055
    if ((($whitelist === FALSE) || isset($whitelist[$event_name])) && $event = rules_get_cache('event_' . $event_name)) {
1056
      $event->executeByArgs($args);
1057
    }
1058
  }
1059
}
1060

    
1061
/**
1062
 * Invokes configured rules for the given event.
1063
 *
1064
 * @param $event_name
1065
 *   The event's name.
1066
 * @param array $args
1067
 *   An array of parameters for the variables provided by the event, as defined
1068
 *   in hook_rules_event_info(). Either pass an array keyed by the variable
1069
 *   names or a numerically indexed array, in which case the ordering of the
1070
 *   passed parameters has to match the order of the specified variables.
1071
 *   Example given:
1072
 *   @code
1073
 *     rules_invoke_event_by_args('node_view', array('node' => $node, 'view_mode' => $view_mode));
1074
 *   @endcode
1075
 *
1076
 * @see rules_invoke_event()
1077
 */
1078
function rules_invoke_event_by_args($event_name, $args = array()) {
1079
  // We maintain a whitelist of configured events to reduces the number of cache
1080
  // reads. If the whitelist is empty we proceed and it is rebuilt.
1081
  if (rules_event_invocation_enabled()) {
1082
    $whitelist = rules_get_cache('rules_event_whitelist');
1083
    if ((empty($whitelist) || isset($whitelist[$event_name])) && $event = rules_get_cache('event_' . $event_name)) {
1084
      $event->executeByArgs($args);
1085
    }
1086
  }
1087
}
1088

    
1089
/**
1090
 * Invokes a rule component, e.g. a rule set.
1091
 *
1092
 * @param $component_name
1093
 *   The component's name.
1094
 * @param $args
1095
 *   Pass further parameters as required for the invoked component.
1096
 *
1097
 * @return array
1098
 *   An array of variables as provided by the component, or FALSE in case the
1099
 *   component could not be executed.
1100
 */
1101
function rules_invoke_component() {
1102
  $args = func_get_args();
1103
  $name = array_shift($args);
1104
  if ($component = rules_get_cache('comp_' . $name)) {
1105
    return $component->executeByArgs($args);
1106
  }
1107
  return FALSE;
1108
}
1109

    
1110
/**
1111
 * Filters the given array of arrays.
1112
 *
1113
 * This filter operates by keeping only entries which have $key set to the
1114
 * value of $value.
1115
 *
1116
 * @param array $array
1117
 *   The array of arrays to filter.
1118
 * @param $key
1119
 *   The key used for the comparison.
1120
 * @param $value
1121
 *   The value to compare the array's entry to.
1122
 *
1123
 * @return array
1124
 *   The filtered array.
1125
 */
1126
function rules_filter_array($array, $key, $value) {
1127
  $return = array();
1128
  foreach ($array as $i => $entry) {
1129
    $entry += array($key => NULL);
1130
    if ($entry[$key] == $value) {
1131
      $return[$i] = $entry;
1132
    }
1133
  }
1134
  return $return;
1135
}
1136

    
1137
/**
1138
 * Merges the $update array into $array.
1139
 *
1140
 * Makes sure no values of $array not appearing in $update are lost.
1141
 *
1142
 * @return array
1143
 *   The updated array.
1144
 */
1145
function rules_update_array(array $array, array $update) {
1146
  foreach ($update as $key => $data) {
1147
    if (isset($array[$key]) && is_array($array[$key]) && is_array($data)) {
1148
      $array[$key] = rules_update_array($array[$key], $data);
1149
    }
1150
    else {
1151
      $array[$key] = $data;
1152
    }
1153
  }
1154
  return $array;
1155
}
1156

    
1157
/**
1158
 * Extracts the property with the given name.
1159
 *
1160
 * @param array $arrays
1161
 *   An array of arrays from which a property is to be extracted.
1162
 * @param $key
1163
 *   The name of the property to extract.
1164
 *
1165
 * @return array
1166
 *   An array of extracted properties, keyed as in $arrays.
1167
 */
1168
function rules_extract_property($arrays, $key) {
1169
  $data = array();
1170
  foreach ($arrays as $name => $item) {
1171
    $data[$name] = $item[$key];
1172
  }
1173
  return $data;
1174
}
1175

    
1176
/**
1177
 * Returns the first key of the array.
1178
 */
1179
function rules_array_key($array) {
1180
  reset($array);
1181
  return key($array);
1182
}
1183

    
1184
/**
1185
 * Clean replacements so they are URL friendly.
1186
 *
1187
 * Can be used as 'cleaning callback' for action or condition parameters.
1188
 *
1189
 * @param $replacements
1190
 *   An array of token replacements that need to be "cleaned" for use in the URL.
1191
 * @param array $data
1192
 *   An array of objects used to generate the replacements.
1193
 * @param array $options
1194
 *   An array of options used to generate the replacements.
1195
 *
1196
 * @see rules_path_action_info()
1197
 */
1198
function rules_path_clean_replacement_values(&$replacements, $data = array(), $options = array()) {
1199
  // Include path.eval.inc which contains path cleaning functions.
1200
  module_load_include('inc', 'rules', 'modules/path.eval');
1201
  foreach ($replacements as $token => $value) {
1202
    $replacements[$token] = rules_clean_path($value);
1203
  }
1204
}
1205

    
1206
/**
1207
 * Implements hook_theme().
1208
 */
1209
function rules_theme() {
1210
  return array(
1211
    'rules_elements' => array(
1212
      'render element' => 'element',
1213
      'file' => 'ui/ui.theme.inc',
1214
    ),
1215
    'rules_content_group' => array(
1216
      'render element' => 'element',
1217
      'file' => 'ui/ui.theme.inc',
1218
    ),
1219
    'rules_parameter_configuration' => array(
1220
      'render element' => 'element',
1221
      'file' => 'ui/ui.theme.inc',
1222
    ),
1223
    'rules_variable_view' => array(
1224
      'render element' => 'element',
1225
      'file' => 'ui/ui.theme.inc',
1226
    ),
1227
    'rules_data_selector_help' => array(
1228
      'variables' => array('parameter' => NULL, 'variables' => NULL),
1229
      'file' => 'ui/ui.theme.inc',
1230
    ),
1231
    'rules_ui_variable_form' => array(
1232
      'render element' => 'element',
1233
      'file' => 'ui/ui.theme.inc',
1234
    ),
1235
    'rules_log' => array(
1236
      'render element' => 'element',
1237
      'file' => 'ui/ui.theme.inc',
1238
    ),
1239
    'rules_autocomplete' => array(
1240
      'render element' => 'element',
1241
      'file' => 'ui/ui.theme.inc',
1242
    ),
1243
    'rules_debug_element' => array(
1244
      'render element' => 'element',
1245
      'file' => 'ui/ui.theme.inc',
1246
    ),
1247
    'rules_settings_help' => array(
1248
      'variables' => array('text' => '', 'heading' => ''),
1249
      'file' => 'ui/ui.theme.inc',
1250
    ),
1251
  );
1252
}
1253

    
1254
/**
1255
 * Implements hook_permission().
1256
 */
1257
function rules_permission() {
1258
  $perms = array(
1259
    'administer rules' => array(
1260
      'title' => t('Administer rule configurations'),
1261
      'description' => t('Administer rule configurations including events, conditions and actions for which the user has sufficient access permissions.'),
1262
    ),
1263
    'bypass rules access' => array(
1264
      'title' => t('Bypass Rules access control'),
1265
      'description' => t('Control all configurations regardless of permission restrictions of events, conditions or actions.'),
1266
      'restrict access' => TRUE,
1267
    ),
1268
    'access rules debug' => array(
1269
      'title' => t('Access the Rules debug log'),
1270
    ),
1271
  );
1272

    
1273
  // Fetch all components to generate the access keys.
1274
  $conditions['plugin'] = array_keys(rules_filter_array(rules_fetch_data('plugin_info'), 'component', TRUE));
1275
  $conditions['access_exposed'] = 1;
1276
  $components = entity_load('rules_config', FALSE, $conditions);
1277
  $perms += rules_permissions_by_component($components);
1278

    
1279
  return $perms;
1280
}
1281

    
1282
/**
1283
 * Helper function to get all the permissions for components that have access exposed.
1284
 */
1285
function rules_permissions_by_component(array $components = array()) {
1286
  $perms = array();
1287
  foreach ($components as $component) {
1288
    $perms += array(
1289
      "use Rules component $component->name" => array(
1290
        'title' => t('Use Rules component %component', array('%component' => $component->label())),
1291
        '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)))),
1292
      ),
1293
    );
1294
  }
1295
  return $perms;
1296
}
1297

    
1298
/**
1299
 * Menu callback for loading rules configuration elements.
1300
 *
1301
 * @see RulesUIController::config_menu()
1302
 */
1303
function rules_element_load($element_id, $config_name) {
1304
  $config = rules_config_load($config_name);
1305
  return $config->elementMap()->lookup($element_id);
1306
}
1307

    
1308
/**
1309
 * Menu callback for getting the title as configured.
1310
 *
1311
 * @see RulesUIController::config_menu()
1312
 */
1313
function rules_get_title($text, $element) {
1314
  if ($element instanceof RulesPlugin) {
1315
    $cache = rules_get_cache();
1316
    $plugin = $element->plugin();
1317
    $plugin = isset($cache['plugin_info'][$plugin]['label']) ? $cache['plugin_info'][$plugin]['label'] : $plugin;
1318
    $plugin = drupal_strtolower(drupal_substr($plugin, 0, 1)) . drupal_substr($plugin, 1);
1319
    return t($text, array('!label' => $element->label(), '!plugin' => $plugin));
1320
  }
1321
  // As fallback treat $element as simple string.
1322
  return t($text, array('!plugin' => $element));
1323
}
1324

    
1325
/**
1326
 * Menu callback for getting the title for the add element page.
1327
 *
1328
 * Uses a work-a-round for accessing the plugin name.
1329
 *
1330
 * @see RulesUIController::config_menu()
1331
 */
1332
function rules_menu_add_element_title($array) {
1333
  $plugin_name = arg($array[0]);
1334
  $cache = rules_get_cache();
1335
  if (isset($cache['plugin_info'][$plugin_name]['class'])) {
1336
    $info = $cache['plugin_info'][$plugin_name] + array('label' => $plugin_name);
1337
    $label = drupal_strtolower(drupal_substr($info['label'], 0, 1)) . drupal_substr($info['label'], 1);
1338
    return t('Add a new !plugin', array('!plugin' => $label));
1339
  }
1340
}
1341

    
1342
/**
1343
 * Returns the current region for the debug log.
1344
 */
1345
function rules_debug_log_region() {
1346
  // If there is no setting for the current theme use the default theme setting.
1347
  global $theme_key;
1348
  $theme_default = variable_get('theme_default', 'bartik');
1349
  return variable_get('rules_debug_region_' . $theme_key, variable_get('rules_debug_region_' . $theme_default, 'help'));
1350
}
1351

    
1352
/**
1353
 * Implements hook_page_build() to add the rules debug log to the page bottom.
1354
 */
1355
function rules_page_build(&$page) {
1356
  // Invoke a the page redirect, in case the action has been executed.
1357
  // @see rules_action_drupal_goto()
1358
  if (isset($GLOBALS['_rules_action_drupal_goto_do'])) {
1359
    list($url, $force) = $GLOBALS['_rules_action_drupal_goto_do'];
1360
    drupal_goto($url);
1361
  }
1362

    
1363
  if (isset($_SESSION['rules_debug'])) {
1364
    $region = rules_debug_log_region();
1365
    foreach ($_SESSION['rules_debug'] as $log) {
1366
      $page[$region]['rules_debug'][] = array(
1367
        '#markup' => $log,
1368
      );
1369
      $page[$region]['rules_debug']['#theme_wrappers'] = array('rules_log');
1370
    }
1371
    unset($_SESSION['rules_debug']);
1372
  }
1373

    
1374
  if (rules_show_debug_output()) {
1375
    $region = rules_debug_log_region();
1376
    $page[$region]['rules_debug']['#pre_render'] = array('rules_debug_log_pre_render');
1377
  }
1378
}
1379

    
1380
/**
1381
 * Pre-render callback for the debug log, which renders and then clears it.
1382
 */
1383
function rules_debug_log_pre_render($elements) {
1384
  $logger = RulesLog::logger();
1385
  if ($log = $logger->render()) {
1386
    $logger = RulesLog::logger();
1387
    $logger->clear();
1388
    $elements[] = array('#markup' => $log);
1389
    $elements['#theme_wrappers'] = array('rules_log');
1390
    // Log the rules log to the system log if enabled.
1391
    if (variable_get('rules_debug_log', FALSE)) {
1392
      watchdog('rules', 'Rules debug information: !log', array('!log' => $log), WATCHDOG_NOTICE);
1393
    }
1394
  }
1395
  return $elements;
1396
}
1397

    
1398
/**
1399
 * Implements hook_drupal_goto_alter().
1400
 *
1401
 * @see rules_action_drupal_goto()
1402
 */
1403
function rules_drupal_goto_alter(&$path, &$options, &$http_response_code) {
1404
  // Invoke a the page redirect, in case the action has been executed.
1405
  if (isset($GLOBALS['_rules_action_drupal_goto_do'])) {
1406
    list($url, $force) = $GLOBALS['_rules_action_drupal_goto_do'];
1407

    
1408
    if ($force || !isset($_GET['destination'])) {
1409
      $url = drupal_parse_url($url);
1410
      $path = $url['path'];
1411
      $options['query'] = $url['query'];
1412
      $options['fragment'] = $url['fragment'];
1413
      $http_response_code = 302;
1414
    }
1415
  }
1416
}
1417

    
1418
/**
1419
 * Returns whether the debug log should be shown.
1420
 */
1421
function rules_show_debug_output() {
1422
  // For performance avoid unnecessary auto-loading of the RulesLog class.
1423
  if (!class_exists('RulesLog', FALSE)) {
1424
    return FALSE;
1425
  }
1426
  if (variable_get('rules_debug', 0) == RulesLog::INFO && user_access('access rules debug')) {
1427
    return TRUE;
1428
  }
1429
  return variable_get('rules_debug', 0) == RulesLog::WARN && user_access('access rules debug') && RulesLog::logger()->hasErrors();
1430
}
1431

    
1432
/**
1433
 * Implements hook_exit().
1434
 */
1435
function rules_exit() {
1436
  // Bail out if this is cached request and modules are not loaded.
1437
  if (!module_exists('rules') || !module_exists('user')) {
1438
    return;
1439
  }
1440
  if (rules_show_debug_output()) {
1441
    if ($log = RulesLog::logger()->render()) {
1442
      // Keep the log in the session so we can show it on the next page.
1443
      $_SESSION['rules_debug'][] = $log;
1444
    }
1445
  }
1446
  // Log the rules log to the system log if enabled.
1447
  if (variable_get('rules_debug_log', FALSE) && $log = RulesLog::logger()->render()) {
1448
    watchdog('rules', 'Rules debug information: !log', array('!log' => $log), WATCHDOG_NOTICE);
1449
  }
1450
}
1451

    
1452
/**
1453
 * Implements hook_element_info().
1454
 */
1455
function rules_element_info() {
1456
  // A duration form element for rules. Needs ui.forms.inc included.
1457
  $types['rules_duration'] = array(
1458
    '#input' => TRUE,
1459
    '#tree' => TRUE,
1460
    '#default_value' => 0,
1461
    '#value_callback' => 'rules_ui_element_duration_value',
1462
    '#process' => array('rules_ui_element_duration_process', 'ajax_process_form'),
1463
    '#after_build' => array('rules_ui_element_duration_after_build'),
1464
    '#pre_render' => array('form_pre_render_conditional_form_element'),
1465
  );
1466
  $types['rules_data_selection'] = array(
1467
    '#input' => TRUE,
1468
    '#pre_render' => array('form_pre_render_conditional_form_element'),
1469
    '#process' => array('rules_data_selection_process', 'ajax_process_form'),
1470
    '#theme' => 'rules_autocomplete',
1471
  );
1472
  return $types;
1473
}
1474

    
1475
/**
1476
 * Implements hook_modules_enabled().
1477
 */
1478
function rules_modules_enabled($modules) {
1479
  // Re-enable Rules configurations that are dirty, because they require one of
1480
  // the enabled the modules.
1481
  $query = db_select('rules_dependencies', 'rd');
1482
  $query->join('rules_config', 'rc', 'rd.id = rc.id');
1483
  $query->fields('rd', array('id'))
1484
        ->condition('rd.module', $modules, 'IN')
1485
        ->condition('rc.dirty', 1);
1486
  $ids = $query->execute()->fetchCol();
1487

    
1488
  // If there are some configurations that might work again, re-check all dirty
1489
  // configurations as others might work again too, e.g. consider a rule that is
1490
  // dirty because it requires a dirty component.
1491
  if ($ids) {
1492
    $rules_configs = rules_config_load_multiple(FALSE, array('dirty' => 1));
1493
    foreach ($rules_configs as $rules_config) {
1494
      try {
1495
        $rules_config->integrityCheck();
1496
        // If no exceptions were thrown we can set the configuration back to OK.
1497
        db_update('rules_config')
1498
          ->fields(array('dirty' => 0))
1499
          ->condition('id', $rules_config->id)
1500
          ->execute();
1501
        if ($rules_config->active) {
1502
          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())));
1503
        }
1504
      }
1505
      catch (RulesIntegrityException $e) {
1506
        // The rule is still dirty, so do nothing.
1507
      }
1508
    }
1509
  }
1510
  rules_clear_cache();
1511
}
1512

    
1513
/**
1514
 * Implements hook_modules_disabled().
1515
 */
1516
function rules_modules_disabled($modules) {
1517
  // Disable Rules configurations that depend on one of the disabled modules.
1518
  $query = db_select('rules_dependencies', 'rd');
1519
  $query->join('rules_config', 'rc', 'rd.id = rc.id');
1520
  $query->fields('rd', array('id'))
1521
        ->distinct()
1522
        ->condition('rd.module', $modules, 'IN')
1523
        ->condition('rc.dirty', 0);
1524
  $ids = $query->execute()->fetchCol();
1525

    
1526
  if (!empty($ids)) {
1527
    db_update('rules_config')
1528
      ->fields(array('dirty' => 1))
1529
      ->condition('id', $ids, 'IN')
1530
      ->execute();
1531
    // Tell the user about enabled rules that have been marked as dirty.
1532
    $count = db_select('rules_config', 'r')
1533
      ->fields('r')
1534
      ->condition('id', $ids, 'IN')
1535
      ->condition('active', 1)
1536
      ->countQuery()
1537
      ->execute()
1538
      ->fetchField();
1539
    if ($count > 0) {
1540
      $message = format_plural($count,
1541
        '1 Rules configuration requires some of the disabled modules to function and cannot be executed any more.',
1542
        '@count Rules configurations require some of the disabled modules to function and cannot be executed any more.'
1543
      );
1544
      drupal_set_message($message, 'warning');
1545
    }
1546
  }
1547
  rules_clear_cache();
1548
}
1549

    
1550
/**
1551
 * Access callback for dealing with Rules configurations.
1552
 *
1553
 * @see entity_access()
1554
 */
1555
function rules_config_access($op, $rules_config = NULL, $account = NULL) {
1556
  if (user_access('bypass rules access', $account)) {
1557
    return TRUE;
1558
  }
1559
  // Allow modules to grant / deny access.
1560
  $access = module_invoke_all('rules_config_access', $op, $rules_config, $account);
1561

    
1562
  // Only grant access if at least one module granted access and no one denied
1563
  // access.
1564
  if (in_array(FALSE, $access, TRUE)) {
1565
    return FALSE;
1566
  }
1567
  elseif (in_array(TRUE, $access, TRUE)) {
1568
    return TRUE;
1569
  }
1570
  return FALSE;
1571
}
1572

    
1573
/**
1574
 * Implements hook_rules_config_access().
1575
 */
1576
function rules_rules_config_access($op, $rules_config = NULL, $account = NULL) {
1577
  // Instead of returning FALSE return nothing, so others still can grant
1578
  // access.
1579
  if (!isset($rules_config) || (isset($account) && $account->uid != $GLOBALS['user']->uid)) {
1580
    return;
1581
  }
1582
  if (user_access('administer rules', $account) && ($op == 'view' || $rules_config->access())) {
1583
    return TRUE;
1584
  }
1585
}
1586

    
1587
/**
1588
 * Implements hook_menu().
1589
 */
1590
function rules_menu() {
1591
  $items['admin/config/workflow/rules/upgrade'] = array(
1592
    'title' => 'Upgrade',
1593
    'page callback' => 'drupal_get_form',
1594
    'page arguments' => array('rules_upgrade_form'),
1595
    'access arguments' => array('administer rules'),
1596
    'file' => 'includes/rules.upgrade.inc',
1597
    'file path' => drupal_get_path('module', 'rules'),
1598
    'type' => MENU_CALLBACK,
1599
  );
1600
  $items['admin/config/workflow/rules/upgrade/clear'] = array(
1601
    'title' => 'Clear',
1602
    'page callback' => 'drupal_get_form',
1603
    'page arguments' => array('rules_upgrade_confirm_clear_form'),
1604
    'access arguments' => array('administer rules'),
1605
    'file' => 'includes/rules.upgrade.inc',
1606
    'file path' => drupal_get_path('module', 'rules'),
1607
    'type' => MENU_CALLBACK,
1608
  );
1609
  $items['admin/config/workflow/rules/autocomplete_tags'] = array(
1610
    'title' => 'Rules tags autocomplete',
1611
    'page callback' => 'rules_autocomplete_tags',
1612
    'page arguments' => array(5),
1613
    'access arguments' => array('administer rules'),
1614
    'file' => 'ui/ui.forms.inc',
1615
    'type' => MENU_CALLBACK,
1616
  );
1617
  return $items;
1618
}
1619

    
1620
/**
1621
 * Helper function to keep track of external documentation pages for Rules.
1622
 *
1623
 * @param string $topic
1624
 *   The topic key for used for identifying help pages.
1625
 *
1626
 * @return string|array|false
1627
 *   Either a URL for the given page, or the full list of external help pages.
1628
 */
1629
function rules_external_help($topic = NULL) {
1630
  $help = array(
1631
    'rules' =>                'https://www.drupal.org/node/298480',
1632
    'terminology' =>          'https://www.drupal.org/node/1299990',
1633
    'condition-components' => 'https://www.drupal.org/node/1300034',
1634
    'data-selection' =>       'https://www.drupal.org/node/1300042',
1635
    'chained-tokens' =>       'https://www.drupal.org/node/1300042',
1636
    'loops' =>                'https://www.drupal.org/node/1300058',
1637
    'components' =>           'https://www.drupal.org/node/1300024',
1638
    'component-types' =>      'https://www.drupal.org/node/1300024',
1639
    'variables' =>            'https://www.drupal.org/node/1300024',
1640
    'scheduler' =>            'https://www.drupal.org/node/1300068',
1641
    'coding' =>               'https://www.drupal.org/node/878720',
1642
  );
1643

    
1644
  if (isset($topic)) {
1645
    return isset($help[$topic]) ? $help[$topic] : FALSE;
1646
  }
1647
  return $help;
1648
}
1649

    
1650
/**
1651
 * Implements hook_help().
1652
 */
1653
function rules_help($path, $arg) {
1654
  // Only enable the help if the admin module is active.
1655
  if ($path == 'admin/help#rules' && module_exists('rules_admin')) {
1656

    
1657
    $output['header'] = array(
1658
      '#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!'),
1659
    );
1660
    // Build a list of essential Rules help pages, formatted as a bullet list.
1661
    $link_list['rules'] = l(t('Rules introduction'), rules_external_help('rules'));
1662
    $link_list['terminology'] = l(t('Rules terminology'), rules_external_help('terminology'));
1663
    $link_list['scheduler'] = l(t('Rules Scheduler'), rules_external_help('scheduler'));
1664
    $link_list['coding'] = l(t('Coding for Rules'), rules_external_help('coding'));
1665

    
1666
    $output['topic-list'] = array(
1667
      '#markup' => theme('item_list', array('items' => $link_list)),
1668
    );
1669
    return render($output);
1670
  }
1671
}
1672

    
1673
/**
1674
 * Implements hook_token_info().
1675
 */
1676
function rules_token_info() {
1677
  $cache = rules_get_cache();
1678
  $data_info = $cache['data_info'];
1679

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

    
1682
  foreach ($types as $type) {
1683
    $token_type = $data_info[$type]['token type'];
1684

    
1685
    $token_info['types'][$token_type] = array(
1686
      'name' => $data_info[$type]['label'],
1687
      'description' => t('Tokens related to %label Rules variables.', array('%label' => $data_info[$type]['label'])),
1688
      'needs-data' => $token_type,
1689
    );
1690
    $token_info['tokens'][$token_type]['value'] = array(
1691
      'name' => t("Value"),
1692
      'description' => t('The value of the variable.'),
1693
    );
1694
  }
1695
  return $token_info;
1696
}
1697

    
1698
/**
1699
 * Implements hook_tokens().
1700
 */
1701
function rules_tokens($type, $tokens, $data, $options = array()) {
1702
  // Handle replacements of primitive variable types.
1703
  if (substr($type, 0, 6) == 'rules_' && !empty($data[$type])) {
1704
    // Leverage entity tokens token processor by passing on as struct.
1705
    $info['property info']['value'] = array(
1706
      'type' => substr($type, 6),
1707
      'label' => '',
1708
    );
1709
    // Entity tokens uses metadata wrappers as values for 'struct' types.
1710
    $wrapper = entity_metadata_wrapper('struct', array('value' => $data[$type]), $info);
1711
    return entity_token_tokens('struct', $tokens, array('struct' => $wrapper), $options);
1712
  }
1713
}
1714

    
1715
/**
1716
 * Helper function that retrieves a metadata wrapper with all properties.
1717
 *
1718
 * Note that without this helper, bundle-specific properties aren't added.
1719
 */
1720
function rules_get_entity_metadata_wrapper_all_properties(RulesAbstractPlugin $element) {
1721
  return entity_metadata_wrapper($element->settings['type'], NULL, array(
1722
    'property info alter' => 'rules_entity_metadata_wrapper_all_properties_callback',
1723
  ));
1724
}
1725

    
1726
/**
1727
 * Callback that returns a metadata wrapper with all properties.
1728
 */
1729
function rules_entity_metadata_wrapper_all_properties_callback(EntityMetadataWrapper $wrapper, $property_info) {
1730
  $info = $wrapper->info();
1731
  $properties = entity_get_all_property_info($info['type']);
1732
  $property_info['properties'] += $properties;
1733
  return $property_info;
1734
}
1735

    
1736
/**
1737
 * Helper to enable or disable the invocation of rules events.
1738
 *
1739
 * Rules invocation is disabled by default, such that Rules does not operate
1740
 * when Drupal is not fully bootstrapped. It gets enabled in rules_init() and
1741
 * rules_enable().
1742
 *
1743
 * @param bool|null $enable
1744
 *   NULL to leave the setting as is and TRUE / FALSE to change the behaviour.
1745
 *
1746
 * @return bool
1747
 *   Whether the rules invocation is enabled or disabled.
1748
 */
1749
function rules_event_invocation_enabled($enable = NULL) {
1750
  static $invocation_enabled = FALSE;
1751
  if (isset($enable)) {
1752
    $invocation_enabled = (bool) $enable;
1753
  }
1754
  // Disable invocation if configured or if site runs in maintenance mode.
1755
  return $invocation_enabled && !defined('MAINTENANCE_MODE');
1756
}