rules.module 52.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
<?php

/**
 * @file Rules engine module
 */

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

/**
 * Implements hook_init().
 */
function rules_init() {
  rules_invoke_event('init');
}

/**
 * Returns an instance of the rules UI controller, which eases re-using the Rules UI.
 *
 * See the rules_admin.module for example usage.
 *
 * @return RulesUIController
 */
function rules_ui() {
  $static = drupal_static(__FUNCTION__);
  if (!isset($static)) {
    $static = new RulesUIController();
  }
  return $static;
}

/**
 * Returns a new rules action.
 *
 * @param $name
 *   The action's name.
 * @param $settings
 *   The action's settings array.
 * @return RulesAction
 */
function rules_action($name, $settings = array()) {
  return rules_plugin_factory('action', $name, $settings);
}

/**
 * Returns a new rules condition.
 *
 * @param $name
 *   The condition's name.
 * @param $settings
 *   The condition's settings array.
 * @return RulesCondition
 */
function rules_condition($name, $settings = array()) {
  return rules_plugin_factory('condition', $name, $settings);
}

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

/**
 * Creates a new reaction rule.
 *
 * @return RulesReactionRule
 */
function rules_reaction_rule() {
  return rules_plugin_factory('reaction rule');
}

/**
 * Creates a logical OR condition container.
 *
 * @param $variables
 *   An optional array as for rule().
 * @return RulesOr
 */
function rules_or($variables = NULL) {
  return rules_plugin_factory('or', $variables);
}

/**
 * Creates a logical AND condition container.
 *
 * @param $variables
 *   An optional array as for rule().
 * @return RulesAnd
 */
function rules_and($variables = NULL) {
  return rules_plugin_factory('and', $variables);
}

/**
 * Creates a loop.
 *
 * @param $settings
 *   The loop settings, containing
 *     'list:select': The data selector for the list to loop over.
 *     'item:var': Optionally a name for the list item variable.
 *     'item:label': Optionally a lebel for the list item variable.
 * @param $variables
 *   An optional array as for rule().
 * @return RulesLoop
 */
function rules_loop($settings = array(), $variables = NULL) {
  return rules_plugin_factory('loop', $settings, $variables);
}

/**
 * Creates a rule set.
 *
 * @param $variables
 *   An array as for rule().
 * @param $provides
 *   The names of variables which should be provided to the caller. See rule().
 * @return RulesRuleSet
 */
function rules_rule_set($variables = array(), $provides = array()) {
  return rules_plugin_factory('rule set', $variables, $provides);
}

/**
 * Creates an action set.
 *
 * @param $variables
 *   An array as for rule().
 * @param $provides
 *   The names of variables which should be provided to the caller. See rule().
 * @return RulesActionSet
 */
function rules_action_set($variables = array(), $provides = array()) {
  return rules_plugin_factory('action set', $variables, $provides);
}

/**
 * Log a message to the rules logger.
 *
 * @param $msg
 *   The message to log.
 * @param $args
 *   An array of placeholder arguments as used by t().
 * @param $priority
 *   A priority as defined by the RulesLog class.
 * @param RulesPlugin $element
 *  (optional) The RulesElement causing the log entry.
 * @param boolean $scope
 *  (optional) This may be used to denote the beginning (TRUE) or the end
 *  (FALSE) of a new execution scope.
 */
function rules_log($msg, $args = array(), $priority = RulesLog::INFO, RulesPlugin $element = NULL, $scope = NULL) {
  static $logger, $settings;

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

  if ($priority >= $settings['rules_log_errors']) {
    $link = NULL;
    if (isset($element) && isset($element->root()->name)) {
      $link = l(t('edit configuration'), RulesPluginUI::path($element->root()->name, 'edit', $element));
    }
    watchdog('rules', $msg, $args, $priority == RulesLog::WARN ? WATCHDOG_WARNING : WATCHDOG_ERROR, $link);
  }
  // Do nothing in case debugging is totally disabled.
  if (!$settings['rules_debug_log'] && !$settings['rules_debug']) {
    return;
  }
  if (!isset($logger)) {
    $logger = RulesLog::logger();
  }
  $path = isset($element) && isset($element->root()->name) ? RulesPluginUI::path($element->root()->name, 'edit', $element) : NULL;
  $logger->log($msg, $args, $priority, $scope, $path);
}

/**
 * Fetches module definitions for the given hook name.
 *
 * Used for collecting events, rules, actions and condtions from other modules.
 *
 * @param $hook
 *   The hook of the definitions to get from invoking hook_rules_{$hook}.
 */
function rules_fetch_data($hook) {
  $data = &drupal_static(__FUNCTION__, array());
  static $discover = array(
    'action_info' => 'RulesActionHandlerInterface',
    'condition_info' => 'RulesConditionHandlerInterface',
    'event_info' => 'RulesEventHandlerInterface',
  );

  if (!isset($data[$hook])) {
    foreach (module_implements('rules_' . $hook) as $module) {
      $result = call_user_func($module . '_rules_' . $hook);
      if (isset($result) && is_array($result)) {
        foreach ($result as $name => $item) {
          $item += array('module' => $module);
          $data[$hook][$name] = $item;
        }
      }
    }
    // Support class discovery.
    if (isset($discover[$hook])) {
      $data[$hook] += rules_discover_plugins($discover[$hook]);
    }
    drupal_alter('rules_'. $hook, $data[$hook]);
  }
  return $data[$hook];
}

