Projet

Général

Profil

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

root / drupal7 / sites / all / modules / rules / rules.module @ 74f6bef0

1
<?php
2

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

    
7
/**
8
 * Implements hook_init().
9
 */
10
function rules_init() {
11
  module_load_include('inc', 'rules', 'modules/events');
12
  rules_invoke_event('init');
13
}
14

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

    
30
/**
31
 * Returns a new rules action.
32
 *
33
 * @param $name
34
 *   The action's name.
35
 * @param $settings
36
 *   The action's settings array.
37
 * @return RulesAction
38
 */
39
function rules_action($name, $settings = array()) {
40
  return rules_plugin_factory('action', $name, $settings);
41
}
42

    
43
/**
44
 * Returns a new rules condition.
45
 *
46
 * @param $name
47
 *   The condition's name.
48
 * @param $settings
49
 *   The condition's settings array.
50
 * @return RulesCondition
51
 */
52
function rules_condition($name, $settings = array()) {
53
  return rules_plugin_factory('condition', $name, $settings);
54
}
55

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

    
83
/**
84
 * Creates a new reaction rule.
85
 *
86
 * @return RulesReactionRule
87
 */
88
function rules_reaction_rule() {
89
  return rules_plugin_factory('reaction rule');
90
}
91

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

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

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

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

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

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

    
174
  // Statically cache the variable settings as this is called very often.
175
  if (!isset($settings)) {
176
    $settings['rules_log_errors'] = variable_get('rules_log_errors', RulesLog::WARN);
177
    $settings['rules_debug_log'] = variable_get('rules_debug_log', FALSE);
178
    $settings['rules_debug'] = variable_get('rules_debug', FALSE);
179
  }
180

    
181
  if ($priority >= $settings['rules_log_errors']) {
182
    $link = NULL;
183
    if (isset($element) && isset($element->root()->name)) {
184
      $link = l(t('edit configuration'), RulesPluginUI::path($element->root()->name, 'edit', $element));
185
    }
186
    watchdog('rules', $msg, $args, $priority == RulesLog::WARN ? WATCHDOG_WARNING : WATCHDOG_ERROR, $link);
187
  }
188
  // Do nothing in case debugging is totally disabled.
189
  if (!$settings['rules_debug_log'] && !$settings['rules_debug']) {
190
    return;
191
  }
192
  if (!isset($logger)) {
193
    $logger = RulesLog::logger();
194
  }
195
  $path = isset($element) && isset($element->root()->name) ? RulesPluginUI::path($element->root()->name, 'edit', $element) : NULL;
196
  $logger->log($msg, $args, $priority, $scope, $path);
197
}
198

    
199
/**
200
 * Fetches module definitions for the given hook name.
201
 *
202
 * Used for collecting events, rules, actions and condtions from other modules.
203
 *
204
 * @param $hook
205
 *   The hook of the definitions to get from invoking hook_rules_{$hook}.
206
 */
207
function rules_fetch_data($hook) {
208
  $data = &drupal_static(__FUNCTION__, array());
209
  static $discover = array(
210
    'action_info' => 'RulesActionHandlerInterface',
211
    'condition_info' => 'RulesConditionHandlerInterface',
212
    'event_info' => 'RulesEventHandlerInterface',
213
  );
214

    
215
  if (!isset($data[$hook])) {
216
    foreach (module_implements('rules_' . $hook) as $module) {
217
      $result = call_user_func($module . '_rules_' . $hook);
218
      if (isset($result) && is_array($result)) {
219
        foreach ($result as $name => $item) {
220
          $item += array('module' => $module);
221
          $data[$hook][$name] = $item;
222
        }
223
      }
224
    }
225
    // Support class discovery.
226
    if (isset($discover[$hook])) {
227
      $data[$hook] += rules_discover_plugins($discover[$hook]);
228
    }
229
    drupal_alter('rules_'. $hook, $data[$hook]);
230
  }
231
  return $data[$hook];
232
}
233

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

    
263
  $items = array();
264
  foreach (get_declared_classes() as $plugin_class) {
265
    if (is_subclass_of($plugin_class, $class) && method_exists($plugin_class, 'getInfo')) {
266
      $info = call_user_func(array($plugin_class, 'getInfo'));
267
      $info['class'] = $plugin_class;
268
      $info['module'] = _rules_discover_module($plugin_class);
269
      $items[$info['name']] = $info;
270
    }
271
  }
272
  return $items;
273
}
274

    
275
/**
276
 * Determines the module providing the given class.
277
 */
278
function _rules_discover_module($class) {
279
  $paths = &drupal_static(__FUNCTION__);
280

    
281
  if (!isset($paths)) {
282
    // Build up a map of modules keyed by their directory.
283
    foreach (system_list('module_enabled') as $name => $module_info) {
284
      $paths[dirname($module_info->filename)] = $name;
285
    }
286
  }
287

    
288
  // Retrieve the class file and convert its absolute path to a regular Drupal
289
  // path relative to the installation root.
290
  $reflection = new ReflectionClass($class);
291
  $path = str_replace(realpath(DRUPAL_ROOT) . DIRECTORY_SEPARATOR, '', realpath(dirname($reflection->getFileName())));
292
  $path = DIRECTORY_SEPARATOR != '/' ? str_replace(DIRECTORY_SEPARATOR, '/', $path) : $path;
293

    
294
  // Go up the path until we match a module up.
295
  $parts = explode('/', $path);
296
  while (!isset($paths[$path]) && array_pop($parts)) {
297
    $path = dirname($path);
298
  }
299
  return isset($paths[$path]) ? $paths[$path] : FALSE;
300
}
301

    
302
/**
303
 * Gets a rules cache entry.
304
 */
305
function &rules_get_cache($cid = 'data') {
306
  // Make use of the fast, advanced drupal static pattern.
307
  static $drupal_static_fast;
308
  if (!isset($drupal_static_fast)) {
309
    $drupal_static_fast['cache'] = &drupal_static(__FUNCTION__, array());
310
  }
311
  $cache = &$drupal_static_fast['cache'];
312

    
313
  if (!isset($cache[$cid])) {
314
    // The main 'data' cache includes translated strings, so each language is
315
    // cached separately.
316
    $cid_suffix = $cid == 'data' ? ':' . $GLOBALS['language']->language : '';
317

    
318
    if ($get = cache_get($cid . $cid_suffix, 'cache_rules')) {
319
      $cache[$cid] = $get->data;
320
    }
321
    elseif ($cid === 'data') {
322
      // There is no 'data' cache so we need to rebuild it. Make sure subsequent
323
      // cache gets of the main 'data' cache during rebuild get the interim
324
      // cache by passing in the reference of the static cache variable.
325
      _rules_rebuild_cache($cache['data']);
326
    }
327
    elseif (strpos($cid, 'comp_') === 0) {
328
      $cache[$cid] = FALSE;
329
      _rules_rebuild_component_cache();
330
    }
331
    elseif (strpos($cid, 'event_') === 0) {
332
      $cache[$cid] = FALSE;
333
      RulesEventSet::rebuildEventCache();
334
    }
335
    else {
336
      $cache[$cid] = FALSE;
337
    }
338
  }
339
  return $cache[$cid];
340
}
341

    
342
/**
343
 * Rebuilds the rules cache.
344
 *
345
 * This rebuilds the rules 'data' cache and invokes rebuildCache() methods on
346
 * all plugin classes, which allows plugins to add their own data to the cache.
347
 * The cache is rebuilt in the order the plugins are defined.
348
 *
349
 * Note that building the action/condition info cache triggers loading of all
350
 * components, thus depends on entity-loading and so syncing entities in code
351
 * to the database.
352
 *
353
 * @see rules_rules_plugin_info()
354
 * @see entity_defaults_rebuild()
355
 */
