rules.core.inc 91.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 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813
<?php

/**
 * @file
 * Rules base classes and interfaces needed for any rule evaluation.
 */

// This is not necessary as the classes are autoloaded via the registry. However
// it saves some possible update headaches until the registry is rebuilt.
// @todo
//   Remove for a future release.
require_once dirname(__FILE__) . '/faces.inc';

/**
 * Make sure loaded rule configs are instantiated right.
 */
class RulesEntityController extends EntityAPIControllerExportable {

  /**
   * Overridden.
   *
   * @see EntityAPIController::create()
   */
  public function create(array $values = array()) {
    // Default to rules as owning module.
    $values += array('owner' => 'rules');
    return parent::create($values);
  }

  /**
   * Overridden.
   * @see DrupalDefaultEntityController::attachLoad()
   */
  protected function attachLoad(&$queried_entities, $revision_id = FALSE) {
    // Retrieve stdClass records and turn them in rules objects stored in 'data'
    $ids = array_keys($queried_entities);
    $result = db_select('rules_tags')
      ->fields('rules_tags', array('id', 'tag'))
      ->condition('id', $ids, 'IN')
      ->execute();
    foreach ($result as $row) {
      $tags[$row->id][] = $row->tag;
    }
    $result = db_select('rules_dependencies')
      ->fields('rules_dependencies', array('id', 'module'))
      ->condition('id', $ids, 'IN')
      ->execute();
    foreach ($result as $row) {
      $modules[$row->id][] = $row->module;
    }

    $entities = array();
    foreach ($queried_entities as $record) {
      $entity = $record->data;
      // Set the values of the other columns.
      foreach ($this->entityInfo['schema_fields_sql']['base table'] as $field) {
        $entity->$field = $record->$field;
      }
      unset($entity->data, $entity->plugin);
      // Add any tags or dependencies.
      $entity->dependencies = isset($modules[$entity->id]) ? $modules[$entity->id] : array();
      $entity->tags = isset($tags[$entity->id]) ? $tags[$entity->id] : array();
      $entities[$entity->id] = $entity;
    }
    $queried_entities = $entities;
    parent::attachLoad($queried_entities, $revision_id);
  }

  /**
   * Override to support having events and tags as conditions.
   * @see EntityAPIController::applyConditions($entities, $conditions)
   * @see rules_query_rules_config_load_multiple_alter()
   */
  protected function applyConditions($entities, $conditions = array()) {
    if (isset($conditions['event']) || isset($conditions['plugin'])) {
      foreach ($entities as $key => $entity) {
        if (isset($conditions['event']) && (!($entity instanceof RulesTriggerableInterface) || !in_array($conditions['event'], $entity->events()))) {
          unset($entities[$key]);
        }
        if (isset($conditions['plugin']) && !is_array($conditions['plugin'])) {
          $conditions['plugin'] = array($conditions['plugin']);
        }
        if (isset($conditions['plugin']) && !in_array($entity->plugin(), $conditions['plugin'])) {
          unset($entities[$key]);
        }
      }
      unset($conditions['event'], $conditions['plugin']);
    }
    if (!empty($conditions['tags'])) {
      foreach ($entities as $key => $entity) {
        foreach ($conditions['tags'] as $tag) {
          if (in_array($tag, $entity->tags)) {
            continue 2;
          }
        }
        unset($entities[$key]);
      }
      unset($conditions['tags']);
    }
    return parent::applyConditions($entities, $conditions);
  }

  /**
   * Overridden to work with Rules' custom export format.
   *
   * @param $export
   *   A serialized string in JSON format as produced by the
   *   RulesPlugin::export() method, or the PHP export as usual PHP array.
   */
  public function import($export, &$error_msg = '') {
    $export = is_array($export) ? $export : drupal_json_decode($export);
    if (!is_array($export)) {
      $error_msg = t('Unable to parse the pasted export.');
      return FALSE;
    }
    // The key ist the configuration name and the value the actual export.
    list($name, $export) = each($export);
    if (!isset($export['PLUGIN'])) {
      $error_msg = t('Export misses plugin information.');
      return FALSE;
    }
    // Create an empty configuration, re-set basic keys and import.
    $config = rules_plugin_factory($export['PLUGIN']);
    $config->name = $name;
    foreach (array('label', 'active', 'weight', 'tags', 'access_exposed', 'owner') as $key) {
      if (isset($export[strtoupper($key)])) {
        $config->$key = $export[strtoupper($key)];
      }
    }
    if (!empty($export['REQUIRES'])) {
      foreach ($export['REQUIRES'] as $module) {
        if (!module_exists($module)) {
          $error_msg = t('Missing the required module %module.', array('%module' => $module));
          return FALSE;
        }
      }
      $config->dependencies = $export['REQUIRES'];
    }
    $config->import($export);
    return $config;
  }

  public function save($rules_config, DatabaseTransaction $transaction = NULL) {
    $transaction = isset($transaction) ? $transaction : db_transaction();

    // Load the stored entity, if any.
    if (!isset($rules_config->original) && $rules_config->{$this->idKey}) {
      $rules_config->original = entity_load_unchanged($this->entityType, $rules_config->{$this->idKey});
    }
    $original = isset($rules_config->original) ? $rules_config->original : NULL;

    $return = parent::save($rules_config, $transaction);
    $this->storeTags($rules_config);
    if ($rules_config instanceof RulesTriggerableInterface) {
      $this->storeEvents($rules_config);
    }
    $this->storeDependencies($rules_config);

    // See if there are any events that have been removed.
    if ($original && $rules_config->plugin == 'reaction rule') {
      foreach (array_diff($original->events(), $rules_config->events()) as $event_name) {
        // Check if the event handler implements the event dispatcher interface.
        $handler = rules_get_event_handler($event_name, $rules_config->getEventSettings($event_name));
        if (!$handler instanceof RulesEventDispatcherInterface) {
          continue;
        }

        // Only stop an event dispatcher if there are no rules for it left.
        if (!rules_config_load_multiple(FALSE, array('event' => $event_name, 'plugin' => 'reaction rule', 'active' => TRUE)) && $handler->isWatching()) {
          $handler->stopWatching();
        }
      }
    }

    return $return;
  }

  /**
   * Save tagging information to the rules_tags table.
   */
  protected function storeTags($rules_config) {
    db_delete('rules_tags')
      ->condition('id', $rules_config->id)
      ->execute();
    if (!empty($rules_config->tags)) {
      foreach ($rules_config->tags as $tag) {
        db_insert('rules_tags')
          ->fields(array('id', 'tag'), array($rules_config->id, $tag))
          ->execute();
      }
    }
  }

  /**
   * Save event information to the rules_trigger table.
   */
  protected function storeEvents(RulesTriggerableInterface $rules_config) {
    db_delete('rules_trigger')
      ->condition('id', $rules_config->id)
      ->execute();
    foreach ($rules_config->events() as $event) {
      db_insert('rules_trigger')
        ->fields(array(
        'id' => $rules_config->id,
        'event' => $event,
      ))
      ->execute();
    }
  }

  protected function storeDependencies($rules_config) {
    db_delete('rules_dependencies')
      ->condition('id', $rules_config->id)
      ->execute();
    if (!empty($rules_config->dependencies)) {
      foreach ($rules_config->dependencies as $dependency) {
        db_insert('rules_dependencies')
          ->fields(array(
          'id' => $rules_config->id,
          'module' => $dependency,
        ))
        ->execute();
      }
    }
  }

  /**
   * Overridden to support tags and events in $conditions.
   * @see EntityAPIControllerExportable::buildQuery()
   */
  protected function buildQuery($ids, $conditions = array(), $revision_id = FALSE) {
    $query = parent::buildQuery($ids, $conditions, $revision_id);
    $query_conditions =& $query->conditions();
    foreach ($query_conditions as &$condition) {
      // One entry in $query_conditions is a string with key '#conjunction'.
      // @see QueryConditionInterface::conditions().
      if (is_array($condition)) {
        // Support using 'tags' => array('tag1', 'tag2') as condition.
        if ($condition['field'] == 'base.tags') {
          $query->join('rules_tags', 'rt', 'base.id = rt.id');
          $condition['field'] = 'rt.tag';
        }
        // Support using 'event' => $name as condition.
        if ($condition['field'] == 'base.event') {
          $query->join('rules_trigger', 'tr', "base.id = tr.id");
          $condition['field'] = 'tr.event';
          // Use like operator to support % wildcards also.
          $condition['operator'] = 'LIKE';
        }
      }
    }
    return $query;
  }

  /**
   * Overridden to also delete tags and events.
   * @see EntityAPIControllerExportable::delete()
   */
  public function delete($ids, DatabaseTransaction $transaction = NULL) {
    $transaction = isset($transaction) ? $transaction : db_transaction();
    // Use entity-load as ids may be the names as well as the ids.
    $configs = $ids ? entity_load('rules_config', $ids) : array();
    if ($configs) {
      foreach ($configs as $config) {
        db_delete('rules_trigger')
          ->condition('id', $config->id)
          ->execute();
        db_delete('rules_tags')
          ->condition('id', $config->id)
          ->execute();
        db_delete('rules_dependencies')
          ->condition('id', $config->id)
          ->execute();
      }
    }
    $return = parent::delete($ids, $transaction);

    // Stop event dispatchers when deleting the last rule of an event set.
    $processed = array();
    foreach ($configs as $config) {
      if ($config->getPluginName() != 'reaction rule') {
        continue;
      }

      foreach ($config->events() as $event_name) {
        // Only process each event once.
        if (!empty($processed[$event_name])) {
          continue;
        }
        $processed[$event_name] = TRUE;

        // Check if the event handler implements the event dispatcher interface.
        $handler = rules_get_event_handler($event_name, $config->getEventSettings($event_name));
        if (!$handler instanceof RulesEventDispatcherInterface) {
          continue;
        }

        // Only stop an event dispatcher if there are no rules for it left.
        if ($handler->isWatching() && !rules_config_load_multiple(FALSE, array('event' => $event_name, 'plugin' => 'reaction rule', 'active' => TRUE))) {
          $handler->stopWatching();
        }
      }
    }

    return $return;
  }
}

/**
 * The RulesExtendable uses the rules cache to setup the defined extenders
 * and overrides automatically.
 * As soon faces is used the faces information is autoloaded using setUp().
 */
abstract class RulesExtendable extends FacesExtendable {

  /**
   * The name of the info definitions associated with info about this class.
   * This would be defined abstract, if possible. Common rules hooks with class
   * info are e.g. plugin_info and data_info.
   */
  protected $hook;

  /**
   * The name of the item this class represents in the info hook.
   */
  protected $itemName;

  protected $cache, $itemInfo = array();


  public function __construct() {
    $this->setUp();
  }