/**
 * Discover plugin implementations.
 *
 * Class based plugin handlers must be loaded when rules caches are rebuilt,
 * such that they get discovered properly. You have the following options:
 *  - Put it into a regular module file (discouraged)
 *  - Put it into your module.rules.inc file
 *  - Put it in any file and declare it using hook_rules_file_info()
 *  - Put it in any file and declare it using hook_rules_directory()
 *
 * In addition to that, the class must be loadable via regular class
 * auto-loading, thus put the file holding the class in your info file or use
 * another class-loader.
 *
 * @param string $class
 *   The class or interface the plugins must implement. For a plugin to be
 *   discovered it must have a static getInfo() method also.
 *
 * @return array
 *   An info-hook style array containing info about discovered plugins.
 *
 * @see RulesActionHandlerInterface
 * @see RulesConditionHandlerInterface
 * @see RulesEventHandlerInterface
 */
function rules_discover_plugins($class) {
  // Make sure all files possibly holding plugins are included.
  RulesAbstractPlugin::includeFiles();

  $items = array();
  foreach (get_declared_classes() as $plugin_class) {
    if (is_subclass_of($plugin_class, $class) && method_exists($plugin_class, 'getInfo')) {
      $info = call_user_func(array($plugin_class, 'getInfo'));
      $info['class'] = $plugin_class;
      $info['module'] = _rules_discover_module($plugin_class);
      $items[$info['name']] = $info;
    }
  }
  return $items;
}

/**
 * Determines the module providing the given class.
 */
function _rules_discover_module($class) {
  $paths = &drupal_static(__FUNCTION__);

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

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

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

/**
 * Gets a rules cache entry.
 */
function &rules_get_cache($cid = 'data') {
  // Make use of the fast, advanced drupal static pattern.
  static $drupal_static_fast;
  if (!isset($drupal_static_fast)) {
    $drupal_static_fast['cache'] = &drupal_static(__FUNCTION__, array());
  }
  $cache = &$drupal_static_fast['cache'];

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

    if ($get = cache_get($cid . $cid_suffix, 'cache_rules')) {
      $cache[$cid] = $get->data;
    }
    elseif ($cid === 'data') {
      // There is no 'data' cache so we need to rebuild it. Make sure subsequent
      // cache gets of the main 'data' cache during rebuild get the interim
      // cache by passing in the reference of the static cache variable.
      _rules_rebuild_cache($cache['data']);
    }
    elseif (strpos($cid, 'comp_') === 0) {
      $cache[$cid] = FALSE;
      _rules_rebuild_component_cache();
    }
    elseif (strpos($cid, 'event_') === 0) {
      $cache[$cid] = FALSE;
      RulesEventSet::rebuildEventCache();
    }
    else {
      $cache[$cid] = FALSE;
    }
  }
  return $cache[$cid];
}

/**
 * Rebuilds the rules cache.
 *
 * This rebuilds the rules 'data' cache and invokes rebuildCache() methods on
 * all plugin classes, which allows plugins to add their own data to the cache.
 * The cache is rebuilt in the order the plugins are defined.
 *
 * Note that building the action/condition info cache triggers loading of all
 * components, thus depends on entity-loading and so syncing entities in code
 * to the database.
 *
 * @see rules_rules_plugin_info()
 * @see entity_defaults_rebuild()
 */
function _rules_rebuild_cache(&$cache) {
  foreach(array('data_info', 'plugin_info') as $hook) {
    $cache[$hook] = rules_fetch_data($hook);
  }
  foreach ($cache['plugin_info'] as $name => &$info) {
    // Let the items add something to the cache.
    $item = new $info['class']();
    $item->rebuildCache($info, $cache);
  }
  $cid_suffix = ':' . $GLOBALS['language']->language;
  cache_set('data' . $cid_suffix, $cache, 'cache_rules');
}

/**
 * Cache components to allow efficient usage via rules_invoke_component().
 *
 * @see rules_invoke_component()
 * @see rules_get_cache()
 */
function _rules_rebuild_component_cache() {
  $components = rules_get_components();

  foreach ($components as $id => $component) {
    // If a component is marked as dirty, check if this still applies.
    if ($component->dirty) {
      rules_config_update_dirty_flag($component);
    }
    if (!$component->dirty) {
      // Clone the component to avoid modules getting the to be cached
      // version from the static loading cache.
      $component = clone $component;
      $component->optimize();
      // Allow modules to alter the cached component.
      drupal_alter('rules_component', $component->plugin, $component);
      rules_set_cache('comp_' . $component->name, $component);
    }
  }
}

/**
 * Sets a rules cache item.
 *
 * In addition to calling cache_set(), this function makes sure the cache item
 * is immediately available via rules_get_cache() by keeping all cache items
 * in memory. That way we can guarantee rules_get_cache() is able to retrieve
 * any cache item, even if all cache gets fail.
 *
 * @see rules_get_cache()
 */
function rules_set_cache($cid, $data) {
  $cache = &drupal_static('rules_get_cache', array());
  $cache[$cid] = $data;
  cache_set($cid, $data, 'cache_rules');
}

/**
 * Implements hook_flush_caches().
 */
function rules_flush_caches() {
  return array('cache_rules');
}

/**
 * Clears the rule set cache
 */
function rules_clear_cache() {
  cache_clear_all('*', 'cache_rules', TRUE);
  variable_del('rules_event_whitelist');
  drupal_static_reset('rules_get_cache');
  drupal_static_reset('rules_fetch_data');
  drupal_static_reset('rules_config_update_dirty_flag');
  entity_get_controller('rules_config')->resetCache();
}

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


/**
 * Wraps the given data.
 *
 * @param $data
 *   If available, the actual data, else NULL.
 * @param $info
 *   An array of info about this data.
 * @param $force
 *   Usually data is only wrapped if really needed. If set to TRUE, wrapping the
 *   data is forced, so primitive data types are also wrapped.
 * @return EntityMetadataWrapper
 *   An EntityMetadataWrapper or the unwrapped data.
 *
 * @see hook_rules_data_info()
 */