356
function _rules_rebuild_cache(&$cache) {
357
  foreach(array('data_info', 'plugin_info') as $hook) {
358
    $cache[$hook] = rules_fetch_data($hook);
359
  }
360
  foreach ($cache['plugin_info'] as $name => &$info) {
361
    // Let the items add something to the cache.
362
    $item = new $info['class']();
363
    $item->rebuildCache($info, $cache);
364
  }
365
  $cid_suffix = ':' . $GLOBALS['language']->language;
366
  cache_set('data' . $cid_suffix, $cache, 'cache_rules');
367
}
368

    
369
/**
370
 * Cache components to allow efficient usage via rules_invoke_component().
371
 *
372
 * @see rules_invoke_component()
373
 * @see rules_get_cache()
374
 */
375
function _rules_rebuild_component_cache() {
376
  $components = rules_get_components();
377

    
378
  foreach ($components as $id => $component) {
379
    // If a component is marked as dirty, check if this still applies.
380
    if ($component->dirty) {
381
      rules_config_update_dirty_flag($component);
382
    }
383
    if (!$component->dirty) {
384
      // Clone the component to avoid modules getting the to be cached
385
      // version from the static loading cache.
386
      $component = clone $component;
387
      $component->optimize();
388
      // Allow modules to alter the cached component.
389
      drupal_alter('rules_component', $component->plugin, $component);
390
      rules_set_cache('comp_' . $component->name, $component);
391
    }
392
  }
393
}
394

    
395
/**
396
 * Sets a rules cache item.
397
 *
398
 * In addition to calling cache_set(), this function makes sure the cache item
399
 * is immediately available via rules_get_cache() by keeping all cache items
400
 * in memory. That way we can guarantee rules_get_cache() is able to retrieve
401
 * any cache item, even if all cache gets fail.
402
 *
403
 * @see rules_get_cache()
404
 */
405
function rules_set_cache($cid, $data) {
406
  $cache = &drupal_static('rules_get_cache', array());
407
  $cache[$cid] = $data;
408
  cache_set($cid, $data, 'cache_rules');
409
}
410

    
411
/**
412
 * Implements hook_flush_caches().
413
 */
414
function rules_flush_caches() {
415
  return array('cache_rules');
416
}
417

    
418
/**
419
 * Clears the rule set cache
420
 */
421
function rules_clear_cache() {
422
  cache_clear_all('*', 'cache_rules', TRUE);
423
  variable_del('rules_event_whitelist');
424
  drupal_static_reset('rules_get_cache');
425
  drupal_static_reset('rules_fetch_data');
426
  drupal_static_reset('rules_config_update_dirty_flag');
427
  entity_get_controller('rules_config')->resetCache();
428
}
429

    
430
/**
431
 * Imports the given export and returns the imported configuration.
432
 *
433
 * @param $export
434
 *   A serialized string in JSON format as produced by the RulesPlugin::export()
435
 *   method, or the PHP export as usual PHP array.
436
 * @return RulesPlugin
437
 */
438
function rules_import($export, &$error_msg = '') {
439
  return entity_get_controller('rules_config')->import($export, $error_msg);
440
}
441

    
442

    
443
/**
444
 * Wraps the given data.
445
 *
446
 * @param $data
447
 *   If available, the actual data, else NULL.
448
 * @param $info
449
 *   An array of info about this data.
450
 * @param $force
451
 *   Usually data is only wrapped if really needed. If set to TRUE, wrapping the
452
 *   data is forced, so primitive data types are also wrapped.
453
 * @return EntityMetadataWrapper
454
 *   An EntityMetadataWrapper or the unwrapped data.
455
 *
456
 * @see hook_rules_data_info()
457
 */
458
function &rules_wrap_data($data = NULL, $info, $force = FALSE) {
459
  // If the data is already wrapped, use the existing wrapper.
460
  if ($data instanceof EntityMetadataWrapper) {
461
    return $data;
462
  }
463
  $cache = rules_get_cache();
464
  // Define the keys to be passed through to the metadata wrapper.
465
  $wrapper_keys = array_flip(array('property info', 'property defaults'));
466
  if (isset($cache['data_info'][$info['type']])) {
467
    $info += array_intersect_key($cache['data_info'][$info['type']], $wrapper_keys);
468
  }
469
  // If a list is given, also add in the info of the item type.
470
  $list_item_type = entity_property_list_extract_type($info['type']);
471
  if ($list_item_type && isset($cache['data_info'][$list_item_type])) {
472
    $info += array_intersect_key($cache['data_info'][$list_item_type], $wrapper_keys);
473
  }
474
  // By default we do not wrap the data, except for completely unknown types.
475
  if (!empty($cache['data_info'][$info['type']]['wrap']) || $list_item_type || $force || empty($cache['data_info'][$info['type']])) {
476
    unset($info['handler']);
477
    // Allow data types to define custom wrapper classes.
478
    if (!empty($cache['data_info'][$info['type']]['wrapper class'])) {
479
      $class = $cache['data_info'][$info['type']]['wrapper class'];
480
      $wrapper = new $class($info['type'], $data, $info);
481
    }
482
    else {
483
      $wrapper = entity_metadata_wrapper($info['type'], $data, $info);
484
    }
485
    return $wrapper;
486
  }
487
  return $data;
488
}
489

    
490
/**
491
 * Unwraps the given data, if it's wrapped.
492
 *
493
 * @param $data
494
 *   An array of wrapped data.
495
 * @param $info
496
 *   Optionally an array of info about how to unwrap the data. Keyed as $data.
497
 * @return
498
 *   An array containing unwrapped or passed through data.
499
 */