  protected function setUp() {
    // Keep a reference on the cache, so elements created during cache
    // rebuilding end up with a complete cache in the end too.
    $this->cache = &rules_get_cache();
    if (isset($this->cache[$this->hook][$this->itemName])) {
      $this->itemInfo = &$this->cache[$this->hook][$this->itemName];
    }
    // Set up the Faces Extenders
    if (!empty($this->itemInfo['faces_cache'])) {
      list($this->facesMethods, $this->facesIncludes, $this->faces) = $this->itemInfo['faces_cache'];
    }
  }

  /**
   * Force the object to be setUp, this executes setUp() if not done yet.
   */
  public function forceSetUp() {
    if (!isset($this->cache) || (!empty($this->itemInfo['faces_cache']) && !$this->faces)) {
      $this->setUp();
    }
  }

  /**
   * Magic method: Invoke the dynamically implemented methods.
   */
  public function __call($name, $arguments = array()) {
    $this->forceSetUp();
    return parent::__call($name, $arguments);
  }

  public function facesAs($interface = NULL) {
    $this->forceSetUp();
    return parent::facesAs($interface);
  }

  /**
   * Allows items to add something to the rules cache.
   */
  public function rebuildCache(&$itemInfo, &$cache) {
    // Speed up setting up items by caching the faces methods.
    if (!empty($itemInfo['extenders'])) {
      // Apply extenders and overrides.
      $itemInfo += array('overrides' => array());
      foreach ($itemInfo['extenders'] as $face => $data) {
        $data += array('file' => array());
        if (isset($data['class'])) {
          $this->extendByClass($face, $data['class'], $data['file']);
        }
        elseif (isset($data['methods'])) {
          $this->extend($face, $data['methods'], $data['file']);
        }
      }
      foreach ($itemInfo['overrides'] as $data) {
        $data += array('file' => array());
        $this->override($data['methods'], $data['file']);
      }
      $itemInfo['faces_cache'] = array($this->facesMethods, $this->facesIncludes, $this->faces);
      // We don't need that any more.
      unset($itemInfo['extenders'], $itemInfo['overrides']);
    }
  }

  /**
   * Returns whether the a RuleExtendable supports the given interface.
   *
   * @param $itemInfo
   *   The info about the item as specified in the hook.
   * @param $interface
   *   The interface to check for.
   * @return
   *   Whether it supports the given interface.
   */
  public static function itemFacesAs(&$itemInfo, $interface) {
    return in_array($interface, class_implements($itemInfo['class'])) || isset($itemInfo['faces_cache'][2][$interface]);
  }
}

/**
 * Base class for rules plugins.
 *
 * We cannot inherit from EntityDB at the same time, so we implement our own
 * entity related methods. Any CRUD related actions performed on contained
 * plugins are applied and the root element representing the configuration is
 * saved.
 */
abstract class RulesPlugin extends RulesExtendable {

  /**
   * If this is a configuration saved to the db, the id of it.
   */
  public $id = NULL;
  public $weight = 0;
  public $name = NULL;

  /**
   * An array of settings for this element.
   */
  public $settings = array();

  /**
   * Info about this element. Usage depends on the plugin.
   */
  protected $info = array();

  /**
   * The parent element, if any.
   * @var RulesContainerPlugin
   */
  protected $parent = NULL;

  protected $cache = NULL, $hook = 'plugin_info';

  /**
   * Identifies an element inside a configuration.
   */
  protected $elementId = NULL;

  /**
   * Static cache for availableVariables().
   */
  protected $availableVariables;


  /**
   * Sets a new parent element.
   */
  public function setParent(RulesContainerPlugin $parent) {
    if ($this->parent == $parent) {
      return;
    }
    if (isset($this->parent) && ($key = array_search($this, $this->parent->children)) !== FALSE) {
      // Remove element from any previous parent.
      unset($this->parent->children[$key]);
      $this->parent->resetInternalCache();
    }
    // Make sure the interface matches the type of the container.
    if (($parent instanceof RulesActionContainer && $this instanceof RulesActionInterface) ||
       ($parent instanceof RulesConditionContainer && $this instanceof RulesConditionInterface)) {

      $this->parent = $parent;
      $parent->children[] = $this;
      $this->parent->resetInternalCache();
    }
    else {
      throw new RulesEvaluationException('The given container is incompatible with this element.', array(), $this, RulesLog::ERROR);
    }
  }

  /**
   * Gets the root element of the configuration.
   */
  public function root() {
    $element = $this;
    while (!$element->isRoot()) {
      $element = $element->parent;
    }
    return $element;
  }

  /**
   * Returns whether the element is the root of the configuration.
   */
  public function isRoot() {
    return empty($this->parent) || isset($this->name);
  }

  /**
   * Returns the element's parent.
   */
  public function parentElement() {
    return $this->parent;
  }

  /**
   * Returns the element id, which identifies the element inside the config.
   */
  public function elementId() {
    if (!isset($this->elementId)) {
      $this->elementMap()->index();
    }
    return $this->elementId;
  }

  /**
   * Gets the element map helper object, which helps mapping elements to ids.
   *
   * @return RulesElementMap
   */
  public function elementMap() {
    $config = $this->root();
    if (empty($config->map)) {
      $config->map = new RulesElementMap($config);
    }
    return $config->map;
  }

  /**
   * Iterate over all elements nested below the current element.
   *
   * This helper can be used to recursively iterate over all elements of a
   * configuration. To iterate over the children only, just regulary iterate
   * over the object.
   *
   * @param $mode
   *   (optional) The iteration mode used. See
   *   RecursiveIteratorIterator::construct(). Defaults to SELF_FIRST.
   *
   * @return RecursiveIteratorIterator
   */
  public function elements($mode = RecursiveIteratorIterator::SELF_FIRST) {
    return new RecursiveIteratorIterator($this, $mode);
  }

  /**
   * Do a deep clone.
   */
  public function __clone() {
    // Make sure the element map is cleared.
    // @see self::elementMap()
    unset($this->map);
  }

  /**
   * Returns the depth of this element in the configuration.
   */
  public function depth() {
    $element = $this;
    $i = 0;
    while (!empty($element->parent)) {
      $element = $element->parent;
      $i++;
    }
    return $i;
  }

  /**
   * Execute the configuration.
   *
   * @param ...
   *   Arguments to pass to the configuration.
   */
  public function execute() {
    return $this->executeByArgs(func_get_args());
  }

  /**
   * Execute the configuration by passing arguments in a single array.
   */
  abstract public function executeByArgs($args = array());

  /**
   * Evaluate the element on a given rules evaluation state.
   */
  abstract function evaluate(RulesState $state);

  protected static function compare(RulesPlugin $a, RulesPlugin $b) {
    if ($a->weight == $b->weight) {
      return 0;
    }
    return ($a->weight < $b->weight) ? -1 : 1;
  }

  /**
   * Returns info about parameters needed by the plugin.
   *
   * Note that not necessarily all parameters are needed when executing the
   * plugin, as values for the parameter might have been already configured via
   * the element settings.
   *
   * @see self::parameterInfo()
   */
  public function pluginParameterInfo() {
    return isset($this->info['parameter']) ? $this->info['parameter'] : array();
  }

  /**
   * Returns info about parameters needed for executing the configured plugin.
   *
   * @param $optional
   *   Whether optional parameters should be included.
   *
   * @see self::pluginParameterInfo()
   */
  public function parameterInfo($optional = FALSE) {
    // We have to filter out parameters that are already configured.
    foreach ($this->pluginParameterInfo() as $name => $info) {
      if (!isset($this->settings[$name . ':select']) && !isset($this->settings[$name]) && ($optional || (empty($info['optional']) && $info['type'] != 'hidden'))) {
        $vars[$name] = $info;
      }
    }
    return isset($vars) ? $vars : array();
  }

  /**
   * Returns the about variables the plugin provides for later evaluated elements.
   *
   * Note that this method returns info about the provided variables as defined
   * by the plugin. Thus this resembles the original info, which may be
   * adapted via configuration.
   *
   * @see self::providesVariables()
   */
  public function pluginProvidesVariables() {
    return isset($this->info['provides']) ? $this->info['provides'] : array();
  }

  /**
   * Returns info about all variables provided for later evaluated elements.
   *
   * @see self::pluginProvidesVariables()
   */
  public function providesVariables() {
    foreach ($this->pluginProvidesVariables() as $name => $info) {
      $info['source name'] = $name;
      $info['label'] = isset($this->settings[$name . ':label']) ? $this->settings[$name . ':label'] : $info['label'];
      if (isset($this->settings[$name . ':var'])) {
        $name = $this->settings[$name . ':var'];
      }
      $provides[$name] = $info;
    }
    return isset($provides) ? $provides : array();
  }

  /**
   * Returns the info of the plugin.
   */
  public function info() {
    return $this->info;
  }

  /**
   * When converted to a string, just use the export format.
   */
  public function __toString() {
    return $this->isRoot() ? $this->export() : entity_var_json_export($this->export());
  }

  /**
   * Gets variables to return once the configuration has been executed.
   */
  protected function returnVariables(RulesState $state, $result = NULL) {
    $var_info = $this->providesVariables();
    foreach ($var_info as $name => $info) {
      try {
        $vars[$name] = $this->getArgument($name, $info, $state);
      }
      catch (RulesEvaluationException $e) {
        // Ignore not existing variables.
        $vars[$name] = NULL;
      }
      $var_info[$name] += array('allow null' => TRUE);
    }
    return isset($vars) ? array_values(rules_unwrap_data($vars, $var_info)) : array();
  }

  /**
   * Sets up the execution state for the given arguments.
   */
  public function setUpState(array $args) {
    $state = new RulesState();
    $vars = $this->setUpVariables();
    // Fix numerically indexed args to start with 0.
    if (!isset($args[rules_array_key($vars)])) {
      $args = array_values($args);
    }
    $offset = 0;
    foreach (array_keys($vars) as $i => $name) {
      $info = $vars[$name];
      if (!empty($info['handler']) || (isset($info['parameter']) && $info['parameter'] === FALSE)) {
        $state->addVariable($name, NULL, $info);
        // Count the variables that are not passed as parameters.
        $offset++;
      }
      // Support numerically indexed arrays as well as named parameter style.
      // The index is reduced to exclude non-parameter variables.
      elseif (isset($args[$i - $offset])) {
        $state->addVariable($name, $args[$i - $offset], $info);
      }
      elseif (isset($args[$name])) {
        $state->addVariable($name, $args[$name], $info);
      }
      elseif (empty($info['optional']) && $info['type'] != 'hidden') {
        throw new RulesEvaluationException('Argument %name is missing.', array('%name' => $name), $this, RulesLog::ERROR);
      }
    }
    return $state;
  }