function &rules_wrap_data($data = NULL, $info, $force = FALSE) {
  // If the data is already wrapped, use the existing wrapper.
  if ($data instanceof EntityMetadataWrapper) {
    return $data;
  }
  $cache = rules_get_cache();
  // Define the keys to be passed through to the metadata wrapper.
  $wrapper_keys = array_flip(array('property info', 'property defaults'));
  if (isset($cache['data_info'][$info['type']])) {
    $info += array_intersect_key($cache['data_info'][$info['type']], $wrapper_keys);
  }
  // If a list is given, also add in the info of the item type.
  $list_item_type = entity_property_list_extract_type($info['type']);
  if ($list_item_type && isset($cache['data_info'][$list_item_type])) {
    $info += array_intersect_key($cache['data_info'][$list_item_type], $wrapper_keys);
  }
  // By default we do not wrap the data, except for completely unknown types.
  if (!empty($cache['data_info'][$info['type']]['wrap']) || $list_item_type || $force || empty($cache['data_info'][$info['type']])) {
    unset($info['handler']);
    // Allow data types to define custom wrapper classes.
    if (!empty($cache['data_info'][$info['type']]['wrapper class'])) {
      $class = $cache['data_info'][$info['type']]['wrapper class'];
      $wrapper = new $class($info['type'], $data, $info);
    }
    else {
      $wrapper = entity_metadata_wrapper($info['type'], $data, $info);
    }
    return $wrapper;
  }
  return $data;
}

/**
 * Unwraps the given data, if it's wrapped.
 *
 * @param $data
 *   An array of wrapped data.
 * @param $info
 *   Optionally an array of info about how to unwrap the data. Keyed as $data.
 * @return
 *   An array containing unwrapped or passed through data.
 */
function rules_unwrap_data(array $data, $info = array()) {
  $cache = rules_get_cache();
  foreach ($data as $key => $entry) {
    // If it's a wrapper, unwrap unless specified otherwise.
    if ($entry instanceof EntityMetadataWrapper) {
      if (!isset($info[$key]['allow null'])) {
        $info[$key]['allow null'] = FALSE;
      }
      if (!isset($info[$key]['wrapped'])) {
        // By default, do not unwrap special data types that are always wrapped.
        $info[$key]['wrapped'] = (isset($info[$key]['type']) && is_string($info[$key]['type']) && !empty($cache['data_info'][$info[$key]['type']]['is wrapped']));
      }
      // Activate the decode option by default if 'sanitize' is not enabled, so
      // any text is either sanitized or decoded.
      // @see EntityMetadataWrapper::value()
      $options = $info[$key] + array('decode' => empty($info[$key]['sanitize']));

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

          if (!$info[$key]['wrapped']) {
            $data[$key] = $value;
          }
          if (!$info[$key]['allow null'] && !isset($value)) {
            throw new RulesEvaluationException('The variable or parameter %name is empty.', array('%name' => $key));
          }
        }
      }
      catch (EntityMetadataWrapperException $e) {
        throw new RulesEvaluationException('Unable to get the data value for the variable or parameter %name. Error: !error', array('%name' => $key, '!error' => $e->getMessage()));
      }
    }
  }
  return $data;
}

/**
 * Gets event info for a given event.
 *
 * @param string $event_name
 *   A (configured) event name.
 *
 * @return array
 *   An array of event info. If the event is unknown, a suiting info array is
 *   generated and returned
 */
function rules_get_event_info($event_name) {
  $base_event_name = rules_get_event_base_name($event_name);
  $events = rules_fetch_data('event_info');
  if (isset($events[$base_event_name])) {
    return $events[$base_event_name] + array('name' => $base_event_name);
  }
  return array(
    'label' => t('Unknown event "!event_name"', array('!event_name' => $base_event_name)),
    'name' => $base_event_name,
  );
}

/**
 * Returns the base name of a configured event name.
 *
 * For a configured event name like node_view--article the base event name
 * node_view is returned.
 *
 * @return string
 *   The event base name.
 */
function rules_get_event_base_name($event_name) {
  // Cut off any suffix from a configured event name.
  if (strpos($event_name, '--') !== FALSE) {
    $parts = explode('--', $event_name, 2);
    return $parts[0];
  }
  return $event_name;
}

/**
 * Returns the rule event handler for the given event.
 *
 * Events having no settings are handled via the class RulesEventSettingsNone.
 *
 * @param string $event_name
 *   The event name (base or configured).
 * @param array $settings
 *   (optional) An array of event settings to set on the handler.
 *
 * @return RulesEventHandlerInterface
 *   The event handler.
 */
function rules_get_event_handler($event_name, array $settings = NULL) {
  $event_name = rules_get_event_base_name($event_name);
  $event_info = rules_get_event_info($event_name);
  $class = !empty($event_info['class']) ? $event_info['class'] : 'RulesEventDefaultHandler';
  $handler = new $class($event_name, $event_info);
  return isset($settings) ? $handler->setSettings($settings) : $handler;
}

/**
 * Creates a new instance of a the given rules plugin.
 *
 * @return RulesPlugin
 */
function rules_plugin_factory($plugin_name, $arg1 = NULL, $arg2 = NULL) {
  $cache = rules_get_cache();
  if (isset($cache['plugin_info'][$plugin_name]['class'])) {
    return new $cache['plugin_info'][$plugin_name]['class']($arg1, $arg2);
  }
}