500
function rules_unwrap_data(array $data, $info = array()) {
501
  $cache = rules_get_cache();
502
  foreach ($data as $key => $entry) {
503
    // If it's a wrapper, unwrap unless specified otherwise.
504
    if ($entry instanceof EntityMetadataWrapper) {
505
      if (!isset($info[$key]['allow null'])) {
506
        $info[$key]['allow null'] = FALSE;
507
      }
508
      if (!isset($info[$key]['wrapped'])) {
509
        // By default, do not unwrap special data types that are always wrapped.
510
        $info[$key]['wrapped'] = (isset($info[$key]['type']) && is_string($info[$key]['type']) && !empty($cache['data_info'][$info[$key]['type']]['is wrapped']));
511
      }
512
      // Activate the decode option by default if 'sanitize' is not enabled, so
513
      // any text is either sanitized or decoded.
514
      // @see EntityMetadataWrapper::value()
515
      $options = $info[$key] + array('decode' => empty($info[$key]['sanitize']));
516

    
517
      try {
518
        if (!($info[$key]['allow null'] && $info[$key]['wrapped'])) {
519
          $value = $entry->value($options);
520

    
521
          if (!$info[$key]['wrapped']) {
522
            $data[$key] = $value;
523
          }
524
          if (!$info[$key]['allow null'] && !isset($value)) {
525
            throw new RulesEvaluationException('The variable or parameter %name is empty.', array('%name' => $key));
526
          }
527
        }
528
      }
529
      catch (EntityMetadataWrapperException $e) {
530
        throw new RulesEvaluationException('Unable to get the data value for the variable or parameter %name. Error: !error', array('%name' => $key, '!error' => $e->getMessage()));
531
      }
532
    }
533
  }
534
  return $data;
535
}
536

    
537
/**
538
 * Gets event info for a given event.
539
 *
540
 * @param string $event_name
541
 *   A (configured) event name.
542
 *
543
 * @return array
544
 *   An array of event info. If the event is unknown, a suiting info array is
545
 *   generated and returned
546
 */
547
function rules_get_event_info($event_name) {
548
  $base_event_name = rules_get_event_base_name($event_name);
549
  $events = rules_fetch_data('event_info');
550
  if (isset($events[$base_event_name])) {
551
    return $events[$base_event_name] + array('name' => $base_event_name);
552
  }
553
  return array(
554
    'label' => t('Unknown event "!event_name"', array('!event_name' => $base_event_name)),
555
    'name' => $base_event_name,
556
  );
557
}
558

    
559
/**
560
 * Returns the base name of a configured event name.
561
 *
562
 * For a configured event name like node_view--article the base event name
563
 * node_view is returned.
564
 *
565
 * @return string
566
 *   The event base name.
567
 */
568
function rules_get_event_base_name($event_name) {
569
  // Cut off any suffix from a configured event name.
570
  if (strpos($event_name, '--') !== FALSE) {
571
    $parts = explode('--', $event_name, 2);
572
    return $parts[0];
573
  }
574
  return $event_name;
575
}
576

    
577
/**
578
 * Returns the rule event handler for the given event.
579
 *
580
 * Events having no settings are handled via the class RulesEventSettingsNone.
581
 *
582
 * @param string $event_name
583
 *   The event name (base or configured).
584
 * @param array $settings
585
 *   (optional) An array of event settings to set on the handler.
586
 *
587
 * @return RulesEventHandlerInterface
588
 *   The event handler.
589
 */
590
function rules_get_event_handler($event_name, array $settings = NULL) {
591
  $event_name = rules_get_event_base_name($event_name);
592
  $event_info = rules_get_event_info($event_name);
593
  $class = !empty($event_info['class']) ? $event_info['class'] : 'RulesEventDefaultHandler';
594
  $handler = new $class($event_name, $event_info);
595
  return isset($settings) ? $handler->setSettings($settings) : $handler;
596
}
597

    
598
/**
599
 * Creates a new instance of a the given rules plugin.
600
 *
601
 * @return RulesPlugin
602
 */
603
function rules_plugin_factory($plugin_name, $arg1 = NULL, $arg2 = NULL) {
604
  $cache = rules_get_cache();
605
  if (isset($cache['plugin_info'][$plugin_name]['class'])) {
606
    return new $cache['plugin_info'][$plugin_name]['class']($arg1, $arg2);
607
  }
608
}
609

    
610
/**
611
 * Implementation of hook_rules_plugin_info().
612
 *
613
 * Note that the cache is rebuilt in the order of the plugins. Therefore the
614
 * condition and action plugins must be at the top, so that any components
615
 * re-building their cache can create configurations including properly setup-ed
616
 * actions and conditions.
617
 */
618
function rules_rules_plugin_info() {
619
  return array(
620
    'condition' => array(
621
      'class' => 'RulesCondition',
622
      'embeddable' => 'RulesConditionContainer',
623
      'extenders' => array (
624
        'RulesPluginImplInterface' => array(
625
          'class' => 'RulesAbstractPluginDefaults',
626
        ),
627
        'RulesPluginFeaturesIntegrationInterace' => array(
628
          'methods' => array(
629
            'features_export' => 'rules_features_abstract_default_features_export',
630
          ),
631
        ),
632
        'RulesPluginUIInterface' => array(
633
          'class' => 'RulesAbstractPluginUI',
634
        ),
635
      ),
636
    ),
637
    'action' => array(
638
      'class' => 'RulesAction',
639
      'embeddable' => 'RulesActionContainer',
640
      'extenders' => array (
641
        'RulesPluginImplInterface' => array(
642
          'class' => 'RulesAbstractPluginDefaults',
643
        ),
644
        'RulesPluginFeaturesIntegrationInterace' => array(
645
          'methods' => array(
646
            'features_export' => 'rules_features_abstract_default_features_export',
647
          ),
648
        ),
649
        'RulesPluginUIInterface' => array(
650
          'class' => 'RulesAbstractPluginUI',
651
        ),
652
      ),
653
    ),
654
    'or' => array(
655
      'label' => t('Condition set (OR)'),
656
      'class' => 'RulesOr',
657
      'embeddable' => 'RulesConditionContainer',
658
      'component' => TRUE,
659
      'extenders' => array(
660
        'RulesPluginUIInterface' => array(
661
          'class' => 'RulesConditionContainerUI',
662
        ),
663
      ),
664
    ),
665
    'and' => array(
666
      'label' => t('Condition set (AND)'),
667
      'class' => 'RulesAnd',
668
      'embeddable' => 'RulesConditionContainer',
669
      'component' => TRUE,
670
      'extenders' => array(
671
        'RulesPluginUIInterface' => array(
672
          'class' => 'RulesConditionContainerUI',
673
        ),
674
      ),
675
    ),
676
    'action set' => array(
677
      'label' => t('Action set'),
678
      'class' => 'RulesActionSet',
679
      'embeddable' => FALSE,
680
      'component' => TRUE,
681
      'extenders' => array(
682
        'RulesPluginUIInterface' => array(
683
          'class' => 'RulesActionContainerUI',
684
        ),
685
      ),
686
    ),
687
    'rule' => array(
688
      'label' => t('Rule'),
689
      'class' => 'Rule',
690
      'embeddable' => 'RulesRuleSet',
691
      'component' => TRUE,
692
      'extenders' => array(
693
        'RulesPluginUIInterface' => array(
694
          'class' => 'RulesRuleUI',
695
        ),
696
      ),
697
    ),
698
    'loop' => array(
699
      'class' => 'RulesLoop',
700
      'embeddable' => 'RulesActionContainer',
701
      'extenders' => array(
702
        'RulesPluginUIInterface' => array(
703
          'class' => 'RulesLoopUI',
704
        ),
705
      ),
706
    ),
707
    'reaction rule' => array(
708
      'class' => 'RulesReactionRule',
709
      'embeddable' => FALSE,
710
      'extenders' => array(
711
        'RulesPluginUIInterface' => array(
712
          'class' => 'RulesReactionRuleUI',
713
        ),
714
      ),
715
    ),
716
    'event set' => array(
717
      'class' => 'RulesEventSet',
718
      'embeddable' => FALSE,
719
    ),
720
    'rule set' => array(
721
      'label' => t('Rule set'),
722
      'class' => 'RulesRuleSet',
723
      'component' => TRUE,
724
      // Rule sets don't get embedded - we use a separate action to execute.
725
      'embeddable' => FALSE,
726
      'extenders' => array(
727
        'RulesPluginUIInterface' => array(
728
          'class' => 'RulesRuleSetUI',
729
        ),
730
      ),
731
    ),
732
  );
733
}
734

    
735
/**
736
 * Implementation of hook_entity_info().
737
 */
