Projet

Général

Profil

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

root / drupal7 / sites / all / modules / rules / rules.module @ 651307cd

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

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

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

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

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

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

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

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

    
501

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1001
  return $return;
1002
}
1003

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

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

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

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

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

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

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

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

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

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

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

    
1246
  return $perms;
1247
}
1248

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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