/**
 * Implementation of hook_rules_plugin_info().
 *
 * Note that the cache is rebuilt in the order of the plugins. Therefore the
 * condition and action plugins must be at the top, so that any components
 * re-building their cache can create configurations including properly setup-ed
 * actions and conditions.
 */
function rules_rules_plugin_info() {
  return array(
    'condition' => array(
      'class' => 'RulesCondition',
      'embeddable' => 'RulesConditionContainer',
      'extenders' => array (
        'RulesPluginImplInterface' => array(
          'class' => 'RulesAbstractPluginDefaults',
        ),
        'RulesPluginFeaturesIntegrationInterace' => array(
          'methods' => array(
            'features_export' => 'rules_features_abstract_default_features_export',
          ),
        ),
        'RulesPluginUIInterface' => array(
          'class' => 'RulesAbstractPluginUI',
        ),
      ),
    ),
    'action' => array(
      'class' => 'RulesAction',
      'embeddable' => 'RulesActionContainer',
      'extenders' => array (
        'RulesPluginImplInterface' => array(
          'class' => 'RulesAbstractPluginDefaults',
        ),
        'RulesPluginFeaturesIntegrationInterace' => array(
          'methods' => array(
            'features_export' => 'rules_features_abstract_default_features_export',
          ),
        ),
        'RulesPluginUIInterface' => array(
          'class' => 'RulesAbstractPluginUI',
        ),
      ),
    ),
    'or' => array(
      'label' => t('Condition set (OR)'),
      'class' => 'RulesOr',
      'embeddable' => 'RulesConditionContainer',
      'component' => TRUE,
      'extenders' => array(
        'RulesPluginUIInterface' => array(
          'class' => 'RulesConditionContainerUI',
        ),
      ),
    ),
    'and' => array(
      'label' => t('Condition set (AND)'),
      'class' => 'RulesAnd',
      'embeddable' => 'RulesConditionContainer',
      'component' => TRUE,
      'extenders' => array(
        'RulesPluginUIInterface' => array(
          'class' => 'RulesConditionContainerUI',
        ),
      ),
    ),
    'action set' => array(
      'label' => t('Action set'),
      'class' => 'RulesActionSet',
      'embeddable' => FALSE,
      'component' => TRUE,
      'extenders' => array(
        'RulesPluginUIInterface' => array(
          'class' => 'RulesActionContainerUI',
        ),
      ),
    ),
    'rule' => array(
      'label' => t('Rule'),
      'class' => 'Rule',
      'embeddable' => 'RulesRuleSet',
      'component' => TRUE,
      'extenders' => array(
        'RulesPluginUIInterface' => array(
          'class' => 'RulesRuleUI',
        ),
      ),
    ),
    'loop' => array(
      'class' => 'RulesLoop',
      'embeddable' => 'RulesActionContainer',
      'extenders' => array(
        'RulesPluginUIInterface' => array(
          'class' => 'RulesLoopUI',
        ),
      ),
    ),
    'reaction rule' => array(
      'class' => 'RulesReactionRule',
      'embeddable' => FALSE,
      'extenders' => array(
        'RulesPluginUIInterface' => array(
          'class' => 'RulesReactionRuleUI',
        ),
      ),
    ),
    'event set' => array(
      'class' => 'RulesEventSet',
      'embeddable' => FALSE,
    ),
    'rule set' => array(
      'label' => t('Rule set'),
      'class' => 'RulesRuleSet',
      'component' => TRUE,
      // Rule sets don't get embedded - we use a separate action to execute.
      'embeddable' => FALSE,
      'extenders' => array(
        'RulesPluginUIInterface' => array(
          'class' => 'RulesRuleSetUI',
        ),
      ),
    ),
  );
}

/**
 * Implementation of hook_entity_info().
 */
function rules_entity_info() {
  return array(
    'rules_config' => array(
      'label' => t('Rules configuration'),
      'controller class' => 'RulesEntityController',
      'base table' => 'rules_config',
      'fieldable' => TRUE,
      'entity keys' => array(
        'id' => 'id',
        'name' => 'name',
        'label' => 'label',
      ),
      'module' => 'rules',
      'static cache' => TRUE,
      'bundles' => array(),
      'configuration' => TRUE,
      'exportable' => TRUE,
      'export' => array(
        'default hook' => 'default_rules_configuration',
      ),
      'access callback' => 'rules_config_access',
      'features controller class' => 'RulesFeaturesController',
    ),
  );
}

/**
 * Implementation of hook_hook_info().
 */
function rules_hook_info() {
  foreach(array('plugin_info', 'rules_directory', 'data_info', 'condition_info', 'action_info', 'event_info', 'file_info', 'evaluator_info', 'data_processor_info') as $hook) {
    $hooks['rules_' . $hook] = array(
      'group' => 'rules',
    );
    $hooks['rules_' . $hook . '_alter'] = array(
      'group' => 'rules',
    );
  }
  $hooks['default_rules_configuration'] = array(
    'group' => 'rules_defaults',
  );
  $hooks['default_rules_configuration_alter'] = array(
    'group' => 'rules_defaults',
  );
  return $hooks;
}

/**
 * Load rule configurations from the database.
 *
 * This function should be used whenever you need to load more than one entity
 * from the database. The entities are loaded into memory and will not require
 * database access if loaded again during the same page request.
 *
 * @see hook_entity_info()
 * @see RulesEntityController
 *
 * @param $names
 *   An array of rules configuration names or FALSE to load all.
 * @param $conditions
 *   An array of conditions in the form 'field' => $value.
 *
 * @return
 *   An array of rule configurations indexed by their ids.
 */
function rules_config_load_multiple($names = array(), $conditions = array()) {
  return entity_load_multiple_by_name('rules_config', $names, $conditions);
}