738
function rules_entity_info() {
739
  return array(
740
    'rules_config' => array(
741
      'label' => t('Rules configuration'),
742
      'controller class' => 'RulesEntityController',
743
      'base table' => 'rules_config',
744
      'fieldable' => TRUE,
745
      'entity keys' => array(
746
        'id' => 'id',
747
        'name' => 'name',
748
        'label' => 'label',
749
      ),
750
      'module' => 'rules',
751
      'static cache' => TRUE,
752
      'bundles' => array(),
753
      'configuration' => TRUE,
754
      'exportable' => TRUE,
755
      'export' => array(
756
        'default hook' => 'default_rules_configuration',
757
      ),
758
      'access callback' => 'rules_config_access',
759
      'features controller class' => 'RulesFeaturesController',
760
    ),
761
  );
762
}
763

    
764
/**
765
 * Implementation of hook_hook_info().
766
 */
767
function rules_hook_info() {
768
  foreach(array('plugin_info', 'rules_directory', 'data_info', 'condition_info', 'action_info', 'event_info', 'file_info', 'evaluator_info', 'data_processor_info') as $hook) {
769
    $hooks['rules_' . $hook] = array(
770
      'group' => 'rules',
771
    );
772
    $hooks['rules_' . $hook . '_alter'] = array(
773
      'group' => 'rules',
774
    );
775
  }
776
  $hooks['default_rules_configuration'] = array(
777
    'group' => 'rules_defaults',
778
  );
779
  $hooks['default_rules_configuration_alter'] = array(
780
    'group' => 'rules_defaults',
781
  );
782
  return $hooks;
783
}
784

    
785
/**
786
 * Load rule configurations from the database.
787
 *
788
 * This function should be used whenever you need to load more than one entity
789
 * from the database. The entities are loaded into memory and will not require
790
 * database access if loaded again during the same page request.
791
 *
792
 * @see hook_entity_info()
793
 * @see RulesEntityController
794
 *
795
 * @param $names
796
 *   An array of rules configuration names or FALSE to load all.
797
 * @param $conditions
798
 *   An array of conditions in the form 'field' => $value.
799
 *
800
 * @return
801
 *   An array of rule configurations indexed by their ids.
802
 */
803
function rules_config_load_multiple($names = array(), $conditions = array()) {
804
  return entity_load_multiple_by_name('rules_config', $names, $conditions);
805
}
806

    
807
/**
808
 * Loads a single rule configuration from the database.
809
 *
810
 * @see rules_config_load_multiple()
811
 *
812
 * @return RulesPlugin
813
 */
814
function rules_config_load($name) {
815
  return entity_load_single('rules_config', $name);
816
}
817

    
818
/**
819
 * Returns an array of configured components.
820
 *
821
 * For actually executing a component use rules_invoke_component(), as this
822
 * retrieves the component from cache instead.
823
 *
824
 * @param $label
825
 *   Whether to return only the label or the whole component object.
826
 * @param $type
827
 *   Optionally filter for 'action' or 'condition' components.
828
 * @param $conditions
829
 *   An array of additional conditions as required by rules_config_load().
830
 *
831
 * @return
832
 *   An array keyed by component name containing either the label or the config.
833
 */
834
function rules_get_components($label = FALSE, $type = NULL, $conditions = array()) {
835
  $cache = rules_get_cache();
836
  $plugins = array_keys(rules_filter_array($cache['plugin_info'], 'component', TRUE));
837
  $conditions = $conditions + array('plugin' => $plugins);
838
  $faces = array(
839
    'action' => 'RulesActionInterface',
840
    'condition' => 'RulesConditionInterface',
841
  );
842
  $items = array();
843
  foreach (rules_config_load_multiple(FALSE, $conditions) as $name => $config) {
844
    if (!isset($type) || $config instanceof $faces[$type]) {
845
      $items[$name] = $label ? $config->label() : $config;
846
    }
847
  }
848
  return $items;
849
}
850

    
851
/**
852
 * Delete rule configurations from database.
853
 *
854
 * @param $ids
855
 *   An array of entity IDs.
856
 */
857
function rules_config_delete(array $ids) {
858
  return entity_get_controller('rules_config')->delete($ids);
859
}
860

    
861
/**
862
 * Ensures the configuration's 'dirty' flag is up to date by running an integrity check.
863
 *
864
 * @param $update
865
 *   (optional) Whether the dirty flag is also updated in the database if
866
 *   necessary. Defaults to TRUE.
867
 */
868
function rules_config_update_dirty_flag($rules_config, $update = TRUE) {
869
  // Keep a log of already check configurations to avoid repetitive checks on
870
  // oftent used components.
871
  // @see rules_element_invoke_component_validate()
872
  $checked = &drupal_static(__FUNCTION__, array());
873
  if (!empty($checked[$rules_config->name])) {
874
    return;
875
  }
876
  $checked[$rules_config->name] = TRUE;
877

    
878
  $was_dirty = !empty($rules_config->dirty);
879
  try {
880
    // First set the rule to dirty, so any repetitive checks give green light
881
    // for this configuration.
882
    $rules_config->dirty = FALSE;
883
    $rules_config->integrityCheck();
884
    if ($was_dirty) {
885
      $variables = array('%label' => $rules_config->label(), '%name' => $rules_config->name, '@plugin' => $rules_config->plugin());
886
      watchdog('rules', 'The @plugin %label (%name) was marked dirty, but passes the integrity check now and is active again.', $variables, WATCHDOG_INFO);
887
    }
888
  }
889
  catch (RulesIntegrityException $e) {
890
    $rules_config->dirty = TRUE;
891
    if (!$was_dirty) {
892
      $variables = array('%label' => $rules_config->label(), '%name' => $rules_config->name, '!message' => $e->getMessage(), '@plugin' => $rules_config->plugin());
893
      watchdog('rules', 'The @plugin %label (%name) fails the integrity check and cannot be executed. Error: !message', $variables, WATCHDOG_ERROR);
894
    }
895
  }
896
  // Save the updated dirty flag to the database.
897
  if ($was_dirty != $rules_config->dirty) {
898
    db_update('rules_config')
899
      ->fields(array('dirty' => (int) $rules_config->dirty))
900
      ->condition('id', $rules_config->id)
901
      ->execute();
902
  }
903
}
904

    
905
/**
906
 * Invokes a hook and the associated rules event.
907
 *
908
 * Calling this function does the same as calling module_invoke_all() and
909
 * rules_invoke_event() separately, however merges both functions into one in
910
 * order to ease usage and to work efficiently.
911
 *
912
 * @param $hook
913
 *   The name of the hook / event to invoke.
914
 * @param ...
915
 *   Arguments to pass to the hook / event.
916
 *
917
 * @return
918
 *   An array of return values of the hook implementations. If modules return
919
 *   arrays from their implementations, those are merged into one array.
920
 */