  /**
   * Returns info about all variables that have to be setup in the state.
   */
  protected function setUpVariables() {
    return $this->parameterInfo(TRUE);
  }

  /**
   * Returns info about variables available to be used as arguments for this element.
   *
   * As this is called very often, e.g. during integrity checks, we statically
   * cache the results.
   *
   * @see RulesPlugin::resetInternalCache()
   */
  public function availableVariables() {
    if (!isset($this->availableVariables)) {
      $this->availableVariables = !$this->isRoot() ? $this->parent->stateVariables($this) : RulesState::defaultVariables();
    }
    return $this->availableVariables;
  }

  /**
   * Returns asserted additions to the available variable info. Any returned
   * info is merged into the variable info, in case the execution flow passes
   * the element.
   * E.g. this is used to assert the content type of a node if the condition
   * is met, such that the per node type properties are available.
   */
  protected function variableInfoAssertions() {
    return array();
  }

  /**
   * Get the name of this plugin instance. The returned name should identify
   * the code which drives this plugin.
   */
  public function getPluginName() {
    return $this->itemName;
  }

  /**
   * Calculates an array of required modules.
   *
   * You can use $this->dependencies to access dependencies for saved
   * configurations.
   */
  public function dependencies() {
    $this->processSettings();
    $modules = isset($this->itemInfo['module']) && $this->itemInfo['module'] != 'rules' ? array($this->itemInfo['module'] => 1) : array();
    foreach ($this->pluginParameterInfo() as $name => $info) {
      if (isset($this->settings[$name . ':process']) && $this->settings[$name . ':process'] instanceof RulesDataProcessor) {
        $modules += array_flip($this->settings[$name . ':process']->dependencies());
      }
    }
    return array_keys($modules);
  }

  /**
   * Whether the currently logged in user has access to all configured elements.
   *
   * Note that this only checks whether the current user has permission to all
   * configured elements, but not whether a user has access to configure Rule
   * configurations in general. Use rules_config_access() for that.
   *
   * Use this to determine access permissions for configuring or triggering the
   * execution of certain configurations independent of the Rules UI.
   *
   * @see rules_config_access()
   */
  public function access() {
    $this->processSettings();
    foreach ($this->pluginParameterInfo() as $name => $info) {
      if (isset($this->settings[$name . ':select']) && $wrapper = $this->applyDataSelector($this->settings[$name . ':select'])) {
        if ($wrapper->access('view') === FALSE) {
          return FALSE;
        }
      }
      // Incorporate access checks for data processors and input evaluators.
      if (isset($this->settings[$name . ':process']) && $this->settings[$name . ':process'] instanceof RulesDataProcessor && !$this->settings[$name . ':process']->editAccess()) {
        return FALSE;
      }
    }
    return TRUE;
  }

  /**
   * Processes the settings e.g. to prepare input evaluators.
   *
   * Usually settings get processed automatically, however if $this->settings
   * has been altered manually after element construction, it needs to be
   * invoked explicitly with $force set to TRUE.
   *
   */
  public function processSettings($force = FALSE) {
    // Process if not done yet.
    if ($force || !empty($this->settings['#_needs_processing'])) {
      $var_info = $this->availableVariables();
      foreach ($this->pluginParameterInfo() as $name => $info) {
        // Prepare input evaluators.
        if (isset($this->settings[$name])) {
          $this->settings[$name . ':process'] = $this->settings[$name];
          RulesDataInputEvaluator::prepareSetting($this->settings[$name . ':process'], $info, $var_info);
        }
        // Prepare data processors.
        elseif (isset($this->settings[$name . ':select']) && !empty($this->settings[$name . ':process'])) {
          RulesDataProcessor::prepareSetting($this->settings[$name . ':process'], $info, $var_info);
        }
        // Clean up.
        if (empty($this->settings[$name . ':process'])) {
          unset($this->settings[$name . ':process']);
        }
      }
      unset($this->settings['#_needs_processing']);
    }
  }

  /**
   * Makes sure the plugin is configured right, e.g. all needed variables
   * are available in the element's scope and dependent modules are enabled.
   *
   * @return RulesPlugin
   *   Returns $this to support chained usage.
   *
   * @throws RulesIntegrityException
   *   In case of a failed integraty check, a RulesIntegrityException exception
   *   is thrown.
   */
  public function integrityCheck() {
    // First process the settings if not done yet.
    $this->processSettings();
    // Check dependencies using the pre-calculated dependencies stored in
    // $this->dependencies. Fail back to calculation them on the fly, e.g.
    // during creation.
    $dependencies = empty($this->dependencies) ? $this->dependencies() : $this->dependencies;
    foreach ($dependencies as $module) {
      if (!module_exists($module)) {
        throw new RulesDependencyException(t('Missing required module %name.', array('%name' => $module)));
      }
    }
    // Check the parameter settings.
    $this->checkParameterSettings();
    // Check variable names for provided variables to be valid.
    foreach ($this->pluginProvidesVariables() as $name => $info) {
      if (isset($this->settings[$name . ':var'])) {
        $this->checkVarName($this->settings[$name . ':var']);
      }
    }
    return $this;
  }

  protected function checkVarName($name) {
    if (!preg_match('/^[0-9a-zA-Z_]*$/', $name)) {
      throw new RulesIntegrityException(t('%plugin: The variable name %name contains not allowed characters.', array('%plugin' => $this->getPluginName(), '%name' => $name)), $this);
    }
  }

  /**
   * Checks whether parameters are correctly configured.
   */
  protected function checkParameterSettings() {
    foreach ($this->pluginParameterInfo() as $name => $info) {
      if (isset($info['restriction']) && $info['restriction'] == 'selector' && isset($this->settings[$name])) {
        throw new RulesIntegrityException(t("The parameter %name may only be configured using a selector.", array('%name' => $name)), array($this, 'parameter', $name));
      }
      elseif (isset($info['restriction']) && $info['restriction'] == 'input' && isset($this->settings[$name . ':select'])) {
        throw new RulesIntegrityException(t("The parameter %name may not be configured using a selector.", array('%name' => $name)), array($this, 'parameter', $name));
      }
      elseif (!empty($this->settings[$name . ':select']) && !$this->applyDataSelector($this->settings[$name . ':select'])) {
        throw new RulesIntegrityException(t("Data selector %selector for parameter %name is invalid.", array('%selector' => $this->settings[$name . ':select'], '%name' => $name)), array($this, 'parameter', $name));
      }
      elseif ($arg_info = $this->getArgumentInfo($name)) {
        // If we have enough metadata, check whether the types match.
        if (!RulesData::typesMatch($arg_info, $info)) {
          throw new RulesIntegrityException(t("The data type of the configured argument does not match the parameter's %name requirement.", array('%name' => $name)), array($this, 'parameter', $name));
        }
      }
      elseif (!$this->isRoot() && !isset($this->settings[$name]) && empty($info['optional']) && $info['type'] != 'hidden') {
        throw new RulesIntegrityException(t('Missing configuration for parameter %name.', array('%name' => $name)), array($this, 'parameter', $name));
      }
      //TODO: Make sure used values are allowed. (key/value pairs + allowed values)
    }
  }

  /**
   * Returns the argument as configured in the element settings for the
   * parameter $name described with $info.
   *
   * @param $name
   *   The name of the parameter for which to get the argument.
   * @param $info
   *   Info about the parameter.
   * @param RulesState $state
   *   The current evaluation state.
   * @param $langcode
   *   (optional) The language code used to get the argument value if the
   *   argument value should be translated. By default (NULL) the current
   *   interface language will be used.
   *
   * @return
   *   The argument, possibly wrapped.
   *
   * @throws RulesEvaluationException
   *   In case the argument cannot be retrieved an exception is thrown.
   */
  protected function getArgument($name, $info, RulesState $state, $langcode = NULL) {
    // Only apply the langcode if the parameter has been marked translatable.
    if (empty($info['translatable'])) {
      $langcode = LANGUAGE_NONE;
    }
    elseif (!isset($langcode)) {
      $langcode = $GLOBALS['language']->language;
    }

    if (!empty($this->settings[$name . ':select'])) {
      $arg = $state->applyDataSelector($this->settings[$name . ':select'], $langcode);
    }
    elseif (isset($this->settings[$name])) {
      $arg = rules_wrap_data($this->settings[$name], $info);
      // We don't sanitize directly specified values.
      $skip_sanitize = TRUE;
    }
    elseif ($state->varinfo($name)) {
      $arg = $state->get($name);
    }
    elseif (empty($info['optional']) && $info['type'] != 'hidden') {
      throw new RulesEvaluationException('Required parameter %name is missing.', array('%name' => $name), $this, RulesLog::ERROR);
    }
    else {
      $arg = isset($info['default value']) ? $info['default value'] : NULL;
      $skip_sanitize = TRUE;
      $info['allow null'] = TRUE;
    }
    // Make sure the given value is set if required (default).
    if (!isset($arg) && empty($info['allow null'])) {
      throw new RulesEvaluationException('The provided argument for parameter %name is empty.', array('%name' => $name), $this);
    }

    // Support passing already sanitized values.
    if ($info['type'] == 'text' && !isset($skip_sanitize) && !empty($info['sanitize']) && !($arg instanceof EntityMetadataWrapper)) {
      $arg = check_plain((string) $arg);
    }

    // Apply any configured data processors.
    if (!empty($this->settings[$name . ':process'])) {
      // For processing, make sure the data is unwrapped now.
      $return = rules_unwrap_data(array($arg), array($info));
      // @todo for Drupal 8: Refactor to add the name and language code as
      // separate parameter to process().
      $info['#name'] = $name;
      $info['#langcode'] = $langcode;
      return isset($return[0]) ? $this->settings[$name . ':process']->process($return[0], $info, $state, $this) : NULL;
    }
    return $arg;
  }

  /**
   * Gets the right arguments for executing the element.
   *
   * @throws RulesEvaluationException
   *   If case an argument cannot be retrieved an exception is thrown.
   */
  protected function getExecutionArguments(RulesState $state) {
    $parameters = $this->pluginParameterInfo();
    // If there is language parameter, get its value first so it can be used
    // for getting other translatable values.
    $langcode = NULL;
    if (isset($parameters['language'])) {
      $lang_arg = $this->getArgument('language', $parameters['language'], $state);
      $langcode = $lang_arg instanceof EntityMetadataWrapper ? $lang_arg->value() : $lang_arg;
    }
    // Now get all arguments.
    foreach ($parameters as $name => $info) {
      $args[$name] = $name == 'language' ? $lang_arg : $this->getArgument($name, $info, $state, $langcode);
    }
    // Append the settings and the execution state. Faces will append $this.
    $args['settings'] = $this->settings;
    $args['state'] = $state;
    // Make the wrapped variables for the arguments available in the state.
    $state->currentArguments = $args;
    return rules_unwrap_data($args, $parameters);
  }