/**
 * Loads a single rule configuration from the database.
 *
 * @see rules_config_load_multiple()
 *
 * @return RulesPlugin
 */
function rules_config_load($name) {
  return entity_load_single('rules_config', $name);
}

/**
 * Returns an array of configured components.
 *
 * For actually executing a component use rules_invoke_component(), as this
 * retrieves the component from cache instead.
 *
 * @param $label
 *   Whether to return only the label or the whole component object.
 * @param $type
 *   Optionally filter for 'action' or 'condition' components.
 * @param $conditions
 *   An array of additional conditions as required by rules_config_load().
 *
 * @return
 *   An array keyed by component name containing either the label or the config.
 */
function rules_get_components($label = FALSE, $type = NULL, $conditions = array()) {
  $cache = rules_get_cache();
  $plugins = array_keys(rules_filter_array($cache['plugin_info'], 'component', TRUE));
  $conditions = $conditions + array('plugin' => $plugins);
  $faces = array(
    'action' => 'RulesActionInterface',
    'condition' => 'RulesConditionInterface',
  );
  $items = array();
  foreach (rules_config_load_multiple(FALSE, $conditions) as $name => $config) {
    if (!isset($type) || $config instanceof $faces[$type]) {
      $items[$name] = $label ? $config->label() : $config;
    }
  }
  return $items;
}

/**
 * Delete rule configurations from database.
 *
 * @param $ids
 *   An array of entity IDs.
 */
function rules_config_delete(array $ids) {
  return entity_get_controller('rules_config')->delete($ids);
}

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

  $was_dirty = !empty($rules_config->dirty);
  try {
    // First set the rule to dirty, so any repetitive checks give green light
    // for this configuration.
    $rules_config->dirty = FALSE;
    $rules_config->integrityCheck();
    if ($was_dirty) {
      $variables = array('%label' => $rules_config->label(), '%name' => $rules_config->name, '@plugin' => $rules_config->plugin());
      watchdog('rules', 'The @plugin %label (%name) was marked dirty, but passes the integrity check now and is active again.', $variables, WATCHDOG_INFO);
    }
  }
  catch (RulesIntegrityException $e) {
    $rules_config->dirty = TRUE;
    if (!$was_dirty) {
      $variables = array('%label' => $rules_config->label(), '%name' => $rules_config->name, '!message' => $e->getMessage(), '@plugin' => $rules_config->plugin());
      watchdog('rules', 'The @plugin %label (%name) fails the integrity check and cannot be executed. Error: !message', $variables, WATCHDOG_ERROR);
    }
  }
  // Save the updated dirty flag to the database.
  if ($was_dirty != $rules_config->dirty) {
    db_update('rules_config')
      ->fields(array('dirty' => (int) $rules_config->dirty))
      ->condition('id', $rules_config->id)
      ->execute();
  }
}

/**
 * Invokes a hook and the associated rules event.
 *
 * Calling this function does the same as calling module_invoke_all() and
 * rules_invoke_event() separately, however merges both functions into one in
 * order to ease usage and to work efficiently.
 *
 * @param $hook
 *   The name of the hook / event to invoke.
 * @param ...
 *   Arguments to pass to the hook / event.
 *
 * @return
 *   An array of return values of the hook implementations. If modules return
 *   arrays from their implementations, those are merged into one array.
 */
function rules_invoke_all() {
  // Copied code from module_invoke_all().
  $args = func_get_args();
  $hook = $args[0];
  unset($args[0]);
  $return = array();
  foreach (module_implements($hook) as $module) {
    $function = $module . '_' . $hook;
    if (function_exists($function)) {
      $result = call_user_func_array($function, $args);
      if (isset($result) && is_array($result)) {
        $return = array_merge_recursive($return, $result);
      }
      elseif (isset($result)) {
        $return[] = $result;
      }
    }
  }
  // Invoke the event.
  rules_invoke_event_by_args($hook, $args);

  return $return;
}

/**
 * Invokes configured rules for the given event.
 *
 * @param $event_name
 *   The event's name.
 * @param ...
 *   Pass parameters for the variables provided by this event, as defined in
 *   hook_rules_event_info(). Example given:
 *   @code
 *     rules_invoke_event('node_view', $node, $view_mode);
 *   @endcode
 *
 * @see rules_invoke_event_by_args()
 */