921
function rules_invoke_all() {
922
  // Copied code from module_invoke_all().
923
  $args = func_get_args();
924
  $hook = $args[0];
925
  unset($args[0]);
926
  $return = array();
927
  foreach (module_implements($hook) as $module) {
928
    $function = $module . '_' . $hook;
929
    if (function_exists($function)) {
930
      $result = call_user_func_array($function, $args);
931
      if (isset($result) && is_array($result)) {
932
        $return = array_merge_recursive($return, $result);
933
      }
934
      elseif (isset($result)) {
935
        $return[] = $result;
936
      }
937
    }
938
  }
939
  // Invoke the event.
940
  rules_invoke_event_by_args($hook, $args);
941

    
942
  return $return;
943
}
944

    
945
/**
946
 * Invokes configured rules for the given event.
947
 *
948
 * @param $event_name
949
 *   The event's name.
950
 * @param ...
951
 *   Pass parameters for the variables provided by this event, as defined in
952
 *   hook_rules_event_info(). Example given:
953
 *   @code
954
 *     rules_invoke_event('node_view', $node, $view_mode);
955
 *   @endcode
956
 *
957
 * @see rules_invoke_event_by_args()
958
 */
959
function rules_invoke_event() {
960
  global $conf;
961

    
962
  $args = func_get_args();
963
  $event_name = $args[0];
964
  unset($args[0]);
965
  // We maintain a whitelist of configured events to reduces the number of cache
966
  // reads. We access it directly via the global $conf as this is fast without
967
  // having to introduce another static cache. Then, if the whitelist is unset,
968
  // we ignore it so cache rebuilding is triggered.
969
  if (!defined('MAINTENANCE_MODE') && (!isset($conf['rules_event_whitelist']) || isset($conf['rules_event_whitelist'][$event_name])) && $event = rules_get_cache('event_' . $event_name)) {
970
    $event->executeByArgs($args);
971
  }
972
}
973

    
974
/**
975
 * Invokes configured rules for the given event.
976
 *
977
 * @param $event_name
978
 *   The event's name.
979
 * @param $args
980
 *   An array of parameters for the variables provided by the event, as defined
981
 *   in hook_rules_event_info(). Either pass an array keyed by the variable
982
 *   names or a numerically indexed array, in which case the ordering of the
983
 *   passed parameters has to match the order of the specified variables.
984
 *   Example given:
985
 *   @code
986
 *     rules_invoke_event_by_args('node_view', array('node' => $node, 'view_mode' => $view_mode));
987
 *   @endcode
988
 *
989
 * @see rules_invoke_event()
990
 */