  /**
   * Apply the given data selector by using the info about available variables.
   * Thus it doesn't require an actual evaluation state.
   *
   * @param $selector
   *   The selector string, e.g. "node:author:mail".
   *
   * @return EntityMetadataWrapper
   *   An empty wrapper for the given selector or FALSE if the selector couldn't
   *   be applied.
   */
  public function applyDataSelector($selector) {
    $parts = explode(':', str_replace('-', '_', $selector), 2);
    if (($vars = $this->availableVariables()) && isset($vars[$parts[0]]['type'])) {
      $wrapper = rules_wrap_data(NULL, $vars[$parts[0]], TRUE);
      if (count($parts) > 1 && $wrapper instanceof EntityMetadataWrapper) {
        try {
          foreach (explode(':', $parts[1]) as $name) {
            if ($wrapper instanceof EntityListWrapper || $wrapper instanceof EntityStructureWrapper) {
              $wrapper = $wrapper->get($name);
            }
            else {
              return FALSE;
            }
          }
        }
        // In case of an exception or we were unable to get a wrapper, return FALSE.
        catch (EntityMetadataWrapperException $e) {
          return FALSE;
        }
      }
    }
    return isset($wrapper) ? $wrapper : FALSE;
  }

  /**
   * Returns info about the configured argument.
   *
   * @return
   *   The determined info. If it's not known NULL is returned.
   */
  public function getArgumentInfo($name) {
    $vars = $this->availableVariables();
    if (!empty($this->settings[$name . ':select']) && !empty($vars[$this->settings[$name . ':select']])) {
      return $vars[$this->settings[$name . ':select']];
    }
    elseif (!empty($this->settings[$name . ':select'])) {
      if ($wrapper = $this->applyDataSelector($this->settings[$name . ':select'])) {
        return $wrapper->info();
      }
      return;
    }
    elseif (isset($this->settings[$name . ':type'])) {
      return array('type' => $this->settings[$name . ':type']);
    }
    elseif (!isset($this->settings[$name]) && isset($vars[$name])) {
      return $vars[$name];
    }
  }

  /**
   * Saves the configuration to the database, regardless whether this is invoked
   * on the rules configuration or a contained rule element.
   */
  public function save($name = NULL, $module = 'rules') {
    if (isset($this->parent)) {
      $this->parent->sortChildren();
      return $this->parent->save($name, $module);
    }
    else {
      // Update the dirty flag before saving.
      // However, this operation depends on a fully built Rules-cache, so skip
      // it when entities in code are imported to the database.
      // @see _rules_rebuild_cache()
      if (empty($this->is_rebuild)) {
        rules_config_update_dirty_flag($this, FALSE);
        // In case the config is not dirty, pre-calculate the dependencies for
        // later checking. Note that this also triggers processing settings if
        // necessary.
        // @see rules_modules_enabled()
        if (empty($this->dirty)) {
          $this->dependencies = $this->dependencies();
        }
      }

      $this->plugin = $this->itemName;
      $this->name = isset($name) ? $name : $this->name;
      // Module stores the module via which the rule is configured and is used
      // for generating machine names with the right prefix. However, for
      // default configurations 'module' points to the module providing the
      // default configuration, so the module via which the rules is configured
      // is stored in the "owner" property.
      // @todo: For Drupal 8 use "owner" for generating machine names also and
      // module only for the modules providing default configurations.
      $this->module = !isset($this->module) || $module != 'rules' ? $module : $this->module;
      if (!isset($this->owner)) {
        $this->owner = 'rules';
      }
      $this->ensureNameExists();
      $this->data = $this;
      $return = entity_get_controller('rules_config')->save($this);
      unset($this->data);

      // Care about clearing necessary caches.
      if (!empty($this->is_rebuild)) {
        rules_clear_cache();
      }
      else {
        $plugin_info = $this->pluginInfo();
        if (!empty($plugin_info['component'])) {
          // When component variables changes rebuild the complete cache so the
          // changes to the provided action/condition take affect.
          if (empty($this->original) || $this->componentVariables() != $this->original->componentVariables()) {
            rules_clear_cache();
          }
          // Clear components cached for evaluation.
          cache_clear_all('comp_', 'cache_rules', TRUE);
        }
        elseif ($this->plugin == 'reaction rule') {
          // Clear event sets cached for evaluation.
          cache_clear_all('event_', 'cache_rules', TRUE);
          variable_del('rules_event_whitelist');
        }
        drupal_static_reset('rules_get_cache');
        drupal_static_reset('rules_config_update_dirty_flag');
      }

      return $return;
    }
  }

  /**
   * Ensure the configuration has a name. If not, generate one.
   */
  protected function ensureNameExists() {
    if (!isset($this->module)) {
      $this->module = 'rules';
    }
    if (!isset($this->name)) {
      // Find a unique name for this configuration.
      $this->name = $this->module . '_';
      for ($i = 0; $i < 8; $i++) {
        // Alphanumeric name generation.
        $rnd = mt_rand(97, 122);
        $this->name .= chr($rnd);
      }
    }
  }

  public function __sleep() {
    // Keep the id always as we need it for the recursion prevention.
    $array = drupal_map_assoc(array('parent', 'id', 'elementId', 'weight', 'settings'));
    // Keep properties related to configurations if they are there.
    $info = entity_get_info('rules_config');
    $fields = array_merge($info['schema_fields_sql']['base table'], array('recursion', 'tags'));
    foreach ($fields as $key) {
      if (isset($this->$key)) {
        $array[$key] = $key;
      }
    }
    return $array;
  }

  /**
   * Optimizes a rule configuration in order to speed up evaluation.
   *
   * Additional optimization methods may be inserted by an extender
   * implementing the RulesOptimizationInterface. By default, there is no
   * optimization extender.
   *
   * An optimization method may rearrange the internal structure of a
   * configuration in order to speed up the evaluation. As the configuration may
   * change optimized configurations should not be saved permanently, except
   * when saving it temporary, for later execution only.
   *
   * @see RulesOptimizationInterface
   */
  public function optimize() {
    // Make sure settings are processed before configs are cached.
    $this->processSettings();
    if ($this->facesAs('RulesOptimizationInterface')) {
      $this->__call('optimize');
    }
  }

  /**
   * If invoked on a rules configuration it is deleted from database. If
   * invoked on a contained rule element, it's removed from the configuration.
   */
  public function delete() {
    if (isset($this->parent)) {
      foreach ($this->parent->children as $key => $child) {
        if ($child === $this) {
          unset($this->parent->children[$key]);
          break;
        }
      }
    }
    elseif (isset($this->id)) {
      entity_get_controller('rules_config')->delete(array($this->name));
      rules_clear_cache();
    }
  }

  public function internalIdentifier() {
    return isset($this->id) ? $this->id : NULL;
  }

  /**
   * Returns the config name.
   */
  public function identifier() {
    return isset($this->name) ? $this->name : NULL;
  }

  public function entityInfo() {
    return entity_get_info('rules_config');
  }

  public function entityType() {
    return 'rules_config';
  }

  /**
   * Checks if the configuration has a certain exportable status.
   *
   * @param $status
   *   A status constant, i.e. one of ENTITY_CUSTOM, ENTITY_IN_CODE,
   *   ENTITY_OVERRIDDEN or ENTITY_FIXED.
   *
   * @return
   *   TRUE if the configuration has the status, else FALSE.
   *
   * @see entity_has_status()
   */
  public function hasStatus($status) {
    return $this->isRoot() && isset($this->status) && ($this->status & $status) == $status;
  }

  /**
   * Remove circular object references so the PHP garbage collector does its
   * work.
   */
  public function destroy() {
    parent::destroy();
    $this->parent = NULL;
  }

  /**
   * Seamlessy invokes the method implemented via faces without having to think
   * about references.
   */
  public function form(&$form, &$form_state, array $options = array()) {
    $this->__call('form', array(&$form, &$form_state, $options));
  }

  public function form_validate($form, &$form_state) {
    $this->__call('form_validate', array($form, &$form_state));
  }

  public function form_submit($form, &$form_state) {
    $this->__call('form_submit', array($form, &$form_state));
  }

  /**
   * Returns the label of the element.
   */
  public function label() {
    if (!empty($this->label) && $this->label != t('unlabeled')) {
      return $this->label;
    }
    $info = $this->info();
    return isset($info['label']) ? $info['label'] : (!empty($this->name) ? $this->name : t('unlabeled'));
  }

  /**
   * Returns the name of the element's plugin.
   */
  public function plugin() {
    return $this->itemName;
  }

  /**
   * Returns info about the element's plugin.
   */
  public function pluginInfo() {
    $this->forceSetUp();
    return $this->itemInfo;
  }

  /**
   * Applies the given export.
   */
  public function import(array $export) {
    $this->importSettings($export[strtoupper($this->plugin())]);
  }

  protected function importSettings($export) {
    // Import parameter settings.
    $export += array('USING' => array(), 'PROVIDE' => array());
    foreach ($export['USING'] as $name => $param_export) {
      $this->importParameterSetting($name, $param_export);
    }
    foreach ($export['PROVIDE'] as $name => $var_export) {
      // The key of $var_export is the variable name, the value the label.
      $this->settings[$name . ':var'] = rules_array_key($var_export);
      $this->settings[$name . ':label'] = reset($var_export);
    }
  }

  protected function importParameterSetting($name, $export) {
    if (is_array($export) && isset($export['select'])) {
      $this->settings[$name . ':select'] = $export['select'];
      if (count($export) > 1) {
        // Add in processor settings.
        unset($export['select']);
        $this->settings[$name . ':process'] = $export;
      }
    }
    // Convert back the [selector] strings being an array with one entry.
    elseif (is_array($export) && count($export) == 1 && isset($export[0])) {
      $this->settings[$name . ':select'] = $export[0];
    }
    elseif (is_array($export) && isset($export['value'])) {
      $this->settings[$name] = $export['value'];
    }
    else {
      $this->settings[$name] = $export;
    }
  }

  /**
   * Exports a rule configuration.
   *
   * @param $prefix
   *   An optional prefix for each line.
   * @param $php
   *   Optional. Set to TRUE to format the export using PHP arrays. By default
   *   JSON is used.
   * @return
   *   The exported confiugration.
   *
   * @see rules_import()
   */
  public function export($prefix = '', $php = FALSE) {
    $export = $this->exportToArray();
    return $this->isRoot() ? $this->returnExport($export, $prefix, $php) : $export;
  }

  protected function exportToArray() {
    $export[strtoupper($this->plugin())] = $this->exportSettings();
    return $export;
  }