function rules_invoke_event() {
  global $conf;

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

/**
 * Invokes configured rules for the given event.
 *
 * @param $event_name
 *   The event's name.
 * @param $args
 *   An array of parameters for the variables provided by the event, as defined
 *   in hook_rules_event_info(). Either pass an array keyed by the variable
 *   names or a numerically indexed array, in which case the ordering of the
 *   passed parameters has to match the order of the specified variables.
 *   Example given:
 *   @code
 *     rules_invoke_event_by_args('node_view', array('node' => $node, 'view_mode' => $view_mode));
 *   @endcode
 *
 * @see rules_invoke_event()
 */
function rules_invoke_event_by_args($event_name, $args = array()) {
  global $conf;

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

/**
 * Invokes a rule component, e.g. a rule set.
 *
 * @param $component_name
 *   The component's name.
 * @param $args
 *   Pass further parameters as required for the invoked component.
 *
 * @return
 *   An array of variables as provided by the component, or FALSE in case the
 *   component could not be executed.
 */
function rules_invoke_component() {
  $args = func_get_args();
  $name = array_shift($args);
  if ($component = rules_get_cache('comp_' . $name)) {
    return $component->executeByArgs($args);
  }
  return FALSE;
}

/**
 * Filters the given array of arrays by keeping only entries which have $key set
 * to the value of $value.
 *
 * @param $array
 *   The array of arrays to filter.
 * @param $key
 *   The key used for the comparison.
 * @param $value
 *   The value to compare the array's entry to.
 *
 * @return array
 *   The filtered array.
 */
function rules_filter_array($array, $key, $value) {
  $return = array();
  foreach ($array as $i => $entry) {
    $entry += array($key => NULL);
    if ($entry[$key] == $value) {
      $return[$i] = $entry;
    }
  }
  return $return;
}

/**
 * Merges the $update array into $array making sure no values of $array not
 * appearing in $update are lost.
 *
 * @return
 *   The updated array.
 */
function rules_update_array(array $array, array $update) {
  foreach ($update as $key => $data) {
    if (isset($array[$key]) && is_array($array[$key]) && is_array($data)) {
      $array[$key] = rules_update_array($array[$key], $data);
    }
    else {
      $array[$key] = $data;
    }
  }
  return $array;
}

/**
 * Extracts the property with the given name.
 *
 * @param $arrays
 *   An array of arrays from which a property is to be extracted.
 * @param $key
 *   The name of the property to extract.
 *
 * @return An array of extracted properties, keyed as in $arrays-
 */
function rules_extract_property($arrays, $key) {
  $data = array();
  foreach ($arrays as $name => $item) {
    $data[$name] = $item[$key];
  }
  return $data;
}

/**
 * Returns the first key of the array.
 */
function rules_array_key($array) {
  reset($array);
  return key($array);
}

/**
 * Clean replacements so they are URL friendly.
 *
 * Can be used as 'cleaning callback' for action or condition parameters.
 *
 * @param $replacements
 *   An array of token replacements that need to be "cleaned" for use in the URL.
 * @param $data
 *   An array of objects used to generate the replacements.
 * @param $options
 *   An array of options used to generate the replacements.
 *
 * @see rules_path_action_info()
 */
function rules_path_clean_replacement_values(&$replacements, $data = array(), $options = array()) {
  // Include path.eval.inc which contains path cleaning functions.
  module_load_include('inc', 'rules', 'modules/path.eval');
  foreach ($replacements as $token => $value) {
    $replacements[$token] = rules_clean_path($value);
  }
}

/**
 * Implements hook_theme().
 */
function rules_theme() {
  return array(
    'rules_elements' => array(
      'render element' => 'element',
      'file' => 'ui/ui.theme.inc',
    ),
    'rules_content_group' => array(
      'render element' => 'element',
      'file' => 'ui/ui.theme.inc',
    ),
    'rules_parameter_configuration' => array(
      'render element' => 'element',
      'file' => 'ui/ui.theme.inc',
    ),
    'rules_variable_view' => array(
      'render element' => 'element',
      'file' => 'ui/ui.theme.inc',
    ),
    'rules_data_selector_help' => array(
      'variables' => array('parameter' => NULL, 'variables' => NULL),
      'file' => 'ui/ui.theme.inc',
    ),
    'rules_ui_variable_form' => array(
      'render element' => 'element',
      'file' => 'ui/ui.theme.inc',
    ),
    'rules_log' => array(
      'render element' => 'element',
      'file' => 'ui/ui.theme.inc',
    ),
    'rules_autocomplete' => array(
      'render element' => 'element',
      'file' => 'ui/ui.theme.inc',
    ),
    'rules_debug_element' => array(
      'render element' => 'element',
      'file' => 'ui/ui.theme.inc',
    ),
    'rules_settings_help' => array(
      'variables' => array('text' => '', 'heading' => ''),
      'file' => 'ui/ui.theme.inc',
    ),
  );
}

/**
 * Implements hook_permission().
 */
function rules_permission() {
  $perms = array(
    'administer rules' => array(
      'title' => t('Administer rule configurations'),
      'description' => t('Administer rule configurations including events, conditions and actions for which the user has sufficient access permissions.'),
    ),
    'bypass rules access' => array(
      'title' => t('Bypass Rules access control'),
      'description' => t('Control all configurations regardless of permission restrictions of events, conditions or actions.'),
      'restrict access' => TRUE,
    ),
    'access rules debug' => array(
      'title' => t('Access the Rules debug log'),
    ),
  );

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

  return $perms;
}

/**
 * Helper function to get all the permissions for components that have access exposed.
 */
function rules_permissions_by_component(array $components = array()) {
  $perms = array();
  foreach ($components as $component) {
    $perms += array(
      "use Rules component $component->name" => array(
        'title' => t('Use Rules component %component', array('%component' => $component->label())),
        '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)))),
      ),
    );
  }
  return $perms;
}

/**
 * Menu callback for loading rules configuration elements.
 * @see RulesUIController::config_menu()
 */
function rules_element_load($element_id, $config_name) {
  $config = rules_config_load($config_name);
  return $config->elementMap()->lookup($element_id);
}

/**
 * Menu callback for getting the title as configured.
 * @see RulesUIController::config_menu()
 */
function rules_get_title($text, $element) {
  if ($element instanceof RulesPlugin) {
    $cache = rules_get_cache();
    $plugin = $element->plugin();
    $plugin = isset($cache['plugin_info'][$plugin]['label']) ? $cache['plugin_info'][$plugin]['label'] : $plugin;
    $plugin = drupal_strtolower(drupal_substr($plugin, 0, 1)) . drupal_substr($plugin, 1);
    return t($text, array('!label' => $element->label(), '!plugin' => $plugin));
  }
  // As fallback treat $element as simple string.
  return t($text, array('!plugin' => $element));
}

/**
 * Menu callback for getting the title for the add element page.
 *
 * Uses a work-a-round for accessing the plugin name.
 * @see RulesUIController::config_menu()
 */
function rules_menu_add_element_title($array) {
  $plugin_name = arg($array[0]);
  $cache = rules_get_cache();
  if (isset($cache['plugin_info'][$plugin_name]['class'])) {
    $info = $cache['plugin_info'][$plugin_name] + array('label' => $plugin_name);
    $label = drupal_strtolower(drupal_substr($info['label'], 0, 1)) . drupal_substr($info['label'], 1);
    return t('Add a new !plugin', array('!plugin' => $label));
  }
}

/**
 * Returns the current region for the debug log.
 */
function rules_debug_log_region() {
  // If there is no setting for the current theme use the default theme setting.
  global $theme_key;
  $theme_default = variable_get('theme_default', 'bartik');
  return variable_get('rules_debug_region_' . $theme_key, variable_get('rules_debug_region_' . $theme_default, 'help'));
}

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

  if (isset($_SESSION['rules_debug'])) {
    $region = rules_debug_log_region();
    foreach ($_SESSION['rules_debug'] as $log) {
      $page[$region]['rules_debug'][] = array(
        '#markup' => $log,
      );
      $page[$region]['rules_debug']['#theme_wrappers'] = array('rules_log');
    }
    unset($_SESSION['rules_debug']);
  }

  if (rules_show_debug_output()) {
    $region = rules_debug_log_region();
    $page[$region]['rules_debug']['#pre_render'] = array('rules_debug_log_pre_render');
  }
}

/**
 * Pre-render callback for the debug log, which renders and then clears it.
 */
function rules_debug_log_pre_render($elements) {
  $logger = RulesLog::logger();
  if ($log = $logger->render()) {
    $logger = RulesLog::logger();
    $logger->clear();
    $elements[] = array('#markup' => $log);
    $elements['#theme_wrappers'] = array('rules_log');
    // Log the rules log to the system log if enabled.
    if (variable_get('rules_debug_log', FALSE)) {
      watchdog('rules', 'Rules debug information: !log', array('!log' => $log), WATCHDOG_NOTICE);
    }
  }
  return $elements;
}

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

    if ($force || !isset($_GET['destination'])) {
      $url = drupal_parse_url($url);
      $path = $url['path'];
      $options['query'] = $url['query'];
      $options['fragment'] = $url['fragment'];
      $http_response_code = 302;
    }
  }
}

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