991
function rules_invoke_event_by_args($event_name, $args = array()) {
992
  global $conf;
993

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

    
1003
/**
1004
 * Invokes a rule component, e.g. a rule set.
1005
 *
1006
 * @param $component_name
1007
 *   The component's name.
1008
 * @param $args
1009
 *   Pass further parameters as required for the invoked component.
1010
 *
1011
 * @return
1012
 *   An array of variables as provided by the component, or FALSE in case the
1013
 *   component could not be executed.
1014
 */
1015
function rules_invoke_component() {
1016
  $args = func_get_args();
1017
  $name = array_shift($args);
1018
  if ($component = rules_get_cache('comp_' . $name)) {
1019
    return $component->executeByArgs($args);
1020
  }
1021
  return FALSE;
1022
}
1023

    
1024
/**
1025
 * Filters the given array of arrays by keeping only entries which have $key set
1026
 * to the value of $value.
1027
 *
1028
 * @param $array
1029
 *   The array of arrays to filter.
1030
 * @param $key
1031
 *   The key used for the comparison.
1032
 * @param $value
1033
 *   The value to compare the array's entry to.
1034
 *
1035
 * @return array
1036
 *   The filtered array.
1037
 */
1038
function rules_filter_array($array, $key, $value) {
1039
  $return = array();
1040
  foreach ($array as $i => $entry) {
1041
    $entry += array($key => NULL);
1042
    if ($entry[$key] == $value) {
1043
      $return[$i] = $entry;
1044
    }
1045
  }
1046
  return $return;
1047
}
1048

    
1049
/**
1050
 * Merges the $update array into $array making sure no values of $array not
1051
 * appearing in $update are lost.
1052
 *
1053
 * @return
1054
 *   The updated array.
1055
 */
1056
function rules_update_array(array $array, array $update) {
1057
  foreach ($update as $key => $data) {
1058
    if (isset($array[$key]) && is_array($array[$key]) && is_array($data)) {
1059
      $array[$key] = rules_update_array($array[$key], $data);
1060
    }
1061
    else {
1062
      $array[$key] = $data;
1063
    }
1064
  }
1065
  return $array;
1066
}
1067

    
1068
/**
1069
 * Extracts the property with the given name.
1070
 *
1071
 * @param $arrays
1072
 *   An array of arrays from which a property is to be extracted.
1073
 * @param $key
1074
 *   The name of the property to extract.
1075
 *
1076
 * @return An array of extracted properties, keyed as in $arrays-
1077
 */
1078
function rules_extract_property($arrays, $key) {
1079
  $data = array();
1080
  foreach ($arrays as $name => $item) {
1081
    $data[$name] = $item[$key];
1082
  }
1083
  return $data;
1084
}
1085

    
1086
/**
1087
 * Returns the first key of the array.
1088
 */
1089
function rules_array_key($array) {
1090
  reset($array);
1091
  return key($array);
1092
}
1093

    
1094
/**
1095
 * Clean replacements so they are URL friendly.
1096
 *
1097
 * Can be used as 'cleaning callback' for action or condition parameters.
1098
 *
1099
 * @param $replacements
1100
 *   An array of token replacements that need to be "cleaned" for use in the URL.
1101
 * @param $data
1102
 *   An array of objects used to generate the replacements.
1103
 * @param $options
1104
 *   An array of options used to generate the replacements.
1105
 *
1106
 * @see rules_path_action_info()
1107
 */
1108
function rules_path_clean_replacement_values(&$replacements, $data = array(), $options = array()) {
1109
  // Include path.eval.inc which contains path cleaning functions.
1110
  module_load_include('inc', 'rules', 'modules/path.eval');
1111
  foreach ($replacements as $token => $value) {
1112
    $replacements[$token] = rules_clean_path($value);
1113
  }
1114
}
1115

    
1116
/**
1117
 * Implements hook_theme().
1118
 */
1119
function rules_theme() {
1120
  return array(
1121
    'rules_elements' => array(
1122
      'render element' => 'element',
1123
      'file' => 'ui/ui.theme.inc',
1124
    ),
1125
    'rules_content_group' => array(
1126
      'render element' => 'element',
1127
      'file' => 'ui/ui.theme.inc',
1128
    ),
1129
    'rules_parameter_configuration' => array(
1130
      'render element' => 'element',
1131
      'file' => 'ui/ui.theme.inc',
1132
    ),
1133
    'rules_variable_view' => array(
1134
      'render element' => 'element',
1135
      'file' => 'ui/ui.theme.inc',
1136
    ),
1137
    'rules_data_selector_help' => array(
1138
      'variables' => array('parameter' => NULL, 'variables' => NULL),
1139
      'file' => 'ui/ui.theme.inc',
1140
    ),
1141
    'rules_ui_variable_form' => array(
1142
      'render element' => 'element',
1143
      'file' => 'ui/ui.theme.inc',
1144
    ),
1145
    'rules_log' => array(
1146
      'render element' => 'element',
1147
      'file' => 'ui/ui.theme.inc',
1148
    ),
1149
    'rules_autocomplete' => array(
1150
      'render element' => 'element',
1151
      'file' => 'ui/ui.theme.inc',
1152
    ),
1153
    'rules_debug_element' => array(
1154
      'render element' => 'element',
1155
      'file' => 'ui/ui.theme.inc',
1156
    ),
1157
    'rules_settings_help' => array(
1158
      'variables' => array('text' => '', 'heading' => ''),
1159
      'file' => 'ui/ui.theme.inc',
1160
    ),
1161
  );
1162
}
1163

    
1164
/**
1165
 * Implements hook_permission().
1166
 */
1167
function rules_permission() {
1168
  $perms = array(
1169
    'administer rules' => array(
1170
      'title' => t('Administer rule configurations'),
1171
      'description' => t('Administer rule configurations including events, conditions and actions for which the user has sufficient access permissions.'),
1172
    ),
1173
    'bypass rules access' => array(
1174
      'title' => t('Bypass Rules access control'),
1175
      'description' => t('Control all configurations regardless of permission restrictions of events, conditions or actions.'),
1176
      'restrict access' => TRUE,
1177
    ),
1178
    'access rules debug' => array(
1179
      'title' => t('Access the Rules debug log'),
1180
    ),
1181
  );
1182

    
1183
  // Fetch all components to generate the access keys.
1184
  $conditions['plugin'] = array_keys(rules_filter_array(rules_fetch_data('plugin_info'), 'component', TRUE));
1185
  $conditions['access_exposed'] = 1;
1186
  $components = entity_load('rules_config', FALSE, $conditions);
1187
  $perms += rules_permissions_by_component($components);
1188

    
1189
  return $perms;
1190
}
1191

    
1192
/**
1193
 * Helper function to get all the permissions for components that have access exposed.
1194
 */
1195
function rules_permissions_by_component(array $components = array()) {
1196
  $perms = array();
1197
  foreach ($components as $component) {
1198
    $perms += array(
1199
      "use Rules component $component->name" => array(
1200
        'title' => t('Use Rules component %component', array('%component' => $component->label())),
1201
        '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)))),
1202
      ),
1203
    );
1204
  }
1205
  return $perms;
1206
}
1207

    
1208
/**
1209
 * Menu callback for loading rules configuration elements.
1210
 * @see RulesUIController::config_menu()
1211
 */
1212
function rules_element_load($element_id, $config_name) {
1213
  $config = rules_config_load($config_name);
1214
  return $config->elementMap()->lookup($element_id);
1215
}
1216

    
1217
/**
1218
 * Menu callback for getting the title as configured.
1219
 * @see RulesUIController::config_menu()
1220
 */
1221
function rules_get_title($text, $element) {
1222
  if ($element instanceof RulesPlugin) {
1223
    $cache = rules_get_cache();
1224
    $plugin = $element->plugin();
1225
    $plugin = isset($cache['plugin_info'][$plugin]['label']) ? $cache['plugin_info'][$plugin]['label'] : $plugin;
1226
    $plugin = drupal_strtolower(drupal_substr($plugin, 0, 1)) . drupal_substr($plugin, 1);
1227
    return t($text, array('!label' => $element->label(), '!plugin' => $plugin));
1228
  }
1229
  // As fallback treat $element as simple string.
1230
  return t($text, array('!plugin' => $element));
1231
}
1232

    
1233
/**
1234
 * Menu callback for getting the title for the add element page.
1235
 *
1236
 * Uses a work-a-round for accessing the plugin name.
1237
 * @see RulesUIController::config_menu()
1238
 */
1239
function rules_menu_add_element_title($array) {
1240
  $plugin_name = arg($array[0]);
1241
  $cache = rules_get_cache();
1242
  if (isset($cache['plugin_info'][$plugin_name]['class'])) {
1243
    $info = $cache['plugin_info'][$plugin_name] + array('label' => $plugin_name);
1244
    $label = drupal_strtolower(drupal_substr($info['label'], 0, 1)) . drupal_substr($info['label'], 1);
1245
    return t('Add a new !plugin', array('!plugin' => $label));
1246
  }
1247
}
1248

    
1249
/**
1250
 * Returns the current region for the debug log.
1251
 */
1252
function rules_debug_log_region() {
1253
  // If there is no setting for the current theme use the default theme setting.
1254
  global $theme_key;
1255
  $theme_default = variable_get('theme_default', 'bartik');
1256
  return variable_get('rules_debug_region_' . $theme_key, variable_get('rules_debug_region_' . $theme_default, 'help'));
1257
}
1258

    
1259
/**
1260
 * Implements hook_page_build() to add the rules debug log to the page bottom.
1261
 */
1262
function rules_page_build(&$page) {
1263
  // Invoke a the page redirect, in case the action has been executed.
1264
  // @see rules_action_drupal_goto()
1265
  if (isset($GLOBALS['_rules_action_drupal_goto_do'])) {
1266
    list($url, $force) = $GLOBALS['_rules_action_drupal_goto_do'];
1267
    drupal_goto($url);
1268
  }
1269

    
1270
  if (isset($_SESSION['rules_debug'])) {
1271
    $region = rules_debug_log_region();
1272
    foreach ($_SESSION['rules_debug'] as $log) {
1273
      $page[$region]['rules_debug'][] = array(
1274
        '#markup' => $log,
1275
      );
1276
      $page[$region]['rules_debug']['#theme_wrappers'] = array('rules_log');
1277
    }
1278
    unset($_SESSION['rules_debug']);
1279
  }
1280

    
1281
  if (rules_show_debug_output()) {
1282
    $region = rules_debug_log_region();
1283
    $page[$region]['rules_debug']['#pre_render'] = array('rules_debug_log_pre_render');
1284
  }
1285
}
1286

    
1287
/**
1288
 * Pre-render callback for the debug log, which renders and then clears it.
1289
 */
1290
function rules_debug_log_pre_render($elements) {
1291
  $logger = RulesLog::logger();
1292
  if ($log = $logger->render()) {
1293
    $logger = RulesLog::logger();
1294
    $logger->clear();
1295
    $elements[] = array('#markup' => $log);
1296
    $elements['#theme_wrappers'] = array('rules_log');
1297
    // Log the rules log to the system log if enabled.
1298
    if (variable_get('rules_debug_log', FALSE)) {
1299
      watchdog('rules', 'Rules debug information: !log', array('!log' => $log), WATCHDOG_NOTICE);
1300
    }
1301
  }
1302
  return $elements;
1303
}
1304

    
1305
/**
1306
 * Implements hook_drupal_goto_alter().
1307
 *
1308
 * @see rules_action_drupal_goto()
1309
 */
1310
function rules_drupal_goto_alter(&$path, &$options, &$http_response_code) {
1311
  // Invoke a the page redirect, in case the action has been executed.
1312
  if (isset($GLOBALS['_rules_action_drupal_goto_do'])) {
1313
    list($url, $force) = $GLOBALS['_rules_action_drupal_goto_do'];
1314

    
1315
    if ($force || !isset($_GET['destination'])) {
1316
      $url = drupal_parse_url($url);
1317
      $path = $url['path'];
1318
      $options['query'] = $url['query'];
1319
      $options['fragment'] = $url['fragment'];
1320
      $http_response_code = 302;
1321
    }
1322
  }
1323
}
1324

    
1325
/**
1326
 * Returns whether the debug log should be shown.
1327
 */
1328
function rules_show_debug_output() {
1329
  if (variable_get('rules_debug', FALSE) == RulesLog::INFO && user_access('access rules debug')) {
1330
    return TRUE;
1331
  }
1332
  // For performance avoid unnecessary auto-loading of the RulesLog class.
1333
  return variable_get('rules_debug', FALSE) == RulesLog::WARN && user_access('access rules debug') && class_exists('RulesLog', FALSE) && RulesLog::logger()->hasErrors();
1334
}
1335

    
1336
/**
1337
 * Implements hook_exit().
1338
 */
1339
function rules_exit() {
1340
  // Bail out if this is cached request and modules are not loaded.
1341
  if (!module_exists('rules') || !module_exists('user')) {
1342
    return;
1343
  }
1344
  if (rules_show_debug_output()) {
1345
    if ($log = RulesLog::logger()->render()) {
1346
      // Keep the log in the session so we can show it on the next page.
1347
      $_SESSION['rules_debug'][] = $log;
1348
    }
1349
  }
1350
  // Log the rules log to the system log if enabled.
1351
  if (variable_get('rules_debug_log', FALSE) && $log = RulesLog::logger()->render()) {
1352
    watchdog('rules', 'Rules debug information: !log', array('!log' => $log), WATCHDOG_NOTICE);
1353
  }
1354
}
1355

    
1356
/**
1357
 * Implements hook_element_info().
1358
 */
1359
function rules_element_info() {
1360
  // A duration form element for rules. Needs ui.forms.inc included.
1361
  $types['rules_duration'] = array(
1362
    '#input' => TRUE,
1363
    '#tree' => TRUE,
1364
    '#default_value' => 0,
1365
    '#value_callback' => 'rules_ui_element_duration_value',
1366
    '#process' => array('rules_ui_element_duration_process', 'ajax_process_form'),
1367
    '#after_build' => array('rules_ui_element_duration_after_build'),
1368
    '#pre_render' => array('form_pre_render_conditional_form_element'),
1369
  );
1370
  $types['rules_data_selection'] = array(
1371
    '#input' => TRUE,
1372
    '#pre_render' => array('form_pre_render_conditional_form_element'),
1373
    '#process' => array('rules_data_selection_process', 'ajax_process_form'),
1374
    '#theme' => 'rules_autocomplete',
1375
  );
1376
  return $types;
1377
}
1378

    
1379
/**
1380
 * Implements hook_modules_enabled().
1381
 */
1382
function rules_modules_enabled($modules) {
1383
  // Re-enable Rules configurations that are dirty, because they require one of
1384
  // the enabled the modules.
1385
  $query = db_select('rules_dependencies', 'rd');
1386
  $query->join('rules_config', 'rc', 'rd.id = rc.id');
1387
  $query->fields('rd', array('id'))
1388
        ->condition('rd.module', $modules, 'IN')
1389
        ->condition('rc.dirty', 1);
1390
  $ids = $query->execute()->fetchCol();
1391

    
1392
  // If there are some configurations that might work again, re-check all dirty
1393
  // configurations as others might work again too, e.g. consider a rule that is
1394
  // dirty because it requires a dirty component.
1395
  if ($ids) {
1396
    $rules_configs = rules_config_load_multiple(FALSE, array('dirty' => 1));
1397
    foreach ($rules_configs as $rules_config) {
1398
      try {
1399
        $rules_config->integrityCheck();
1400
        // If no exceptions were thrown we can set the configuration back to OK.
1401
        db_update('rules_config')
1402
          ->fields(array('dirty' => 0))
1403
          ->condition('id', $rules_config->id)
1404
          ->execute();
1405
        if ($rules_config->active) {
1406
          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())));
1407
        }
1408
      }
1409
      catch (RulesIntegrityException $e) {
1410
        // The rule is still dirty, so do nothing.
1411
      }
1412
    }