  protected function exportSettings() {
    $export = array();
    if (!$this->isRoot()) {
      foreach ($this->pluginParameterInfo() as $name => $info) {
        if (($return = $this->exportParameterSetting($name, $info)) !== NULL) {
          $export['USING'][$name] = $return;
        }
      }
      foreach ($this->providesVariables() as $name => $info) {
        if (!empty($info['source name'])) {
          $export['PROVIDE'][$info['source name']][$name] = $info['label'];
        }
      }
    }
    return $export;
  }

  protected function exportParameterSetting($name, $info) {
    if (isset($this->settings[$name]) && (empty($info['optional']) || !isset($info['default value']) || $this->settings[$name] != $info['default value'])) {
      // In case of an array-value wrap the value into another array, such that
      // the value cannot be confused with an exported data selector.
      return is_array($this->settings[$name]) ? array('value' => $this->settings[$name]) : $this->settings[$name];
    }
    elseif (isset($this->settings[$name . ':select'])) {
      if (isset($this->settings[$name . ':process']) && $processor = $this->settings[$name . ':process']) {
        $export['select'] = $this->settings[$name . ':select'];
        $export += $processor instanceof RulesDataProcessor ? $processor->getChainSettings() : $processor;
        return $export;
      }
      // If there is no processor use a simple array to abbreviate this usual
      // case. In JSON this turns to a nice [selector] string.
      return array($this->settings[$name . ':select']);
    }
  }

  /**
   * Finalizies the configuration export by adding general attributes regarding
   * the configuration and returns it in the right format.
   */
  protected function returnExport($export, $prefix = '', $php = FALSE) {
    $this->ensureNameExists();
    if (!empty($this->label) && $this->label != t('unlabeled')) {
      $export_cfg[$this->name]['LABEL'] = $this->label;
    }
    $export_cfg[$this->name]['PLUGIN'] = $this->plugin();
    if (!empty($this->weight)) {
      $export_cfg[$this->name]['WEIGHT'] = $this->weight;
    }
    if (isset($this->active) && !$this->active) {
      $export_cfg[$this->name]['ACTIVE'] = FALSE;
    }
    if (!empty($this->owner)) {
      $export_cfg[$this->name]['OWNER'] = $this->owner;
    }
    if (!empty($this->tags)) {
      $export_cfg[$this->name]['TAGS'] = $this->tags;
    }
    if ($modules = $this->dependencies()) {
      $export_cfg[$this->name]['REQUIRES'] = $modules;
    }
    if (!empty($this->access_exposed)) {
      $export_cfg[$this->name]['ACCESS_EXPOSED'] = $this->access_exposed;
    };
    $export_cfg[$this->name] += $export;
    return $php ? entity_var_export($export_cfg, $prefix) : entity_var_json_export($export_cfg, $prefix);
  }

  /**
   * Resets any internal static caches.
   *
   * This function does not reset regular caches as retrieved via
   * rules_get_cache(). Usually, it's invoked automatically when a Rules
   * configuration is modified.
   *
   * Static caches are reset for the element and any elements down the tree. To
   * clear static caches of the whole configuration, invoke the function at the
   * root.
   *
   * @see RulesPlugin::availableVariables()
   */
  public function resetInternalCache() {
    $this->availableVariables = NULL;
  }
}

/**
 * Defines a common base class for so called "Abstract Plugins" like actions.
 * Thus modules have to provide the concrete plugin implementation.
 */
abstract class RulesAbstractPlugin extends RulesPlugin {

  protected $elementName;
  protected $info = array('parameter' => array(), 'provides' => array());
  protected $infoLoaded = FALSE;

  /**
   * @param $name
   *   The plugin implementation's name.
   * @param $info
   *   Further information provided about the plugin. Optional.
   * @throws RulesException
   *   If validation of the passed settings fails RulesExceptions are thrown.
   */
  function __construct($name = NULL, $settings = array()) {
    $this->elementName = $name;
    $this->settings = (array) $settings + array('#_needs_processing' => TRUE);
    $this->setUp();
  }

  protected function setUp() {
    parent::setUp();
    if (isset($this->cache[$this->itemName . '_info'][$this->elementName])) {
      $this->info = $this->cache[$this->itemName . '_info'][$this->elementName];
      // Remember that the info has been correctly setup.
      // @see self::forceSetup().
      $this->infoLoaded = TRUE;

      // Register the defined class, if any.
      if (isset($this->info['class'])) {
        $this->faces['RulesPluginImplInterface'] = 'RulesPluginImplInterface';
        $face_methods = get_class_methods('RulesPluginImplInterface');
        $class_info = array(1 => $this->info['class']);
        foreach ($face_methods as $method) {
          $this->facesMethods[$method] = $class_info;
        }
      }
      // Add in per-plugin implementation callbacks if any.
      if (!empty($this->info['faces_cache'])) {
        foreach ($this->info['faces_cache'] as $face => $data) {
          list($methods, $file_names) = $data;
          foreach ($methods as $method => $callback) {
            $this->facesMethods[$method] = $callback;
          }
          foreach ((array) $file_names as $method => $name) {
            $this->facesIncludes[$method] = array('module' => $this->info['module'], 'name' => $name);
          }
        }
        // Invoke the info_alter callback, but only if it has been implemented.
        if ($this->facesMethods['info_alter'] != $this->itemInfo['faces_cache'][0]['info_alter']) {
          $this->__call('info_alter', array(&$this->info));
        }
      }
    }
    elseif (!empty($this->itemInfo['faces_cache']) && function_exists($this->elementName)) {
      // We don't have any info, so just add the name as execution callback.
      $this->override(array('execute' => $this->elementName));
    }
  }

  public function forceSetUp() {
    if (!isset($this->cache) || (!empty($this->itemInfo['faces_cache']) && !$this->faces)) {
      $this->setUp();
    }
    // In case we have element specific information, which is not loaded yet,
    // do so now. This might happen if the element has been initially loaded
    // with an incomplete cache, i.e. during cache rebuilding.
    elseif (!$this->infoLoaded && isset($this->cache[$this->itemName . '_info'][$this->elementName])) {
      $this->setUp();
    }
  }

  /**
   * Returns the label of the element.
   */
  public function label() {
    $info = $this->info();
    return isset($info['label']) ? $info['label'] : t('@plugin "@name"', array('@name' => $this->elementName, '@plugin' => $this->plugin()));
  }

  public function access() {
    $info = $this->info();
    $this->loadBasicInclude();
    if (!empty($info['access callback']) && !call_user_func($info['access callback'], $this->itemName, $this->getElementName())) {
      return FALSE;
    }
    return parent::access() && $this->__call('access');
  }

  public function integrityCheck() {
    // Do the usual integrity check first so the implementation's validation
    // handler can rely on that already.
    parent::integrityCheck();
    // Make sure the element is known.
    $this->forceSetUp();
    if (!isset($this->cache[$this->itemName . '_info'][$this->elementName])) {
      throw new RulesIntegrityException(t('Unknown @plugin %name.', array('@plugin' => $this->plugin(), '%name' => $this->elementName)));
    }
    $this->validate();
    return $this;
  }

  public function processSettings($force = FALSE) {
    // Process if not done yet.
    if ($force || !empty($this->settings['#_needs_processing'])) {
      $this->resetInternalCache();
      // In case the element implements the info alteration callback, (re-)run
      // the alteration so that any settings depending info alterations are
      // applied.
      if ($this->facesMethods && $this->facesMethods['info_alter'] != $this->itemInfo['faces_cache'][0]['info_alter']) {
        $this->__call('info_alter', array(&$this->info));
      }
      // First let the plugin implementation do processing, so data types of the
      // parameters are fixed when we process the settings.
      $this->process();
      parent::processSettings($force);
    }
  }

  public function pluginParameterInfo() {
    // Ensure the info alter callback has been executed.
    $this->forceSetup();
    return parent::pluginParameterInfo();
  }

  public function pluginProvidesVariables() {
    // Ensure the info alter callback has been executed.
    $this->forceSetup();
    return parent::pluginProvidesVariables();
  }

  public function info() {
    // Ensure the info alter callback has been executed.
    $this->forceSetup();
    return $this->info;
  }

  protected function variableInfoAssertions() {
    // Get the implementation's assertions and map them to the variable names.
    if ($assertions = $this->__call('assertions')) {
      foreach ($assertions as $param_name => $data) {
        $name = isset($this->settings[$param_name . ':select']) ? $this->settings[$param_name . ':select'] : $param_name;
        $return[$name] = $data;
      }
      return $return;
    }
  }

  public function import(array $export) {
    // The key is the element name and the value the actual export.
    $this->elementName = rules_array_key($export);
    $export = reset($export);

    // After setting the element name, setup the element again so the right
    // element info is loaded.
    $this->setUp();

    if (!isset($export['USING']) && !isset($export['PROVIDES']) && !empty($export)) {
      // The export has been abbreviated to skip "USING".
      $export = array('USING' => $export);
    }
    $this->importSettings($export);
  }

  protected function exportToArray() {
    $export = $this->exportSettings();
    if (!$this->providesVariables()) {
      // Abbreviate the export making "USING" implicit.
      $export = isset($export['USING']) ? $export['USING'] : array();
    }
    return array($this->elementName => $export);
  }

  public function dependencies() {
    $modules = array_flip(parent::dependencies());
    $modules += array_flip((array) $this->__call('dependencies'));
    return array_keys($modules + (!empty($this->info['module']) ? array($this->info['module'] => 1) : array()));
  }

  public function executeByArgs($args = array()) {
    $replacements = array('%label' => $this->label(), '@plugin' => $this->itemName);
    rules_log('Executing @plugin %label.', $replacements, RulesLog::INFO, $this, TRUE);
    $this->processSettings();
    // If there is no element info, just pass through the passed arguments.
    // That way we support executing actions without any info at all.
    if ($this->info()) {
      $state = $this->setUpState($args);
      module_invoke_all('rules_config_execute', $this);

      $result = $this->evaluate($state);
      $return = $this->returnVariables($state, $result);
    }
    else {
      rules_log('Unable to execute @plugin %label.', $replacements, RulesLog::ERROR, $this);
    }
    $state->cleanUp();
    rules_log('Finished executing of @plugin %label.', $replacements, RulesLog::INFO, $this, FALSE);
    return $return;
  }

  /**
   * Execute the configured execution callback and log that.
   */
  abstract protected function executeCallback(array $args, RulesState $state = NULL);