/**
 * Implements hook_exit().
 */
function rules_exit() {
  // Bail out if this is cached request and modules are not loaded.
  if (!module_exists('rules') || !module_exists('user')) {
    return;
  }
  if (rules_show_debug_output()) {
    if ($log = RulesLog::logger()->render()) {
      // Keep the log in the session so we can show it on the next page.
      $_SESSION['rules_debug'][] = $log;
    }
  }
  // Log the rules log to the system log if enabled.
  if (variable_get('rules_debug_log', FALSE) && $log = RulesLog::logger()->render()) {
    watchdog('rules', 'Rules debug information: !log', array('!log' => $log), WATCHDOG_NOTICE);
  }
}

/**
 * Implements hook_element_info().
 */
function rules_element_info() {
  // A duration form element for rules. Needs ui.forms.inc included.
  $types['rules_duration'] = array(
    '#input' => TRUE,
    '#tree' => TRUE,
    '#default_value' => 0,
    '#value_callback' => 'rules_ui_element_duration_value',
    '#process' => array('rules_ui_element_duration_process', 'ajax_process_form'),
    '#after_build' => array('rules_ui_element_duration_after_build'),
    '#pre_render' => array('form_pre_render_conditional_form_element'),
  );
  $types['rules_data_selection'] = array(
    '#input' => TRUE,
    '#pre_render' => array('form_pre_render_conditional_form_element'),
    '#process' => array('rules_data_selection_process', 'ajax_process_form'),
    '#theme' => 'rules_autocomplete',
  );
  return $types;
}

/**
 * Implements hook_modules_enabled().
 */
function rules_modules_enabled($modules) {
  // Re-enable Rules configurations that are dirty, because they require one of
  // the enabled the modules.
  $query = db_select('rules_dependencies', 'rd');
  $query->join('rules_config', 'rc', 'rd.id = rc.id');
  $query->fields('rd', array('id'))
        ->condition('rd.module', $modules, 'IN')
        ->condition('rc.dirty', 1);
  $ids = $query->execute()->fetchCol();

  // If there are some configurations that might work again, re-check all dirty
  // configurations as others might work again too, e.g. consider a rule that is
  // dirty because it requires a dirty component.
  if ($ids) {
    $rules_configs = rules_config_load_multiple(FALSE, array('dirty' => 1));
    foreach ($rules_configs as $rules_config) {
      try {
        $rules_config->integrityCheck();
        // If no exceptions were thrown we can set the configuration back to OK.
        db_update('rules_config')
          ->fields(array('dirty' => 0))
          ->condition('id', $rules_config->id)
          ->execute();
        if ($rules_config->active) {
          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())));
        }
      }
      catch (RulesIntegrityException $e) {
        // The rule is still dirty, so do nothing.
      }
    }
  }
  rules_clear_cache();
}

/**
 * Implements hook_modules_disabled().
 */