1413
  }
1414
  rules_clear_cache();
1415
}
1416

    
1417
/**
1418
 * Implements hook_modules_disabled().
1419
 */
1420
function rules_modules_disabled($modules) {
1421
  // Disable Rules configurations that depend on one of the disabled modules.
1422
  $query = db_select('rules_dependencies', 'rd');
1423
  $query->join('rules_config', 'rc', 'rd.id = rc.id');
1424
  $query->fields('rd', array('id'))
1425
        ->distinct()
1426
        ->condition('rd.module', $modules, 'IN')
1427
        ->condition('rc.dirty', 0);
1428
  $ids = $query->execute()->fetchCol();
1429

    
1430
  if (!empty($ids)) {
1431
    db_update('rules_config')
1432
      ->fields(array('dirty' => 1))
1433
      ->condition('id', $ids, 'IN')
1434
      ->execute();
1435
    // Tell the user about enabled rules that have been marked as dirty.
1436
    $count = db_select('rules_config', 'r')
1437
      ->fields('r')
1438
      ->condition('id', $ids, 'IN')
1439
      ->condition('active', 1)
1440
      ->execute()->rowCount();
1441
    if ($count > 0) {
1442
      $message = format_plural($count,
1443
        '1 Rules configuration requires some of the disabled modules to function and cannot be executed any more.',
1444
        '@count Rules configuration require some of the disabled modules to function and cannot be executed any more.'
1445
      );
1446
      drupal_set_message($message, 'warning');
1447
    }
1448
  }
1449
  rules_clear_cache();
1450
}
1451

    
1452
/**
1453
 * Access callback for dealing with Rules configurations.
1454
 *
1455
 * @see entity_access()
1456
 */
1457
function rules_config_access($op, $rules_config = NULL, $account = NULL) {
1458
  if (user_access('bypass rules access', $account)) {
1459
    return TRUE;
1460
  }
1461
  // Allow modules to grant / deny access.
1462
  $access = module_invoke_all('rules_config_access', $op, $rules_config, $account);
1463

    
1464
  // Only grant access if at least one module granted access and no one denied
1465
  // access.
1466
  if (in_array(FALSE, $access, TRUE)) {
1467
    return FALSE;
1468
  }
1469
  elseif (in_array(TRUE, $access, TRUE)) {
1470
    return TRUE;
1471
  }
1472
  return FALSE;
1473
}
1474

    
1475
/**
1476
 * Implements hook_rules_config_access().
1477
 */