  public function evaluate(RulesState $state) {
    $this->processSettings();
    try {
      // Get vars as needed for execute and call it.
      return $this->executeCallback($this->getExecutionArguments($state), $state);
    }
    catch (RulesEvaluationException $e) {
      rules_log($e->msg, $e->args, $e->severity);
      rules_log('Unable to evaluate %name.', array('%name' => $this->getPluginName()), RulesLog::WARN, $this);
    }
    // Catch wrapper exceptions that might occur due to failures loading an
    // entity or similar.
    catch (EntityMetadataWrapperException $e) {
      rules_log('Unable to get a data value. Error: !error', array('!error' => $e->getMessage()), RulesLog::WARN);
      rules_log('Unable to evaluate %name.', array('%name' => $this->getPluginName()), RulesLog::WARN, $this);
    }
  }

  public function __sleep() {
    return parent::__sleep() + array('elementName' => 'elementName');
  }

  public function getPluginName() {
    return $this->itemName ." ". $this->elementName;
  }

  /**
   * Gets the name of the configured action or condition.
   */
  public function getElementName() {
    return $this->elementName;
  }

  /**
   * Add in the data provided by the info hooks to the cache.
   */
  public function rebuildCache(&$itemInfo, &$cache) {
    parent::rebuildCache($itemInfo, $cache);

    // Include all declared files so we can find all implementations.
    self::includeFiles();

    // Get the plugin's own info data.
    $cache[$this->itemName .'_info'] = rules_fetch_data($this->itemName .'_info');
    foreach ($cache[$this->itemName .'_info'] as $name => &$info) {
      $info += array(
        'parameter' => isset($info['arguments']) ? $info['arguments'] : array(),
        'provides' => isset($info['new variables']) ? $info['new variables'] : array(),
        'base' => $name,
        'callbacks' => array(),
      );
      unset($info['arguments'], $info['new variables']);

      if (function_exists($info['base'])) {
        $info['callbacks'] += array('execute' => $info['base']);
      }

      // We do not need to build a faces cache for RulesPluginHandlerInterface,
      // which gets added in automatically as its a parent of
      // RulesPluginImplInterface.
      unset($this->faces['RulesPluginHandlerInterface']);

      // Build up the per plugin implementation faces cache.
      foreach ($this->faces as $interface) {
        $methods = $file_names = array();
        $includes = self::getIncludeFiles($info['module']);

        foreach (get_class_methods($interface) as $method) {
          if (isset($info['callbacks'][$method]) && ($function = $info['callbacks'][$method])) {
            $methods[$method][0] = $function;
            $file_names[$method] = $this->getFileName($function, $includes);
          }
          // Note that this skips RulesPluginImplInterface, which is not
          // implemented by plugin handlers.
          elseif (isset($info['class']) && is_subclass_of($info['class'], $interface)) {
            $methods[$method][1] = $info['class'];
          }
          elseif (function_exists($function = $info['base'] . '_' . $method)) {
            $methods[$method][0] = $function;
            $file_names[$method] = $this->getFileName($function, $includes);
          }
        }
        // Cache only the plugin implementation specific callbacks.
        $info['faces_cache'][$interface] = array($methods, array_filter($file_names));
      }
      // Filter out interfaces with no overriden methods.
      $info['faces_cache'] = rules_filter_array($info['faces_cache'], 0, TRUE);
      // We don't need that any more.
      unset($info['callbacks'], $info['base']);
    }
  }

  /**
   * Makes sure the providing modules' .rules.inc file is included as diverse
   * callbacks may reside in that file.
   */
  protected function loadBasicInclude() {
    static $included = array();

    if (isset($this->info['module']) && !isset($included[$this->info['module']])) {
      $module = $this->info['module'];
      module_load_include('inc', $module, $module . '.rules');
      $included[$module] = TRUE;
    }
  }

  /**
   * Make sure all supported destinations are included.
   */
  public static function includeFiles() {
    static $included;

    if (!isset($included)) {
      foreach (module_implements('rules_file_info') as $module) {
        // rules.inc are already included thanks to the rules_hook_info() group.
        foreach (self::getIncludeFiles($module, FALSE) as $name) {
          module_load_include('inc', $module, $name);
        }
      }
      $dirs = array();
      foreach (module_implements('rules_directory') as $module) {
        // Include all files once, so the discovery can find them.
        $result = module_invoke($module, 'rules_directory');
        if (!is_array($result)) {
          $result = array($module => $result);
        }
        $dirs += $result;
      }
      foreach ($dirs as $module => $directory) {
        foreach (glob(drupal_get_path('module', $module) . "/$directory/*.{inc,php}", GLOB_BRACE) as $filename) {
          include_once $filename;
        }
      }
      $included = TRUE;
    }
  }

  /**
   * Returns all include files for a module. If $all is set to FALSE the
   * $module.rules.inc file isn't added.
   */
  protected static function getIncludeFiles($module, $all = TRUE) {
    $files = (array)module_invoke($module, 'rules_file_info');
    // Automatically add "$module.rules_forms.inc" and "$module.rules.inc".
    $files[] = $module . '.rules_forms';
    if ($all) {
      $files[] = $module . '.rules';
    }
    return $files;
  }

  protected function getFileName($function, $includes) {
    $reflector = new ReflectionFunction($function);
    // On windows the path contains backslashes instead of slashes, fix that.
    $file = str_replace('\\', '/', $reflector->getFileName());
    foreach ($includes as $include) {
      $pos = strpos($file, $include . '.inc');
      // Test whether the file ends with the given filename.inc.
      if ($pos !== FALSE && strlen($file) - $pos == strlen($include) + 4) {
        return $include;
      }
    }
  }
}

/**
 * Interface for objects that can be used as action.
 */
interface RulesActionInterface {

  /**
   * @return As specified.
   *
   * @throws RulesEvaluationException
   *   Throws an exception if not all necessary arguments have been provided.
   */
  public function execute();
}

/**
 * Interface for objects that can be used as condition.
 */
interface RulesConditionInterface {

  /**
   * @return Boolean.
   *
   * @throws RulesEvaluationException
   *   Throws an exception if not all necessary arguments have been provided.
   */
  public function execute();

  /**
   * Negate the result.
   */
  public function negate($negate = TRUE);

  /**
   * Returns whether the element is configured to negate the result.
   */
  public function isNegated();
}

interface RulesTriggerableInterface {

  /**
   * Returns the array of (configured) event names associated with this object.
   */
  public function events();

  /**
   * Removes an event from the rule configuration.
   *
   * @param $event
   *   The name of the (configured) event to remove.
   * @return RulesTriggerableInterface
   *   The object instance itself, to allow chaining.
   */
  public function removeEvent($event_name);

  /**
   * Adds the specified event.
   *
   * @param string $event_name
   *   The base name of the event to add.
   * @param array $settings
   *   (optional) The event settings. If there are no event settings, pass an
   *   empty array (default).
   *
   * @return RulesTriggerableInterface
   */
  public function event($event_name, array $settings = array());

  /**
   * Gets the event settings associated with the given (configured) event.
   *
   * @param $event_name
   *   The (configured) event's name.
   *
   * @return array|null
   *   The array of event settings, or NULL if there are no settings.
   */
  public function getEventSettings($event_name);

}

/**
 * Provides the base interface for implementing abstract plugins via classes.
 */
interface RulesPluginHandlerInterface {

  /**
   * Validates $settings independent from a form submission.
   *
   * @throws RulesIntegrityException
   *   In case of validation errors, RulesIntegrityExceptions are thrown.
   */
  public function validate();

  /**
   * Processes settings independent from a form submission.
   *
   * Processing results may be stored and accessed on execution time in $settings.
   */
  public function process();

  /**
   * Allows altering of the element's action/condition info.
   *
   * Note that this method is also invoked on evaluation time, thus any costly
   * operations should be avoided.
   *
   * @param $element_info
   *   A reference on the element's info as returned by RulesPlugin::info().
   */
  public function info_alter(&$element_info);

  /**
   * Checks whether the user has access to configure this element.
   *
   * Note that this only covers access for already created elements. In order to
   * control access for creating or using elements specify an 'access callback'
   * in the element's info array.
   *
   * @see hook_rules_action_info()
   */
  public function access();

  /**
   * Returns an array of required modules.
   */
  public function dependencies();

  /**
   * Alter the generated configuration form of the element.
   *
   * Validation and processing of the settings should be untied from the form
   * and implemented in validate() and process() wherever it makes sense.
   * For the remaining cases where form tied validation and processing is needed
   * make use of the form API #element_validate and #value_callback properties.
   */
  public function form_alter(&$form, $form_state, $options);


  /**
   * Optionally returns an array of info assertions for the specified
   * parameters. This allows conditions to assert additional metadata, such as
   * info about the fields of a bundle.
   *
   * @see RulesPlugin::variableInfoAssertions()
   */
  public function assertions();

}

/**
 * Interface for implementing conditions via classes.
 *
 * In addition to the interface an execute() and a static getInfo() method must
 * be implemented. The static getInfo() method has to return the info as
 * returned by hook_rules_condition_info() but including an additional 'name'
 * key, specifying the plugin name.
 * The execute method is the equivalent to the usual execution callback and
 * gets the parameters passed as specified in the info array.
 *
 * See RulesNodeConditionType for an example and rules_discover_plugins()
 * for information about class discovery.
 */
interface RulesConditionHandlerInterface extends RulesPluginHandlerInterface {}

/**
 * Interface for implementing actions via classes.
 *
 * In addition to the interface an execute() and a static getInfo() method must
 * be implemented. The static getInfo() method has to return the info as
 * returned by hook_rules_action_info() but including an additional 'name' key,
 * specifying the plugin name.
 * The execute method is the equivalent to the usual execution callback and
 * gets the parameters passed as specified in the info array.
 *
 * See RulesNodeConditionType for an example and rules_discover_plugins()
 * for information about class discovery.
 */
interface RulesActionHandlerInterface extends RulesPluginHandlerInterface {}

/**
 *
 * Provides the interface used for implementing an abstract plugin by using
 * the Faces extension mechanism.
 */
interface RulesPluginImplInterface extends RulesPluginHandlerInterface {

  /**
   * Execute the action or condition making use of the parameters as specified.
   */
  public function execute();
}

/**
 * Interface for optimizing evaluation.
 *
 * @see RulesContainerPlugin::optimize()
 */
interface RulesOptimizationInterface {
  /**
   * Optimizes a rule configuration in order to speed up evaluation.
   */
  public function optimize();
}

/**
 * Base class for implementing abstract plugins via classes.
 */
abstract class RulesPluginHandlerBase extends FacesExtender implements RulesPluginHandlerInterface {

  /**
   * @var RulesAbstractPlugin
   */
  protected $element;

  /**
   * Overridden to provide $this->element to make the code more meaningful.
   */
  public function __construct(FacesExtendable $object) {
    $this->object = $object;
    $this->element = $object;
  }