function rules_modules_disabled($modules) {
  // Disable Rules configurations that depend on one of the disabled modules.
  $query = db_select('rules_dependencies', 'rd');
  $query->join('rules_config', 'rc', 'rd.id = rc.id');
  $query->fields('rd', array('id'))
        ->distinct()
        ->condition('rd.module', $modules, 'IN')
        ->condition('rc.dirty', 0);
  $ids = $query->execute()->fetchCol();

  if (!empty($ids)) {
    db_update('rules_config')
      ->fields(array('dirty' => 1))
      ->condition('id', $ids, 'IN')
      ->execute();
    // Tell the user about enabled rules that have been marked as dirty.
    $count = db_select('rules_config', 'r')
      ->fields('r')
      ->condition('id', $ids, 'IN')
      ->condition('active', 1)
      ->execute()->rowCount();
    if ($count > 0) {
      $message = format_plural($count,
        '1 Rules configuration requires some of the disabled modules to function and cannot be executed any more.',
        '@count Rules configuration require some of the disabled modules to function and cannot be executed any more.'
      );
      drupal_set_message($message, 'warning');
    }
  }
  rules_clear_cache();
}

/**
 * Access callback for dealing with Rules configurations.
 *
 * @see entity_access()
 */
function rules_config_access($op, $rules_config = NULL, $account = NULL) {
  if (user_access('bypass rules access', $account)) {
    return TRUE;
  }
  // Allow modules to grant / deny access.
  $access = module_invoke_all('rules_config_access', $op, $rules_config, $account);

  // Only grant access if at least one module granted access and no one denied
  // access.
  if (in_array(FALSE, $access, TRUE)) {
    return FALSE;
  }
  elseif (in_array(TRUE, $access, TRUE)) {
    return TRUE;
  }
  return FALSE;
}

/**
 * Implements hook_rules_config_access().
 */
function rules_rules_config_access($op, $rules_config = NULL, $account = NULL) {
  // Instead of returning FALSE return nothing, so others still can grant
  // access.
  if (!isset($rules_config) || (isset($account) && $account->uid != $GLOBALS['user']->uid)) {
    return;
  }
  if (user_access('administer rules', $account) && ($op == 'view' || $rules_config->access())) {
    return TRUE;
  }
}

/**
 * Implements hook_menu().
 */
function rules_menu() {
  $items['admin/config/workflow/rules/upgrade'] = array(
    'title' => 'Upgrade',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('rules_upgrade_form'),
    'access arguments' => array('administer rules'),
    'file' => 'includes/rules.upgrade.inc',
    'file path' => drupal_get_path('module', 'rules'),
    'type' => MENU_CALLBACK,
  );
  $items['admin/config/workflow/rules/upgrade/clear'] = array(
    'title' => 'Clear',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('rules_upgrade_confirm_clear_form'),
    'access arguments' => array('administer rules'),
    'file' => 'includes/rules.upgrade.inc',
    'file path' => drupal_get_path('module', 'rules'),
    'type' => MENU_CALLBACK,
  );
  $items['admin/config/workflow/rules/autocomplete_tags'] = array(
    'title' => 'Rules tags autocomplete',
    'page callback' => 'rules_autocomplete_tags',
    'page arguments' => array(5),
    'access arguments' => array('administer rules'),
    'file' => 'ui/ui.forms.inc',
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Helper function to keep track of external documentation pages for Rules.
 *
 * @param $topic
 *   The topic key for used for identifying help pages.
 *
 * @return
 *   Either a URL for the given page, or the full list of external help pages.
 */
function rules_external_help($topic = NULL) {
  $help = array(
    'rules' =>                'http://drupal.org/node/298480',
    'terminology' =>          'http://drupal.org/node/1299990',
    'condition-components' => 'http://drupal.org/node/1300034',
    'data-selection' =>       'http://drupal.org/node/1300042',
    'chained-tokens' =>       'http://drupal.org/node/1300042',
    'loops' =>                'http://drupal.org/node/1300058',
    'components' =>           'http://drupal.org/node/1300024',
    'component-types' =>      'http://drupal.org/node/1300024',
    'variables' =>            'http://drupal.org/node/1300024',
    'scheduler' =>            'http://drupal.org/node/1300068',
    'coding' =>               'http://drupal.org/node/878720',
  );

  if (isset($topic)) {
    return isset($help[$topic]) ? $help[$topic] : FALSE;
  }
  return $help;
}

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

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

    $output['topic-list'] = array(
      '#markup' => theme('item_list', array('items' => $link_list)),
    );
    return render($output);
  }
}

/**
 * Implements hook_token_info().
 */
function rules_token_info() {
  $cache = rules_get_cache();
  $data_info = $cache['data_info'];

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

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

    $token_info['types'][$token_type] = array(
      'name' => $data_info[$type]['label'],
      'description' => t('Tokens related to %label Rules variables.', array('%label' => $data_info[$type]['label'])),
      'needs-data' => $token_type,
    );
    $token_info['tokens'][$token_type]['value'] = array(
      'name' => t("Value"),
      'description' => t('The value of the variable.'),
    );
  }
  return $token_info;
}

/**
 * Implements hook_tokens().
 */
function rules_tokens($type, $tokens, $data, $options = array()) {
  // Handle replacements of primitive variable types.
  if (substr($type, 0, 6) == 'rules_' && !empty($data[$type])) {
    // Leverage entity tokens token processor by passing on as struct.
    $info['property info']['value'] = array(
      'type' => substr($type, 6),
      'label' => '',
    );
    // Entity tokens uses metadata wrappers as values for 'struct' types.
    $wrapper = entity_metadata_wrapper('struct', array('value' => $data[$type]), $info);
    return entity_token_tokens('struct', $tokens, array('struct' => $wrapper), $options);
  }
}

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

/**
 * Callback that returns a metadata wrapper with all properties.
 */
function rules_entity_metadata_wrapper_all_properties_callback(EntityMetadataWrapper $wrapper, $property_info) {
  $info = $wrapper->info();
  $properties = entity_get_all_property_info($info['type']);
  $property_info['properties'] += $properties;
  return $property_info;
}