1478
function rules_rules_config_access($op, $rules_config = NULL, $account = NULL) {
1479
  // Instead of returning FALSE return nothing, so others still can grant
1480
  // access.
1481
  if (!isset($rules_config) || (isset($account) && $account->uid != $GLOBALS['user']->uid)) {
1482
    return;
1483
  }
1484
  if (user_access('administer rules', $account) && ($op == 'view' || $rules_config->access())) {
1485
    return TRUE;
1486
  }
1487
}
1488

    
1489
/**
1490
 * Implements hook_menu().
1491
 */
1492
function rules_menu() {
1493
  $items['admin/config/workflow/rules/upgrade'] = array(
1494
    'title' => 'Upgrade',
1495
    'page callback' => 'drupal_get_form',
1496
    'page arguments' => array('rules_upgrade_form'),
1497
    'access arguments' => array('administer rules'),
1498
    'file' => 'includes/rules.upgrade.inc',
1499
    'file path' => drupal_get_path('module', 'rules'),
1500
    'type' => MENU_CALLBACK,
1501
  );
1502
  $items['admin/config/workflow/rules/upgrade/clear'] = array(
1503
    'title' => 'Clear',
1504
    'page callback' => 'drupal_get_form',
1505
    'page arguments' => array('rules_upgrade_confirm_clear_form'),
1506
    'access arguments' => array('administer rules'),
1507
    'file' => 'includes/rules.upgrade.inc',
1508
    'file path' => drupal_get_path('module', 'rules'),
1509
    'type' => MENU_CALLBACK,
1510
  );
1511
  $items['admin/config/workflow/rules/autocomplete_tags'] = array(
1512
    'title' => 'Rules tags autocomplete',
1513
    'page callback' => 'rules_autocomplete_tags',
1514
    'page arguments' => array(5),
1515
    'access arguments' => array('administer rules'),
1516
    'file' => 'ui/ui.forms.inc',
1517
    'type' => MENU_CALLBACK,
1518
  );
1519
  return $items;
1520
}
1521

    
1522
/**
1523
 * Helper function to keep track of external documentation pages for Rules.
1524
 *
1525
 * @param $topic
1526
 *   The topic key for used for identifying help pages.
1527
 *
1528
 * @return
1529
 *   Either a URL for the given page, or the full list of external help pages.
1530
 */
1531
function rules_external_help($topic = NULL) {
1532
  $help = array(
1533
    'rules' =>                'http://drupal.org/node/298480',
1534
    'terminology' =>          'http://drupal.org/node/1299990',
1535
    'condition-components' => 'http://drupal.org/node/1300034',
1536
    'data-selection' =>       'http://drupal.org/node/1300042',
1537
    'chained-tokens' =>       'http://drupal.org/node/1300042',
1538
    'loops' =>                'http://drupal.org/node/1300058',
1539
    'components' =>           'http://drupal.org/node/1300024',
1540
    'component-types' =>      'http://drupal.org/node/1300024',
1541
    'variables' =>            'http://drupal.org/node/1300024',
1542
    'scheduler' =>            'http://drupal.org/node/1300068',
1543
    'coding' =>               'http://drupal.org/node/878720',
1544
  );
1545

    
1546
  if (isset($topic)) {
1547
    return isset($help[$topic]) ? $help[$topic] : FALSE;
1548
  }
1549
  return $help;
1550
}
1551

    
1552
/**
1553
 * Implements hook_help().
1554
 */
1555
function rules_help($path, $arg) {
1556
  // Only enable the help if the admin module is active.
1557
  if ($path == 'admin/help#rules' && module_exists('rules_admin')) {
1558

    
1559
    $output['header'] = array(
1560
      '#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!'),
1561
    );
1562
    // Build a list of essential Rules help pages, formatted as a bullet list.
1563
    $link_list['rules'] = l(t('Rules introduction'), rules_external_help('rules'));
1564
    $link_list['terminology'] = l(t('Rules terminology'), rules_external_help('terminology'));
1565
    $link_list['scheduler'] = l(t('Rules Scheduler'), rules_external_help('scheduler'));
1566
    $link_list['coding'] = l(t('Coding for Rules'), rules_external_help('coding'));
1567

    
1568
    $output['topic-list'] = array(
1569
      '#markup' => theme('item_list', array('items' => $link_list)),
1570
    );
1571
    return render($output);
1572
  }
1573
}
1574

    
1575
/**
1576
 * Implements hook_token_info().
1577
 */
1578
function rules_token_info() {
1579
  $cache = rules_get_cache();
1580
  $data_info = $cache['data_info'];
1581

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

    
1584
  foreach ($types as $type) {
1585
    $token_type = $data_info[$type]['token type'];
1586

    
1587
    $token_info['types'][$token_type] = array(
1588
      'name' => $data_info[$type]['label'],
1589
      'description' => t('Tokens related to %label Rules variables.', array('%label' => $data_info[$type]['label'])),
1590
      'needs-data' => $token_type,
1591
    );
1592
    $token_info['tokens'][$token_type]['value'] = array(
1593
      'name' => t("Value"),
1594
      'description' => t('The value of the variable.'),
1595
    );
1596
  }
1597
  return $token_info;
1598
}
1599

    
1600
/**
1601
 * Implements hook_tokens().
1602
 */
1603
function rules_tokens($type, $tokens, $data, $options = array()) {
1604
  // Handle replacements of primitive variable types.
1605
  if (substr($type, 0, 6) == 'rules_' && !empty($data[$type])) {
1606
    // Leverage entity tokens token processor by passing on as struct.
1607
    $info['property info']['value'] = array(
1608
      'type' => substr($type, 6),
1609
      'label' => '',
1610
    );
1611
    // Entity tokens uses metadata wrappers as values for 'struct' types.
1612
    $wrapper = entity_metadata_wrapper('struct', array('value' => $data[$type]), $info);
1613
    return entity_token_tokens('struct', $tokens, array('struct' => $wrapper), $options);
1614
  }
1615
}
1616

    
1617
/**
1618
 * Helper function that retrieves a metadata wrapper with all properties.
1619
 *
1620
 * Note that without this helper, bundle-specific properties aren't added.
1621
 */
1622
function rules_get_entity_metadata_wrapper_all_properties(RulesAbstractPlugin $element) {
1623
  return entity_metadata_wrapper($element->settings['type'], NULL, array(
1624
    'property info alter' => 'rules_entity_metadata_wrapper_all_properties_callback',
1625
  ));
1626
}
1627

    
1628
/**
1629
 * Callback that returns a metadata wrapper with all properties.
1630
 */
1631
function rules_entity_metadata_wrapper_all_properties_callback(EntityMetadataWrapper $wrapper, $property_info) {
1632
  $info = $wrapper->info();
1633
  $properties = entity_get_all_property_info($info['type']);
1634
  $property_info['properties'] += $properties;
1635
  return $property_info;
1636
}