  /**
   * Implements RulesPluginImplInterface.
   */
  public function access() {
    return TRUE;
  }

  public function validate() {}
  public function process() {}
  public function info_alter(&$element_info) {}
  public function dependencies() {}
  public function form_alter(&$form, $form_state, $options) {}
  public function assertions() {}
}

/**
 * Base class for implementing conditions via classes.
 */
abstract class RulesConditionHandlerBase extends RulesPluginHandlerBase implements RulesConditionHandlerInterface {}

/**
 * Base class for implementing actions via classes.
 */
abstract class RulesActionHandlerBase extends RulesPluginHandlerBase implements RulesActionHandlerInterface {}

/**
 * Class providing default implementations of the methods of the RulesPluginImplInterface.
 *
 * If a plugin implementation does not provide a function for a method, the
 * default method of this class will be invoked.
 *
 * @see RulesPluginImplInterface
 * @see RulesAbstractPlugin
 */
class RulesAbstractPluginDefaults extends RulesPluginHandlerBase implements RulesPluginImplInterface {

  public function execute() {
    throw new RulesEvaluationException($this->object->getPluginName() .": Execution implementation is missing.", array(), $this->object, RulesLog::ERROR);
  }
}

/**
 * A RecursiveIterator for rule elements.
 */
class RulesRecursiveElementIterator extends ArrayIterator implements RecursiveIterator {

   public function getChildren() {
     return $this->current()->getIterator();
   }

   public function hasChildren() {
      return $this->current() instanceof IteratorAggregate;
   }
}

/**
 * Base class for ContainerPlugins like Rules, Logical Operations or Loops.
 */
abstract class RulesContainerPlugin extends RulesPlugin implements IteratorAggregate {

  protected $children = array();

  public function __construct($variables = array()) {
    $this->setUp();
    if (!empty($variables) && $this->isRoot()) {
      $this->info['variables'] = $variables;
    }
  }

  /**
   * Returns the specified variables, in case the plugin is used as component.
   */
  public function &componentVariables() {
    if ($this->isRoot()) {
      $this->info += array('variables' => array());
      return $this->info['variables'];
    }
    // We have to return a reference in any case.
    $return = NULL;
    return $return;
  }

  /**
   * Allow access to the children through the iterator.
   *
   * @return RulesRecursiveElementIterator
   */
  public function getIterator() {
    return new RulesRecursiveElementIterator($this->children);
  }

  /**
   * @return RulesContainerPlugin
   */
  public function integrityCheck() {
    if (!empty($this->info['variables']) && !$this->isRoot()) {
      throw new RulesIntegrityException(t('%plugin: Specifying state variables is not possible for child elements.', array('%plugin' => $this->getPluginName())), $this);
    }
    parent::integrityCheck();
    foreach ($this->children as $child) {
      $child->integrityCheck();
    }
    return $this;
  }

  public function dependencies() {
    $modules = array_flip(parent::dependencies());
    foreach ($this->children as $child) {
      $modules += array_flip($child->dependencies());
    }
    return array_keys($modules);
  }

  public function parameterInfo($optional = FALSE) {
    $params = parent::parameterInfo($optional);
    if (isset($this->info['variables'])) {
      foreach ($this->info['variables'] as $name => $var_info) {
        if (empty($var_info['handler']) && (!isset($var_info['parameter']) || $var_info['parameter'])) {
          $params[$name] = $var_info;
          // For lists allow empty variables by default.
          if (entity_property_list_extract_type($var_info['type'])) {
            $params[$name] += array('allow null' => TRUE);
          }
        }
      }
    }
    return $params;
  }

  public function availableVariables() {
    if (!isset($this->availableVariables)) {
      if ($this->isRoot()) {
        $this->availableVariables = RulesState::defaultVariables();
        if (isset($this->info['variables'])) {
          $this->availableVariables += $this->info['variables'];
        }
      }
      else {
        $this->availableVariables = $this->parent->stateVariables($this);
      }
    }
    return $this->availableVariables;
  }

  /**
   * Returns info about variables available in the evaluation state for any
   * children elements or if given for a special child element.
   *
   * @param $element
   *   The element for which the available state variables should be returned.
   *   If NULL is given, the variables available before any children are invoked
   *   are returned. If set to TRUE, the variables available after evaluating
   *   all children will be returned.
   */
  protected function stateVariables($element = NULL) {
    $vars = $this->availableVariables();
    if (isset($element)) {
      // Add in variables provided by siblings executed before the element.
      foreach ($this->children as $child) {
        if ($child === $element) {
          break;
        }
        $vars += $child->providesVariables();
        // Take variable info assertions into account.
        if ($assertions = $child->variableInfoAssertions()) {
          $vars = RulesData::addMetadataAssertions($vars, $assertions);
        }
      }
    }
    return $vars;
  }

  protected function variableInfoAssertions() {
    $assertions = array();
    foreach ($this->children as $child) {
      if ($add = $child->variableInfoAssertions()) {
        $assertions = rules_update_array($assertions, $add);
      }
    }
    return $assertions;
  }

  protected function setUpVariables() {
    return isset($this->info['variables']) ? parent::parameterInfo(TRUE) + $this->info['variables'] : $this->parameterInfo(TRUE);
  }

  /**
   * Condition containers just return a boolean while action containers return
   * the configured provided variables as an array of variables.
   */
  public function executeByArgs($args = array()) {
    $replacements = array('%label' => $this->label(), '@plugin' => $this->itemName);
    rules_log('Executing @plugin %label.', $replacements, RulesLog::INFO, $this, TRUE);
    $this->processSettings();
    $state = $this->setUpState($args);

    // Handle recursion prevention.
    if ($state->isBlocked($this)) {
      return rules_log('Not evaluating @plugin %label to prevent recursion.', array('%label' => $this->label(), '@plugin' => $this->plugin()), RulesLog::INFO);
    }
    // Block the config to prevent any future recursion.
    $state->block($this);

    module_invoke_all('rules_config_execute', $this);
    $result = $this->evaluate($state);
    $return = $this->returnVariables($state, $result);

    $state->unblock($this);
    $state->cleanUp();
    rules_log('Finished executing of @plugin %label.', $replacements, RulesLog::INFO, $this, FALSE);
    return $return;
  }

  public function access() {
    foreach ($this->children as $key => $child) {
      if (!$child->access()) {
        return FALSE;
      }
    }
    return TRUE;
  }

  public function destroy() {
    foreach ($this->children as $key => $child) {
      $child->destroy();
    }
    parent::destroy();
  }

  /**
   * By default we do a deep clone.
   */
  public function __clone() {
    parent::__clone();
    foreach ($this->children as $key => $child) {
      $this->children[$key] = clone $child;
      $this->children[$key]->parent = $this;
    }
  }

  /**
   * Override delete to keep the children alive, if possible.
   */
  public function delete($keep_children = TRUE) {
    if (isset($this->parent) && $keep_children) {
      foreach ($this->children as $child) {
        $child->setParent($this->parent);
      }
    }
    parent::delete();
  }

  public function __sleep() {
    return parent::__sleep() + array('children' => 'children', 'info' => 'info');
  }

  /**
   * Sorts all child elements by their weight.
   *
   * @param $deep
   *   If enabled a deep sort is performed, thus the whole element tree below
   *   this element is sorted.
   */
  public function sortChildren($deep = FALSE) {
    // Make sure the array order is kept in case two children have the same
    // weight by ensuring later childrens would have higher weights.
    foreach (array_values($this->children) as $i => $child) {
      $child->weight += $i / 1000;
    }
    usort($this->children, array('RulesPlugin', 'compare'));

    // Fix up the weights afterwards to be unique integers.
    foreach (array_values($this->children) as $i => $child) {
      $child->weight = $i;
    }

    if ($deep) {
      foreach (new ParentIterator($this->getIterator()) as $child) {
        $child->sortChildren(TRUE);
      }
    }
    $this->resetInternalCache();
  }

  protected function exportChildren($key = NULL) {
    $key = isset($key) ? $key : strtoupper($this->plugin());
    $export[$key] = array();
    foreach ($this->children as $child) {
      $export[$key][] = $child->export();
    }
    return $export;
  }

  /**
   * Determines whether the element should be exported in flat style. Flat style
   * means that the export keys are written directly into the export array,
   * whereas else the export is written into a sub-array.
   */
  protected function exportFlat() {
    // By default we always use flat style for plugins without any parameters
    // or provided variables, as then only children have to be exported. E.g.
    // this applies to the OR and AND plugins.
    return $this->isRoot() || (!$this->pluginParameterInfo() && !$this->providesVariables());
  }

  protected function exportToArray() {
    $export = array();
    if (!empty($this->info['variables'])) {
      $export['USES VARIABLES'] = $this->info['variables'];
    }
    if ($this->exportFlat()) {
      $export += $this->exportSettings() + $this->exportChildren();
    }
    else {
      $export[strtoupper($this->plugin())] = $this->exportSettings() + $this->exportChildren();
    }
    return $export;
  }

  public function import(array $export) {
    if (!empty($export['USES VARIABLES'])) {
      $this->info['variables'] = $export['USES VARIABLES'];
    }
    // Care for exports having the export array nested in a sub-array.
    if (!$this->exportFlat()) {
      $export = reset($export);
    }
    $this->importSettings($export);
    $this->importChildren($export);
  }

  protected function importChildren($export, $key = NULL) {
    $key = isset($key) ? $key : strtoupper($this->plugin());
    foreach ($export[$key] as $child_export) {
      $plugin = _rules_import_get_plugin(rules_array_key($child_export), $this instanceof RulesActionInterface ? 'action' : 'condition');
      $child = rules_plugin_factory($plugin);
      $child->setParent($this);
      $child->import($child_export);
    }
  }

  public function resetInternalCache() {
    $this->availableVariables = NULL;
    foreach ($this->children as $child) {
      $child->resetInternalCache();
    }
  }

  /**
   * Overrides optimize().
   */
  public function optimize() {
    parent::optimize();
    // Now let the children optimize itself.
    foreach ($this as $element) {
      $element->optimize();
    }
  }
}

/**
 * Base class for all action containers.
 */
abstract class RulesActionContainer extends RulesContainerPlugin implements RulesActionInterface {

  public function __construct($variables = array(), $providesVars = array()) {
    parent::__construct($variables);
    // The provided vars of a component are the names of variables, which should
    // be provided to the caller. See rule().
    if ($providesVars) {
      $this->info['provides'] = $providesVars;
    }
  }

  /**
   * Add an action. Pass either an instance of the RulesActionInterface
   * or the arguments as needed by rules_action().
   *
   * @return RulesActionContainer
   *   Returns $this to support chained usage.
   */
  public function action($name, $settings = array()) {
    $action = (is_object($name) && $name instanceof RulesActionInterface) ? $name : rules_action($name, $settings);
    $action->setParent($this);
    return $this;
  }

  /**
   * Evaluate, whereas by default new vars are visible in the parent's scope.
   */
  public function evaluate(RulesState $state) {
    foreach ($this->children as $action) {
      $action->evaluate($state);
    }
  }

  public function pluginProvidesVariables() {
    return array();
  }

  public function providesVariables() {
    $provides = parent::providesVariables();
    if (isset($this->info['provides']) && $vars = $this->componentVariables()) {
      // Determine the full variable info for the provided variables. Note that
      // we only support providing variables list in the component vars.
      $provides += array_intersect_key($vars, array_flip($this->info['provides']));
    }
    return $provides;
  }

  /**
   * Returns an array of variable names, which are provided by passing through
   * the provided variables of the children.
   */
  public function &componentProvidesVariables() {
    $this->info += array('provides' => array());
    return $this->info['provides'];
  }

  protected function exportToArray() {
    $export = parent::exportToArray();
    if (!empty($this->info['provides'])) {
      $export['PROVIDES VARIABLES'] = $this->info['provides'];
    }
    return $export;
  }

  public function import(array $export) {
    parent::import($export);
    if (!empty($export['PROVIDES VARIABLES'])) {
      $this->info['provides'] = $export['PROVIDES VARIABLES'];
    }
  }
}

/**
 * Base class for all condition containers.
 */
abstract class RulesConditionContainer extends RulesContainerPlugin implements RulesConditionInterface {

  protected $negate = FALSE;

  /**
   * Add a condition. Pass either an instance of the RulesConditionInterface
   * or the arguments as needed by rules_condition().
   *
   * @return RulesConditionContainer
   *   Returns $this to support chained usage.
   */
  public function condition($name, $settings = array()) {
    $condition = (is_object($name) && $name instanceof RulesConditionInterface) ? $name : rules_condition($name, $settings);
    $condition->setParent($this);
    return $this;
  }

  /**
   * Negate this condition.
   *
   * @return RulesConditionContainer
   */
  public function negate($negate = TRUE) {
    $this->negate = (bool) $negate;
    return $this;
  }

  public function isNegated() {
    return $this->negate;
  }

  public function __sleep() {
    return parent::__sleep() + array('negate' => 'negate');
  }

  /**
   * Just return the condition container's result.
   */
  protected function returnVariables(RulesState $state, $result = NULL) {
    return $result;
  }

  protected function exportChildren($key = NULL) {
    $key = isset($key) ? $key : strtoupper($this->plugin());
    return parent::exportChildren($this->negate ? 'NOT ' . $key : $key);
  }

  protected function importChildren($export, $key = NULL) {
    $key = isset($key) ? $key : strtoupper($this->plugin());
    // Care for negated elements.
    if (!isset($export[$key]) && isset($export['NOT ' . $key])) {
      $this->negate = TRUE;
      $key = 'NOT ' . $key;
    }
    parent::importChildren($export, $key);
  }

  /**
   * Overridden to exclude variable assertions of negated conditions.
   */
  protected function stateVariables($element = NULL) {
    $vars = $this->availableVariables();
    if (isset($element)) {
      // Add in variables provided by siblings executed before the element.
      foreach ($this->children as $child) {
        if ($child === $element) {
          break;
        }
        $vars += $child->providesVariables();
        // Take variable info assertions into account.
        if (!$this->negate && !$child->isNegated() && ($assertions = $child->variableInfoAssertions())) {
          $vars = RulesData::addMetadataAssertions($vars, $assertions);
        }
      }
    }
    return $vars;
  }
}

/**
 * The rules default logging class.
 */
class RulesLog {

  const INFO  = 1;
  const WARN  = 2;
  const ERROR = 3;

  static protected $logger;

  /**
   * @return RulesLog
   *   Returns the rules logger instance.
   */
  static function logger() {
    if (!isset(self::$logger)) {
      $class = __CLASS__;
      self::$logger = new $class(variable_get('rules_log_level', self::INFO));
    }
    return self::$logger;
  }

  protected $log = array();
  protected $logLevel, $line = 0;

  /**
   * This is a singleton.
   */
  protected function __construct($logLevel = self::WARN) {
    $this->logLevel = $logLevel;
  }

  public function __clone() {
    throw new Exception("Cannot clone the logger.");
  }

  /**
   * Logs a log message.
   *
   * @see rules_log()
   */
  public function log($msg, $args = array(), $logLevel = self::INFO, $scope = NULL, $path = NULL) {
    if ($logLevel >= $this->logLevel) {
      $this->log[] = array($msg, $args, $logLevel, microtime(TRUE), $scope, $path);
    }
  }

  /**
   * Checks the log and throws an exception if there were any problems.
   */
  function checkLog($logLevel = self::WARN) {
    foreach ($this->log as $entry) {
      if ($entry[2] >= $logLevel) {
        throw new Exception($this->render());
      }
    }
  }

  /**
   * Checks the log for (error) messages with a log level equal or higher than the given one.
   *
   * @return
   *   Whether the an error has been logged.
   */
  public function hasErrors($logLevel = self::WARN) {
    foreach ($this->log as $entry) {
      if ($entry[2] >= $logLevel) {
        return TRUE;
      }
    }
    return FALSE;
  }

  /**
   * Gets an array of logged messages.
   */
  public function get() {
    return $this->log;
  }

  /**
   * Renders the whole log.
   */
  public function render() {
    $line = 0;
    $output = array();
    while (isset($this->log[$line])) {
      $vars['head'] = t($this->log[$line][0], $this->log[$line][1]);
      $vars['log'] = $this->renderHelper($line);
      $output[] = theme('rules_debug_element', $vars);
      $line++;
    }
    return implode('', $output);
  }

  /**
   * Renders the log of one event invocation.
   */
  protected function renderHelper(&$line = 0) {
    $startTime = isset($this->log[$line][3]) ? $this->log[$line][3] : 0;
    $output = array();
    while ($line < count($this->log)) {
      if ($output && !empty($this->log[$line][4])) {
        // The next entry stems from another evaluated set, add in its log
        // messages here.
        $vars['head'] = t($this->log[$line][0], $this->log[$line][1]);
        if (isset($this->log[$line][5])) {
          $vars['link'] = '[' . l('edit', $this->log[$line][5]) . ']';
        }
        $vars['log'] = $this->renderHelper($line);
        $output[] = theme('rules_debug_element', $vars);
      }
      else {
        $formatted_diff = round(($this->log[$line][3] - $startTime) * 1000, 3) .' ms';
        $msg = $formatted_diff .' '. t($this->log[$line][0], $this->log[$line][1]);
        if ($this->log[$line][2] >= RulesLog::WARN) {
          $level = $this->log[$line][2] == RulesLog::WARN ? 'warn' : 'error';
          $msg = '<span class="rules-debug-' . $level . '">'. $msg .'</span>';
        }
        if (isset($this->log[$line][5]) && !isset($this->log[$line][4])) {
          $msg .= ' [' . l('edit', $this->log[$line][5]) . ']';
        }
        $output[] = $msg;

        if (isset($this->log[$line][4]) && !$this->log[$line][4]) {
          // This was the last log entry of this set.
          return theme('item_list', array('items' => $output));
        }
      }
      $line++;
    }
    return theme('item_list', array('items' => $output));
  }

  /**
   * Clears the logged messages.
   */
  public function clear() {
    $this->log = array();
  }
}

/**
 * A common exception for Rules.
 *
 * This class can be used to catch all exceptions thrown by Rules.
 */
abstract class RulesException extends Exception {}

/**
 * An exception that is thrown during evaluation.
 *
 * Messages are prepared to be logged to the watchdog, thus not yet translated.
 *
 * @see watchdog()
 */
class RulesEvaluationException extends RulesException {

  public $msg, $args, $severity, $element, $keys = array();

  /**
   * @param $msg
   *   The exception message containing placeholder as t().
   * @param $args
   *   Replacement arguments such as for t().
   * @param $element
   *   The element of a configuration causing the exception or an array
   *   consisting of the element and keys specifying a setting value causing
   *   the exception.
   * @param $severity
   *   The RulesLog severity. Defaults to RulesLog::WARN.
   */
  function __construct($msg, array $args = array(), $element = NULL, $severity = RulesLog::WARN) {
    $this->element = is_array($element) ? array_shift($element) : $element;
    $this->keys = is_array($element) ? $element : array();
    $this->msg = $msg;
    $this->args = $args;
    $this->severity = $severity;
    // If an error happened, run the integrity check on the rules configuration
    // and mark it as dirty if it the check fails.
    if ($severity == RulesLog::ERROR && isset($this->element)) {
      $rules_config = $this->element->root();
      rules_config_update_dirty_flag($rules_config);
      // If we discovered a broken configuration, exclude it in future.
      if ($rules_config->dirty) {
        rules_clear_cache();
      }
    }
    // @todo fix _drupal_decode_exception() to use __toString() and override it.
    $this->message = t($this->msg, $this->args);
  }
}

/**
 * An exception that is thrown for Rules configurations that fail the integrity check.
 *
 * @see RulesPlugin::integrityCheck()
 */
class RulesIntegrityException extends RulesException {

  public $msg, $element, $keys = array();

  /**
   * @param string $msg
   *   The exception message, already translated.
   * @param $element
   *   The element of a configuration causing the exception or an array
   *   consisting of the element and keys specifying a parameter or provided
   *   variable causing the exception, e.g.
   *   @code array($element, 'parameter', 'node') @endcode.
   */
  function __construct($msg, $element = NULL) {
    $this->element = is_array($element) ? array_shift($element) : $element;
    $this->keys = is_array($element) ? $element : array();
    parent::__construct($msg);
  }
}

/**
 * An exception that is thrown for missing module dependencies.
 */
class RulesDependencyException extends RulesIntegrityException {}

/**
 * Determines the plugin to be used for importing a child element.
 *
 * @param $key
 *   The key to look for, e.g. 'OR' or 'DO'.
 * @param $default
 *   The default to return if no special plugin can be found.
 */
function _rules_import_get_plugin($key, $default = 'action') {
  $map = &drupal_static(__FUNCTION__);
  if (!isset($map)) {
    $cache = rules_get_cache();
    foreach ($cache['plugin_info'] as $name => $info) {
      if (!empty($info['embeddable'])) {
        $info += array('import keys' => array(strtoupper($name)));
        foreach ($info['import keys'] as $k) {
          $map[$k] = $name;
        }
      }
    }
  }
  // Cut of any leading NOT from the key.
  if (strpos($key, 'NOT ') === 0) {
    $key = substr($key, 4);
  }
  if (isset($map[$key])) {
    return $map[$key];
  }
  return $default;
}