rules.module 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716
  1. <?php
  2. /**
  3. * @file Rules engine module
  4. */
  5. // Include our hook implementations early, as they can be called even before
  6. // hook_init().
  7. require_once dirname(__FILE__) . '/modules/events.inc';
  8. /**
  9. * Implements hook_module_implements_alter().
  10. */
  11. function rules_module_implements_alter(&$implementations, $hook) {
  12. // Ensures the invocation of hook_menu_get_item_alter() triggers
  13. // rules_menu_get_item_alter() first so the rules invocation is ready for all
  14. // sub-sequent hook implementations.
  15. if ($hook == 'menu_get_item_alter' && array_key_exists('rules', $implementations)) {
  16. $group = $implementations['rules'];
  17. unset($implementations['rules']);
  18. $implementations = array_merge(array('rules' => $group), $implementations);
  19. }
  20. }
  21. /**
  22. * Implements hook_menu_get_item_alter().
  23. */
  24. function rules_menu_get_item_alter() {
  25. // Make sure that event invocation is enabled before menu items are loaded.
  26. // But make sure later calls to menu_get_item() won't automatically re-enabled
  27. // the rules invocation.
  28. // Example: modules that implement hook_entity_ENTITY_TYPE_load() might want
  29. // to invoke Rules events in that load hook, which is also invoked for menu
  30. // item loading. Since this can happen even before hook_init() we need to make
  31. // sure that firing Rules events is enabled at that point. A typical use case
  32. // for this is Drupal Commerce with commerce_cart_commerce_order_load().
  33. if (!drupal_static('rules_init', FALSE)) {
  34. rules_event_invocation_enabled(TRUE);
  35. }
  36. }
  37. /**
  38. * Implements hook_init().
  39. */
  40. function rules_init() {
  41. // See rules_menu_get_item_alter().
  42. $rules_init = &drupal_static(__FUNCTION__, FALSE);
  43. $rules_init = TRUE;
  44. // Enable event invocation once hook_init() was invoked for Rules.
  45. rules_event_invocation_enabled(TRUE);
  46. rules_invoke_event('init');
  47. }
  48. /**
  49. * Returns an instance of the rules UI controller, which eases re-using the Rules UI.
  50. *
  51. * See the rules_admin.module for example usage.
  52. *
  53. * @return RulesUIController
  54. */
  55. function rules_ui() {
  56. $static = drupal_static(__FUNCTION__);
  57. if (!isset($static)) {
  58. $static = new RulesUIController();
  59. }
  60. return $static;
  61. }
  62. /**
  63. * Returns a new rules action.
  64. *
  65. * @param $name
  66. * The action's name.
  67. * @param $settings
  68. * The action's settings array.
  69. * @return RulesAction
  70. */
  71. function rules_action($name, $settings = array()) {
  72. return rules_plugin_factory('action', $name, $settings);
  73. }
  74. /**
  75. * Returns a new rules condition.
  76. *
  77. * @param $name
  78. * The condition's name.
  79. * @param $settings
  80. * The condition's settings array.
  81. * @return RulesCondition
  82. */
  83. function rules_condition($name, $settings = array()) {
  84. return rules_plugin_factory('condition', $name, $settings);
  85. }
  86. /**
  87. * Creates a new rule.
  88. *
  89. * @param $variables
  90. * The array of variables to setup in the evaluation state, making them
  91. * available for the configuraion elements. Values for the variables need to
  92. * be passed as argument when the rule is executed. Only Rule instances with
  93. * no variables can be embedded in other configurations, e.g. rule sets.
  94. * The array has to be keyed by variable name and contain a sub-array for each
  95. * variable that has the same structure as the arrays used for describing
  96. * parameters of an action, see hook_rules_action_info(). However, in addition
  97. * to that the following keys are supported:
  98. * - parameter: (optional) If set to FALSE, no parameter for the variable
  99. * is created - thus no argument needs to be passed to the rule for the
  100. * variable upon execution. As a consequence no value will be set
  101. * initially, but the "Set data value" action may be used to do so. This is
  102. * in particular useful for defining variables which can be provided to the
  103. * caller (see $provides argument) but need not be passed in as parameter.
  104. * @param $provides
  105. * The names of variables which should be provided to the caller. Only
  106. * variables contained in $variables may be specified.
  107. * @return Rule
  108. */
  109. function rule($variables = NULL, $provides = array()) {
  110. return rules_plugin_factory('rule', $variables, $provides);
  111. }
  112. /**
  113. * Creates a new reaction rule.
  114. *
  115. * @return RulesReactionRule
  116. */
  117. function rules_reaction_rule() {
  118. return rules_plugin_factory('reaction rule');
  119. }
  120. /**
  121. * Creates a logical OR condition container.
  122. *
  123. * @param $variables
  124. * An optional array as for rule().
  125. * @return RulesOr
  126. */
  127. function rules_or($variables = NULL) {
  128. return rules_plugin_factory('or', $variables);
  129. }
  130. /**
  131. * Creates a logical AND condition container.
  132. *
  133. * @param $variables
  134. * An optional array as for rule().
  135. * @return RulesAnd
  136. */
  137. function rules_and($variables = NULL) {
  138. return rules_plugin_factory('and', $variables);
  139. }
  140. /**
  141. * Creates a loop.
  142. *
  143. * @param $settings
  144. * The loop settings, containing
  145. * 'list:select': The data selector for the list to loop over.
  146. * 'item:var': Optionally a name for the list item variable.
  147. * 'item:label': Optionally a lebel for the list item variable.
  148. * @param $variables
  149. * An optional array as for rule().
  150. * @return RulesLoop
  151. */
  152. function rules_loop($settings = array(), $variables = NULL) {
  153. return rules_plugin_factory('loop', $settings, $variables);
  154. }
  155. /**
  156. * Creates a rule set.
  157. *
  158. * @param $variables
  159. * An array as for rule().
  160. * @param $provides
  161. * The names of variables which should be provided to the caller. See rule().
  162. * @return RulesRuleSet
  163. */
  164. function rules_rule_set($variables = array(), $provides = array()) {
  165. return rules_plugin_factory('rule set', $variables, $provides);
  166. }
  167. /**
  168. * Creates an action set.
  169. *
  170. * @param $variables
  171. * An array as for rule().
  172. * @param $provides
  173. * The names of variables which should be provided to the caller. See rule().
  174. * @return RulesActionSet
  175. */
  176. function rules_action_set($variables = array(), $provides = array()) {
  177. return rules_plugin_factory('action set', $variables, $provides);
  178. }
  179. /**
  180. * Log a message to the rules logger.
  181. *
  182. * @param $msg
  183. * The message to log.
  184. * @param $args
  185. * An array of placeholder arguments as used by t().
  186. * @param $priority
  187. * A priority as defined by the RulesLog class.
  188. * @param RulesPlugin $element
  189. * (optional) The RulesElement causing the log entry.
  190. * @param boolean $scope
  191. * (optional) This may be used to denote the beginning (TRUE) or the end
  192. * (FALSE) of a new execution scope.
  193. */
  194. function rules_log($msg, $args = array(), $priority = RulesLog::INFO, RulesPlugin $element = NULL, $scope = NULL) {
  195. static $logger, $settings;
  196. // Statically cache the variable settings as this is called very often.
  197. if (!isset($settings)) {
  198. $settings['rules_log_errors'] = variable_get('rules_log_errors', RulesLog::WARN);
  199. $settings['rules_debug_log'] = variable_get('rules_debug_log', FALSE);
  200. $settings['rules_debug'] = variable_get('rules_debug', FALSE);
  201. }
  202. if ($priority >= $settings['rules_log_errors']) {
  203. $link = NULL;
  204. if (isset($element) && isset($element->root()->name)) {
  205. $link = l(t('edit configuration'), RulesPluginUI::path($element->root()->name, 'edit', $element));
  206. }
  207. // Disabled rules invocation to avoid an endless loop when using
  208. // watchdog - which would trigger a rules event.
  209. rules_event_invocation_enabled(FALSE);
  210. watchdog('rules', $msg, $args, $priority == RulesLog::WARN ? WATCHDOG_WARNING : WATCHDOG_ERROR, $link);
  211. rules_event_invocation_enabled(TRUE);
  212. }
  213. // Do nothing in case debugging is totally disabled.
  214. if (!$settings['rules_debug_log'] && !$settings['rules_debug']) {
  215. return;
  216. }
  217. if (!isset($logger)) {
  218. $logger = RulesLog::logger();
  219. }
  220. $path = isset($element) && isset($element->root()->name) ? RulesPluginUI::path($element->root()->name, 'edit', $element) : NULL;
  221. $logger->log($msg, $args, $priority, $scope, $path);
  222. }
  223. /**
  224. * Fetches module definitions for the given hook name.
  225. *
  226. * Used for collecting events, rules, actions and condtions from other modules.
  227. *
  228. * @param $hook
  229. * The hook of the definitions to get from invoking hook_rules_{$hook}.
  230. */
  231. function rules_fetch_data($hook) {
  232. $data = &drupal_static(__FUNCTION__, array());
  233. static $discover = array(
  234. 'action_info' => 'RulesActionHandlerInterface',
  235. 'condition_info' => 'RulesConditionHandlerInterface',
  236. 'event_info' => 'RulesEventHandlerInterface',
  237. );
  238. if (!isset($data[$hook])) {
  239. $data[$hook] = array();
  240. foreach (module_implements('rules_' . $hook) as $module) {
  241. $result = call_user_func($module . '_rules_' . $hook);
  242. if (isset($result) && is_array($result)) {
  243. foreach ($result as $name => $item) {
  244. $item += array('module' => $module);
  245. $data[$hook][$name] = $item;
  246. }
  247. }
  248. }
  249. // Support class discovery.
  250. if (isset($discover[$hook])) {
  251. $data[$hook] += rules_discover_plugins($discover[$hook]);
  252. }
  253. drupal_alter('rules_'. $hook, $data[$hook]);
  254. }
  255. return $data[$hook];
  256. }
  257. /**
  258. * Discover plugin implementations.
  259. *
  260. * Class based plugin handlers must be loaded when rules caches are rebuilt,
  261. * such that they get discovered properly. You have the following options:
  262. * - Put it into a regular module file (discouraged)
  263. * - Put it into your module.rules.inc file
  264. * - Put it in any file and declare it using hook_rules_file_info()
  265. * - Put it in any file and declare it using hook_rules_directory()
  266. *
  267. * In addition to that, the class must be loadable via regular class
  268. * auto-loading, thus put the file holding the class in your info file or use
  269. * another class-loader.
  270. *
  271. * @param string $class
  272. * The class or interface the plugins must implement. For a plugin to be
  273. * discovered it must have a static getInfo() method also.
  274. *
  275. * @return array
  276. * An info-hook style array containing info about discovered plugins.
  277. *
  278. * @see RulesActionHandlerInterface
  279. * @see RulesConditionHandlerInterface
  280. * @see RulesEventHandlerInterface
  281. */
  282. function rules_discover_plugins($class) {
  283. // Make sure all files possibly holding plugins are included.
  284. RulesAbstractPlugin::includeFiles();
  285. $items = array();
  286. foreach (get_declared_classes() as $plugin_class) {
  287. if (is_subclass_of($plugin_class, $class) && method_exists($plugin_class, 'getInfo')) {
  288. $info = call_user_func(array($plugin_class, 'getInfo'));
  289. $info['class'] = $plugin_class;
  290. $info['module'] = _rules_discover_module($plugin_class);
  291. $items[$info['name']] = $info;
  292. }
  293. }
  294. return $items;
  295. }
  296. /**
  297. * Determines the module providing the given class.
  298. */
  299. function _rules_discover_module($class) {
  300. $paths = &drupal_static(__FUNCTION__);
  301. if (!isset($paths)) {
  302. // Build up a map of modules keyed by their directory.
  303. foreach (system_list('module_enabled') as $name => $module_info) {
  304. $paths[dirname($module_info->filename)] = $name;
  305. }
  306. }
  307. // Retrieve the class file and convert its absolute path to a regular Drupal
  308. // path relative to the installation root.
  309. $reflection = new ReflectionClass($class);
  310. $path = str_replace(realpath(DRUPAL_ROOT) . DIRECTORY_SEPARATOR, '', realpath(dirname($reflection->getFileName())));
  311. $path = DIRECTORY_SEPARATOR != '/' ? str_replace(DIRECTORY_SEPARATOR, '/', $path) : $path;
  312. // Go up the path until we match a module up.
  313. $parts = explode('/', $path);
  314. while (!isset($paths[$path]) && array_pop($parts)) {
  315. $path = dirname($path);
  316. }
  317. return isset($paths[$path]) ? $paths[$path] : FALSE;
  318. }
  319. /**
  320. * Gets a rules cache entry.
  321. */
  322. function &rules_get_cache($cid = 'data') {
  323. // Make use of the fast, advanced drupal static pattern.
  324. static $drupal_static_fast;
  325. if (!isset($drupal_static_fast)) {
  326. $drupal_static_fast['cache'] = &drupal_static(__FUNCTION__, array());
  327. }
  328. $cache = &$drupal_static_fast['cache'];
  329. if (!isset($cache[$cid])) {
  330. // The main 'data' cache includes translated strings, so each language is
  331. // cached separately.
  332. $cid_suffix = $cid == 'data' ? ':' . $GLOBALS['language']->language : '';
  333. if ($get = cache_get($cid . $cid_suffix, 'cache_rules')) {
  334. $cache[$cid] = $get->data;
  335. }
  336. else {
  337. // Prevent stampeding by ensuring the cache is rebuilt just once at the
  338. // same time.
  339. while (!lock_acquire(__FUNCTION__ . $cid . $cid_suffix, 60)) {
  340. rules_log('Cache rebuild lock hit: !cid', array('!cid' => $cid), RulesLog::WARN);
  341. // Now wait until the lock is released.
  342. lock_wait(__FUNCTION__ . $cid . $cid_suffix, 10);
  343. // If the lock is released it's likely the cache was rebuild. Thus check
  344. // again if we can fetch it from the persistent cache.
  345. if ($get = cache_get($cid . $cid_suffix, 'cache_rules')) {
  346. $cache[$cid] = $get->data;
  347. return $cache[$cid];
  348. }
  349. }
  350. if ($cid === 'data') {
  351. // There is no 'data' cache so we need to rebuild it. Make sure subsequent
  352. // cache gets of the main 'data' cache during rebuild get the interim
  353. // cache by passing in the reference of the static cache variable.
  354. _rules_rebuild_cache($cache['data']);
  355. }
  356. elseif (strpos($cid, 'comp_') === 0) {
  357. $cache[$cid] = FALSE;
  358. _rules_rebuild_component_cache();
  359. }
  360. elseif (strpos($cid, 'event_') === 0 || $cid == 'rules_event_whitelist') {
  361. $cache[$cid] = FALSE;
  362. RulesEventSet::rebuildEventCache();
  363. }
  364. else {
  365. $cache[$cid] = FALSE;
  366. }
  367. // Ensure a set lock is released.
  368. lock_release(__FUNCTION__ . $cid . $cid_suffix);
  369. }
  370. }
  371. return $cache[$cid];
  372. }
  373. /**
  374. * Rebuilds the rules cache.
  375. *
  376. * This rebuilds the rules 'data' cache and invokes rebuildCache() methods on
  377. * all plugin classes, which allows plugins to add their own data to the cache.
  378. * The cache is rebuilt in the order the plugins are defined.
  379. *
  380. * Note that building the action/condition info cache triggers loading of all
  381. * components, thus depends on entity-loading and so syncing entities in code
  382. * to the database.
  383. *
  384. * @see rules_rules_plugin_info()
  385. * @see entity_defaults_rebuild()
  386. */
  387. function _rules_rebuild_cache(&$cache) {
  388. foreach(array('data_info', 'plugin_info') as $hook) {
  389. $cache[$hook] = rules_fetch_data($hook);
  390. }
  391. foreach ($cache['plugin_info'] as $name => &$info) {
  392. // Let the items add something to the cache.
  393. $item = new $info['class']();
  394. $item->rebuildCache($info, $cache);
  395. }
  396. $cid_suffix = ':' . $GLOBALS['language']->language;
  397. cache_set('data' . $cid_suffix, $cache, 'cache_rules');
  398. }
  399. /**
  400. * Cache components to allow efficient usage via rules_invoke_component().
  401. *
  402. * @see rules_invoke_component()
  403. * @see rules_get_cache()
  404. */
  405. function _rules_rebuild_component_cache() {
  406. $components = rules_get_components();
  407. foreach ($components as $id => $component) {
  408. // If a component is marked as dirty, check if this still applies.
  409. if ($component->dirty) {
  410. rules_config_update_dirty_flag($component);
  411. }
  412. if (!$component->dirty) {
  413. // Clone the component to avoid modules getting the to be cached
  414. // version from the static loading cache.
  415. $component = clone $component;
  416. $component->optimize();
  417. // Allow modules to alter the cached component.
  418. drupal_alter('rules_component', $component->plugin, $component);
  419. rules_set_cache('comp_' . $component->name, $component);
  420. }
  421. }
  422. }
  423. /**
  424. * Sets a rules cache item.
  425. *
  426. * In addition to calling cache_set(), this function makes sure the cache item
  427. * is immediately available via rules_get_cache() by keeping all cache items
  428. * in memory. That way we can guarantee rules_get_cache() is able to retrieve
  429. * any cache item, even if all cache gets fail.
  430. *
  431. * @see rules_get_cache()
  432. */
  433. function rules_set_cache($cid, $data) {
  434. $cache = &drupal_static('rules_get_cache', array());
  435. $cache[$cid] = $data;
  436. cache_set($cid, $data, 'cache_rules');
  437. }
  438. /**
  439. * Implements hook_flush_caches().
  440. */
  441. function rules_flush_caches() {
  442. return array('cache_rules');
  443. }
  444. /**
  445. * Clears the rule set cache
  446. */
  447. function rules_clear_cache() {
  448. cache_clear_all('*', 'cache_rules', TRUE);
  449. drupal_static_reset('rules_get_cache');
  450. drupal_static_reset('rules_fetch_data');
  451. drupal_static_reset('rules_config_update_dirty_flag');
  452. entity_get_controller('rules_config')->resetCache();
  453. }
  454. /**
  455. * Imports the given export and returns the imported configuration.
  456. *
  457. * @param $export
  458. * A serialized string in JSON format as produced by the RulesPlugin::export()
  459. * method, or the PHP export as usual PHP array.
  460. * @return RulesPlugin
  461. */
  462. function rules_import($export, &$error_msg = '') {
  463. return entity_get_controller('rules_config')->import($export, $error_msg);
  464. }
  465. /**
  466. * Wraps the given data.
  467. *
  468. * @param $data
  469. * If available, the actual data, else NULL.
  470. * @param $info
  471. * An array of info about this data.
  472. * @param $force
  473. * Usually data is only wrapped if really needed. If set to TRUE, wrapping the
  474. * data is forced, so primitive data types are also wrapped.
  475. * @return EntityMetadataWrapper
  476. * An EntityMetadataWrapper or the unwrapped data.
  477. *
  478. * @see hook_rules_data_info()
  479. */
  480. function &rules_wrap_data($data = NULL, $info, $force = FALSE) {
  481. // If the data is already wrapped, use the existing wrapper.
  482. if ($data instanceof EntityMetadataWrapper) {
  483. return $data;
  484. }
  485. $cache = rules_get_cache();
  486. // Define the keys to be passed through to the metadata wrapper.
  487. $wrapper_keys = array_flip(array('property info', 'property defaults'));
  488. if (isset($cache['data_info'][$info['type']])) {
  489. $info += array_intersect_key($cache['data_info'][$info['type']], $wrapper_keys);
  490. }
  491. // If a list is given, also add in the info of the item type.
  492. $list_item_type = entity_property_list_extract_type($info['type']);
  493. if ($list_item_type && isset($cache['data_info'][$list_item_type])) {
  494. $info += array_intersect_key($cache['data_info'][$list_item_type], $wrapper_keys);
  495. }
  496. // By default we do not wrap the data, except for completely unknown types.
  497. if (!empty($cache['data_info'][$info['type']]['wrap']) || $list_item_type || $force || empty($cache['data_info'][$info['type']])) {
  498. unset($info['handler']);
  499. // Allow data types to define custom wrapper classes.
  500. if (!empty($cache['data_info'][$info['type']]['wrapper class'])) {
  501. $class = $cache['data_info'][$info['type']]['wrapper class'];
  502. $wrapper = new $class($info['type'], $data, $info);
  503. }
  504. else {
  505. $wrapper = entity_metadata_wrapper($info['type'], $data, $info);
  506. }
  507. return $wrapper;
  508. }
  509. return $data;
  510. }
  511. /**
  512. * Unwraps the given data, if it's wrapped.
  513. *
  514. * @param $data
  515. * An array of wrapped data.
  516. * @param $info
  517. * Optionally an array of info about how to unwrap the data. Keyed as $data.
  518. * @return
  519. * An array containing unwrapped or passed through data.
  520. */
  521. function rules_unwrap_data(array $data, $info = array()) {
  522. $cache = rules_get_cache();
  523. foreach ($data as $key => $entry) {
  524. // If it's a wrapper, unwrap unless specified otherwise.
  525. if ($entry instanceof EntityMetadataWrapper) {
  526. if (!isset($info[$key]['allow null'])) {
  527. $info[$key]['allow null'] = FALSE;
  528. }
  529. if (!isset($info[$key]['wrapped'])) {
  530. // By default, do not unwrap special data types that are always wrapped.
  531. $info[$key]['wrapped'] = (isset($info[$key]['type']) && is_string($info[$key]['type']) && !empty($cache['data_info'][$info[$key]['type']]['is wrapped']));
  532. }
  533. // Activate the decode option by default if 'sanitize' is not enabled, so
  534. // any text is either sanitized or decoded.
  535. // @see EntityMetadataWrapper::value()
  536. $options = $info[$key] + array('decode' => empty($info[$key]['sanitize']));
  537. try {
  538. if (!($info[$key]['allow null'] && $info[$key]['wrapped'])) {
  539. $value = $entry->value($options);
  540. if (!$info[$key]['wrapped']) {
  541. $data[$key] = $value;
  542. }
  543. if (!$info[$key]['allow null'] && !isset($value)) {
  544. throw new RulesEvaluationException('The variable or parameter %name is empty.', array('%name' => $key));
  545. }
  546. }
  547. }
  548. catch (EntityMetadataWrapperException $e) {
  549. throw new RulesEvaluationException('Unable to get the data value for the variable or parameter %name. Error: !error', array('%name' => $key, '!error' => $e->getMessage()));
  550. }
  551. }
  552. }
  553. return $data;
  554. }
  555. /**
  556. * Gets event info for a given event.
  557. *
  558. * @param string $event_name
  559. * A (configured) event name.
  560. *
  561. * @return array
  562. * An array of event info. If the event is unknown, a suiting info array is
  563. * generated and returned
  564. */
  565. function rules_get_event_info($event_name) {
  566. $base_event_name = rules_get_event_base_name($event_name);
  567. $events = rules_fetch_data('event_info');
  568. if (isset($events[$base_event_name])) {
  569. return $events[$base_event_name] + array('name' => $base_event_name);
  570. }
  571. return array(
  572. 'label' => t('Unknown event "!event_name"', array('!event_name' => $base_event_name)),
  573. 'name' => $base_event_name,
  574. );
  575. }
  576. /**
  577. * Returns the base name of a configured event name.
  578. *
  579. * For a configured event name like node_view--article the base event name
  580. * node_view is returned.
  581. *
  582. * @return string
  583. * The event base name.
  584. */
  585. function rules_get_event_base_name($event_name) {
  586. // Cut off any suffix from a configured event name.
  587. if (strpos($event_name, '--') !== FALSE) {
  588. $parts = explode('--', $event_name, 2);
  589. return $parts[0];
  590. }
  591. return $event_name;
  592. }
  593. /**
  594. * Returns the rule event handler for the given event.
  595. *
  596. * Events having no settings are handled via the class RulesEventSettingsNone.
  597. *
  598. * @param string $event_name
  599. * The event name (base or configured).
  600. * @param array $settings
  601. * (optional) An array of event settings to set on the handler.
  602. *
  603. * @return RulesEventHandlerInterface
  604. * The event handler.
  605. */
  606. function rules_get_event_handler($event_name, array $settings = NULL) {
  607. $event_name = rules_get_event_base_name($event_name);
  608. $event_info = rules_get_event_info($event_name);
  609. $class = !empty($event_info['class']) ? $event_info['class'] : 'RulesEventDefaultHandler';
  610. $handler = new $class($event_name, $event_info);
  611. return isset($settings) ? $handler->setSettings($settings) : $handler;
  612. }
  613. /**
  614. * Creates a new instance of a the given rules plugin.
  615. *
  616. * @return RulesPlugin
  617. */
  618. function rules_plugin_factory($plugin_name, $arg1 = NULL, $arg2 = NULL) {
  619. $cache = rules_get_cache();
  620. if (isset($cache['plugin_info'][$plugin_name]['class'])) {
  621. return new $cache['plugin_info'][$plugin_name]['class']($arg1, $arg2);
  622. }
  623. }
  624. /**
  625. * Implementation of hook_rules_plugin_info().
  626. *
  627. * Note that the cache is rebuilt in the order of the plugins. Therefore the
  628. * condition and action plugins must be at the top, so that any components
  629. * re-building their cache can create configurations including properly setup-ed
  630. * actions and conditions.
  631. */
  632. function rules_rules_plugin_info() {
  633. return array(
  634. 'condition' => array(
  635. 'class' => 'RulesCondition',
  636. 'embeddable' => 'RulesConditionContainer',
  637. 'extenders' => array (
  638. 'RulesPluginImplInterface' => array(
  639. 'class' => 'RulesAbstractPluginDefaults',
  640. ),
  641. 'RulesPluginFeaturesIntegrationInterace' => array(
  642. 'methods' => array(
  643. 'features_export' => 'rules_features_abstract_default_features_export',
  644. ),
  645. ),
  646. 'RulesPluginUIInterface' => array(
  647. 'class' => 'RulesAbstractPluginUI',
  648. ),
  649. ),
  650. ),
  651. 'action' => array(
  652. 'class' => 'RulesAction',
  653. 'embeddable' => 'RulesActionContainer',
  654. 'extenders' => array (
  655. 'RulesPluginImplInterface' => array(
  656. 'class' => 'RulesAbstractPluginDefaults',
  657. ),
  658. 'RulesPluginFeaturesIntegrationInterace' => array(
  659. 'methods' => array(
  660. 'features_export' => 'rules_features_abstract_default_features_export',
  661. ),
  662. ),
  663. 'RulesPluginUIInterface' => array(
  664. 'class' => 'RulesAbstractPluginUI',
  665. ),
  666. ),
  667. ),
  668. 'or' => array(
  669. 'label' => t('Condition set (OR)'),
  670. 'class' => 'RulesOr',
  671. 'embeddable' => 'RulesConditionContainer',
  672. 'component' => TRUE,
  673. 'extenders' => array(
  674. 'RulesPluginUIInterface' => array(
  675. 'class' => 'RulesConditionContainerUI',
  676. ),
  677. ),
  678. ),
  679. 'and' => array(
  680. 'label' => t('Condition set (AND)'),
  681. 'class' => 'RulesAnd',
  682. 'embeddable' => 'RulesConditionContainer',
  683. 'component' => TRUE,
  684. 'extenders' => array(
  685. 'RulesPluginUIInterface' => array(
  686. 'class' => 'RulesConditionContainerUI',
  687. ),
  688. ),
  689. ),
  690. 'action set' => array(
  691. 'label' => t('Action set'),
  692. 'class' => 'RulesActionSet',
  693. 'embeddable' => FALSE,
  694. 'component' => TRUE,
  695. 'extenders' => array(
  696. 'RulesPluginUIInterface' => array(
  697. 'class' => 'RulesActionContainerUI',
  698. ),
  699. ),
  700. ),
  701. 'rule' => array(
  702. 'label' => t('Rule'),
  703. 'class' => 'Rule',
  704. 'embeddable' => 'RulesRuleSet',
  705. 'component' => TRUE,
  706. 'extenders' => array(
  707. 'RulesPluginUIInterface' => array(
  708. 'class' => 'RulesRuleUI',
  709. ),
  710. ),
  711. ),
  712. 'loop' => array(
  713. 'class' => 'RulesLoop',
  714. 'embeddable' => 'RulesActionContainer',
  715. 'extenders' => array(
  716. 'RulesPluginUIInterface' => array(
  717. 'class' => 'RulesLoopUI',
  718. ),
  719. ),
  720. ),
  721. 'reaction rule' => array(
  722. 'class' => 'RulesReactionRule',
  723. 'embeddable' => FALSE,
  724. 'extenders' => array(
  725. 'RulesPluginUIInterface' => array(
  726. 'class' => 'RulesReactionRuleUI',
  727. ),
  728. ),
  729. ),
  730. 'event set' => array(
  731. 'class' => 'RulesEventSet',
  732. 'embeddable' => FALSE,
  733. ),
  734. 'rule set' => array(
  735. 'label' => t('Rule set'),
  736. 'class' => 'RulesRuleSet',
  737. 'component' => TRUE,
  738. // Rule sets don't get embedded - we use a separate action to execute.
  739. 'embeddable' => FALSE,
  740. 'extenders' => array(
  741. 'RulesPluginUIInterface' => array(
  742. 'class' => 'RulesRuleSetUI',
  743. ),
  744. ),
  745. ),
  746. );
  747. }
  748. /**
  749. * Implementation of hook_entity_info().
  750. */
  751. function rules_entity_info() {
  752. return array(
  753. 'rules_config' => array(
  754. 'label' => t('Rules configuration'),
  755. 'controller class' => 'RulesEntityController',
  756. 'base table' => 'rules_config',
  757. 'fieldable' => TRUE,
  758. 'entity keys' => array(
  759. 'id' => 'id',
  760. 'name' => 'name',
  761. 'label' => 'label',
  762. ),
  763. 'module' => 'rules',
  764. 'static cache' => TRUE,
  765. 'bundles' => array(),
  766. 'configuration' => TRUE,
  767. 'exportable' => TRUE,
  768. 'export' => array(
  769. 'default hook' => 'default_rules_configuration',
  770. ),
  771. 'access callback' => 'rules_config_access',
  772. 'features controller class' => 'RulesFeaturesController',
  773. ),
  774. );
  775. }
  776. /**
  777. * Implementation of hook_hook_info().
  778. */
  779. function rules_hook_info() {
  780. foreach(array('plugin_info', 'rules_directory', 'data_info', 'condition_info', 'action_info', 'event_info', 'file_info', 'evaluator_info', 'data_processor_info') as $hook) {
  781. $hooks['rules_' . $hook] = array(
  782. 'group' => 'rules',
  783. );
  784. $hooks['rules_' . $hook . '_alter'] = array(
  785. 'group' => 'rules',
  786. );
  787. }
  788. $hooks['default_rules_configuration'] = array(
  789. 'group' => 'rules_defaults',
  790. );
  791. $hooks['default_rules_configuration_alter'] = array(
  792. 'group' => 'rules_defaults',
  793. );
  794. return $hooks;
  795. }
  796. /**
  797. * Load rule configurations from the database.
  798. *
  799. * This function should be used whenever you need to load more than one entity
  800. * from the database. The entities are loaded into memory and will not require
  801. * database access if loaded again during the same page request.
  802. *
  803. * @see hook_entity_info()
  804. * @see RulesEntityController
  805. *
  806. * @param $names
  807. * An array of rules configuration names or FALSE to load all.
  808. * @param $conditions
  809. * An array of conditions in the form 'field' => $value.
  810. *
  811. * @return
  812. * An array of rule configurations indexed by their ids.
  813. */
  814. function rules_config_load_multiple($names = array(), $conditions = array()) {
  815. return entity_load_multiple_by_name('rules_config', $names, $conditions);
  816. }
  817. /**
  818. * Loads a single rule configuration from the database.
  819. *
  820. * @see rules_config_load_multiple()
  821. *
  822. * @return RulesPlugin
  823. */
  824. function rules_config_load($name) {
  825. return entity_load_single('rules_config', $name);
  826. }
  827. /**
  828. * Returns an array of configured components.
  829. *
  830. * For actually executing a component use rules_invoke_component(), as this
  831. * retrieves the component from cache instead.
  832. *
  833. * @param $label
  834. * Whether to return only the label or the whole component object.
  835. * @param $type
  836. * Optionally filter for 'action' or 'condition' components.
  837. * @param $conditions
  838. * An array of additional conditions as required by rules_config_load().
  839. *
  840. * @return
  841. * An array keyed by component name containing either the label or the config.
  842. */
  843. function rules_get_components($label = FALSE, $type = NULL, $conditions = array()) {
  844. $cache = rules_get_cache();
  845. $plugins = array_keys(rules_filter_array($cache['plugin_info'], 'component', TRUE));
  846. $conditions = $conditions + array('plugin' => $plugins);
  847. $faces = array(
  848. 'action' => 'RulesActionInterface',
  849. 'condition' => 'RulesConditionInterface',
  850. );
  851. $items = array();
  852. foreach (rules_config_load_multiple(FALSE, $conditions) as $name => $config) {
  853. if (!isset($type) || $config instanceof $faces[$type]) {
  854. $items[$name] = $label ? $config->label() : $config;
  855. }
  856. }
  857. return $items;
  858. }
  859. /**
  860. * Delete rule configurations from database.
  861. *
  862. * @param $ids
  863. * An array of entity IDs.
  864. */
  865. function rules_config_delete(array $ids) {
  866. return entity_get_controller('rules_config')->delete($ids);
  867. }
  868. /**
  869. * Ensures the configuration's 'dirty' flag is up to date by running an integrity check.
  870. *
  871. * @param $update
  872. * (optional) Whether the dirty flag is also updated in the database if
  873. * necessary. Defaults to TRUE.
  874. */
  875. function rules_config_update_dirty_flag($rules_config, $update = TRUE) {
  876. // Keep a log of already check configurations to avoid repetitive checks on
  877. // oftent used components.
  878. // @see rules_element_invoke_component_validate()
  879. $checked = &drupal_static(__FUNCTION__, array());
  880. if (!empty($checked[$rules_config->name])) {
  881. return;
  882. }
  883. $checked[$rules_config->name] = TRUE;
  884. $was_dirty = !empty($rules_config->dirty);
  885. try {
  886. // First set the rule to dirty, so any repetitive checks give green light
  887. // for this configuration.
  888. $rules_config->dirty = FALSE;
  889. $rules_config->integrityCheck();
  890. if ($was_dirty) {
  891. $variables = array('%label' => $rules_config->label(), '%name' => $rules_config->name, '@plugin' => $rules_config->plugin());
  892. watchdog('rules', 'The @plugin %label (%name) was marked dirty, but passes the integrity check now and is active again.', $variables, WATCHDOG_INFO);
  893. }
  894. }
  895. catch (RulesIntegrityException $e) {
  896. $rules_config->dirty = TRUE;
  897. if (!$was_dirty) {
  898. $variables = array('%label' => $rules_config->label(), '%name' => $rules_config->name, '!message' => $e->getMessage(), '@plugin' => $rules_config->plugin());
  899. watchdog('rules', 'The @plugin %label (%name) fails the integrity check and cannot be executed. Error: !message', $variables, WATCHDOG_ERROR);
  900. }
  901. }
  902. // Save the updated dirty flag to the database.
  903. if ($was_dirty != $rules_config->dirty) {
  904. db_update('rules_config')
  905. ->fields(array('dirty' => (int) $rules_config->dirty))
  906. ->condition('id', $rules_config->id)
  907. ->execute();
  908. }
  909. }
  910. /**
  911. * Invokes a hook and the associated rules event.
  912. *
  913. * Calling this function does the same as calling module_invoke_all() and
  914. * rules_invoke_event() separately, however merges both functions into one in
  915. * order to ease usage and to work efficiently.
  916. *
  917. * @param $hook
  918. * The name of the hook / event to invoke.
  919. * @param ...
  920. * Arguments to pass to the hook / event.
  921. *
  922. * @return
  923. * An array of return values of the hook implementations. If modules return
  924. * arrays from their implementations, those are merged into one array.
  925. */
  926. function rules_invoke_all() {
  927. // Copied code from module_invoke_all().
  928. $args = func_get_args();
  929. $hook = $args[0];
  930. unset($args[0]);
  931. $return = array();
  932. foreach (module_implements($hook) as $module) {
  933. $function = $module . '_' . $hook;
  934. if (function_exists($function)) {
  935. $result = call_user_func_array($function, $args);
  936. if (isset($result) && is_array($result)) {
  937. $return = array_merge_recursive($return, $result);
  938. }
  939. elseif (isset($result)) {
  940. $return[] = $result;
  941. }
  942. }
  943. }
  944. // Invoke the event.
  945. rules_invoke_event_by_args($hook, $args);
  946. return $return;
  947. }
  948. /**
  949. * Invokes configured rules for the given event.
  950. *
  951. * @param $event_name
  952. * The event's name.
  953. * @param ...
  954. * Pass parameters for the variables provided by this event, as defined in
  955. * hook_rules_event_info(). Example given:
  956. * @code
  957. * rules_invoke_event('node_view', $node, $view_mode);
  958. * @endcode
  959. *
  960. * @see rules_invoke_event_by_args()
  961. */
  962. function rules_invoke_event() {
  963. $args = func_get_args();
  964. $event_name = $args[0];
  965. unset($args[0]);
  966. // We maintain a whitelist of configured events to reduces the number of cache
  967. // reads. If the whitelist is empty we proceed and it is rebuilt.
  968. if (rules_event_invocation_enabled()) {
  969. $whitelist = rules_get_cache('rules_event_whitelist');
  970. if ((empty($whitelist) || isset($whitelist[$event_name])) && $event = rules_get_cache('event_' . $event_name)) {
  971. $event->executeByArgs($args);
  972. }
  973. }
  974. }
  975. /**
  976. * Invokes configured rules for the given event.
  977. *
  978. * @param $event_name
  979. * The event's name.
  980. * @param $args
  981. * An array of parameters for the variables provided by the event, as defined
  982. * in hook_rules_event_info(). Either pass an array keyed by the variable
  983. * names or a numerically indexed array, in which case the ordering of the
  984. * passed parameters has to match the order of the specified variables.
  985. * Example given:
  986. * @code
  987. * rules_invoke_event_by_args('node_view', array('node' => $node, 'view_mode' => $view_mode));
  988. * @endcode
  989. *
  990. * @see rules_invoke_event()
  991. */
  992. function rules_invoke_event_by_args($event_name, $args = array()) {
  993. // We maintain a whitelist of configured events to reduces the number of cache
  994. // reads. If the whitelist is empty we proceed and it is rebuilt.
  995. if (rules_event_invocation_enabled()) {
  996. $whitelist = rules_get_cache('rules_event_whitelist');
  997. if ((empty($whitelist) || isset($whitelist[$event_name])) && $event = rules_get_cache('event_' . $event_name)) {
  998. $event->executeByArgs($args);
  999. }
  1000. }
  1001. }
  1002. /**
  1003. * Invokes a rule component, e.g. a rule set.
  1004. *
  1005. * @param $component_name
  1006. * The component's name.
  1007. * @param $args
  1008. * Pass further parameters as required for the invoked component.
  1009. *
  1010. * @return
  1011. * An array of variables as provided by the component, or FALSE in case the
  1012. * component could not be executed.
  1013. */
  1014. function rules_invoke_component() {
  1015. $args = func_get_args();
  1016. $name = array_shift($args);
  1017. if ($component = rules_get_cache('comp_' . $name)) {
  1018. return $component->executeByArgs($args);
  1019. }
  1020. return FALSE;
  1021. }
  1022. /**
  1023. * Filters the given array of arrays by keeping only entries which have $key set
  1024. * to the value of $value.
  1025. *
  1026. * @param $array
  1027. * The array of arrays to filter.
  1028. * @param $key
  1029. * The key used for the comparison.
  1030. * @param $value
  1031. * The value to compare the array's entry to.
  1032. *
  1033. * @return array
  1034. * The filtered array.
  1035. */
  1036. function rules_filter_array($array, $key, $value) {
  1037. $return = array();
  1038. foreach ($array as $i => $entry) {
  1039. $entry += array($key => NULL);
  1040. if ($entry[$key] == $value) {
  1041. $return[$i] = $entry;
  1042. }
  1043. }
  1044. return $return;
  1045. }
  1046. /**
  1047. * Merges the $update array into $array making sure no values of $array not
  1048. * appearing in $update are lost.
  1049. *
  1050. * @return
  1051. * The updated array.
  1052. */
  1053. function rules_update_array(array $array, array $update) {
  1054. foreach ($update as $key => $data) {
  1055. if (isset($array[$key]) && is_array($array[$key]) && is_array($data)) {
  1056. $array[$key] = rules_update_array($array[$key], $data);
  1057. }
  1058. else {
  1059. $array[$key] = $data;
  1060. }
  1061. }
  1062. return $array;
  1063. }
  1064. /**
  1065. * Extracts the property with the given name.
  1066. *
  1067. * @param $arrays
  1068. * An array of arrays from which a property is to be extracted.
  1069. * @param $key
  1070. * The name of the property to extract.
  1071. *
  1072. * @return An array of extracted properties, keyed as in $arrays-
  1073. */
  1074. function rules_extract_property($arrays, $key) {
  1075. $data = array();
  1076. foreach ($arrays as $name => $item) {
  1077. $data[$name] = $item[$key];
  1078. }
  1079. return $data;
  1080. }
  1081. /**
  1082. * Returns the first key of the array.
  1083. */
  1084. function rules_array_key($array) {
  1085. reset($array);
  1086. return key($array);
  1087. }
  1088. /**
  1089. * Clean replacements so they are URL friendly.
  1090. *
  1091. * Can be used as 'cleaning callback' for action or condition parameters.
  1092. *
  1093. * @param $replacements
  1094. * An array of token replacements that need to be "cleaned" for use in the URL.
  1095. * @param $data
  1096. * An array of objects used to generate the replacements.
  1097. * @param $options
  1098. * An array of options used to generate the replacements.
  1099. *
  1100. * @see rules_path_action_info()
  1101. */
  1102. function rules_path_clean_replacement_values(&$replacements, $data = array(), $options = array()) {
  1103. // Include path.eval.inc which contains path cleaning functions.
  1104. module_load_include('inc', 'rules', 'modules/path.eval');
  1105. foreach ($replacements as $token => $value) {
  1106. $replacements[$token] = rules_clean_path($value);
  1107. }
  1108. }
  1109. /**
  1110. * Implements hook_theme().
  1111. */
  1112. function rules_theme() {
  1113. return array(
  1114. 'rules_elements' => array(
  1115. 'render element' => 'element',
  1116. 'file' => 'ui/ui.theme.inc',
  1117. ),
  1118. 'rules_content_group' => array(
  1119. 'render element' => 'element',
  1120. 'file' => 'ui/ui.theme.inc',
  1121. ),
  1122. 'rules_parameter_configuration' => array(
  1123. 'render element' => 'element',
  1124. 'file' => 'ui/ui.theme.inc',
  1125. ),
  1126. 'rules_variable_view' => array(
  1127. 'render element' => 'element',
  1128. 'file' => 'ui/ui.theme.inc',
  1129. ),
  1130. 'rules_data_selector_help' => array(
  1131. 'variables' => array('parameter' => NULL, 'variables' => NULL),
  1132. 'file' => 'ui/ui.theme.inc',
  1133. ),
  1134. 'rules_ui_variable_form' => array(
  1135. 'render element' => 'element',
  1136. 'file' => 'ui/ui.theme.inc',
  1137. ),
  1138. 'rules_log' => array(
  1139. 'render element' => 'element',
  1140. 'file' => 'ui/ui.theme.inc',
  1141. ),
  1142. 'rules_autocomplete' => array(
  1143. 'render element' => 'element',
  1144. 'file' => 'ui/ui.theme.inc',
  1145. ),
  1146. 'rules_debug_element' => array(
  1147. 'render element' => 'element',
  1148. 'file' => 'ui/ui.theme.inc',
  1149. ),
  1150. 'rules_settings_help' => array(
  1151. 'variables' => array('text' => '', 'heading' => ''),
  1152. 'file' => 'ui/ui.theme.inc',
  1153. ),
  1154. );
  1155. }
  1156. /**
  1157. * Implements hook_permission().
  1158. */
  1159. function rules_permission() {
  1160. $perms = array(
  1161. 'administer rules' => array(
  1162. 'title' => t('Administer rule configurations'),
  1163. 'description' => t('Administer rule configurations including events, conditions and actions for which the user has sufficient access permissions.'),
  1164. ),
  1165. 'bypass rules access' => array(
  1166. 'title' => t('Bypass Rules access control'),
  1167. 'description' => t('Control all configurations regardless of permission restrictions of events, conditions or actions.'),
  1168. 'restrict access' => TRUE,
  1169. ),
  1170. 'access rules debug' => array(
  1171. 'title' => t('Access the Rules debug log'),
  1172. ),
  1173. );
  1174. // Fetch all components to generate the access keys.
  1175. $conditions['plugin'] = array_keys(rules_filter_array(rules_fetch_data('plugin_info'), 'component', TRUE));
  1176. $conditions['access_exposed'] = 1;
  1177. $components = entity_load('rules_config', FALSE, $conditions);
  1178. $perms += rules_permissions_by_component($components);
  1179. return $perms;
  1180. }
  1181. /**
  1182. * Helper function to get all the permissions for components that have access exposed.
  1183. */
  1184. function rules_permissions_by_component(array $components = array()) {
  1185. $perms = array();
  1186. foreach ($components as $component) {
  1187. $perms += array(
  1188. "use Rules component $component->name" => array(
  1189. 'title' => t('Use Rules component %component', array('%component' => $component->label())),
  1190. 'description' => t('Controls access for using the component %component via the provided action or condition. <a href="@component-edit-url">Edit this component.</a>', array('%component' => $component->label(), '@component-edit-url' => url(RulesPluginUI::path($component->name)))),
  1191. ),
  1192. );
  1193. }
  1194. return $perms;
  1195. }
  1196. /**
  1197. * Menu callback for loading rules configuration elements.
  1198. * @see RulesUIController::config_menu()
  1199. */
  1200. function rules_element_load($element_id, $config_name) {
  1201. $config = rules_config_load($config_name);
  1202. return $config->elementMap()->lookup($element_id);
  1203. }
  1204. /**
  1205. * Menu callback for getting the title as configured.
  1206. * @see RulesUIController::config_menu()
  1207. */
  1208. function rules_get_title($text, $element) {
  1209. if ($element instanceof RulesPlugin) {
  1210. $cache = rules_get_cache();
  1211. $plugin = $element->plugin();
  1212. $plugin = isset($cache['plugin_info'][$plugin]['label']) ? $cache['plugin_info'][$plugin]['label'] : $plugin;
  1213. $plugin = drupal_strtolower(drupal_substr($plugin, 0, 1)) . drupal_substr($plugin, 1);
  1214. return t($text, array('!label' => $element->label(), '!plugin' => $plugin));
  1215. }
  1216. // As fallback treat $element as simple string.
  1217. return t($text, array('!plugin' => $element));
  1218. }
  1219. /**
  1220. * Menu callback for getting the title for the add element page.
  1221. *
  1222. * Uses a work-a-round for accessing the plugin name.
  1223. * @see RulesUIController::config_menu()
  1224. */
  1225. function rules_menu_add_element_title($array) {
  1226. $plugin_name = arg($array[0]);
  1227. $cache = rules_get_cache();
  1228. if (isset($cache['plugin_info'][$plugin_name]['class'])) {
  1229. $info = $cache['plugin_info'][$plugin_name] + array('label' => $plugin_name);
  1230. $label = drupal_strtolower(drupal_substr($info['label'], 0, 1)) . drupal_substr($info['label'], 1);
  1231. return t('Add a new !plugin', array('!plugin' => $label));
  1232. }
  1233. }
  1234. /**
  1235. * Returns the current region for the debug log.
  1236. */
  1237. function rules_debug_log_region() {
  1238. // If there is no setting for the current theme use the default theme setting.
  1239. global $theme_key;
  1240. $theme_default = variable_get('theme_default', 'bartik');
  1241. return variable_get('rules_debug_region_' . $theme_key, variable_get('rules_debug_region_' . $theme_default, 'help'));
  1242. }
  1243. /**
  1244. * Implements hook_page_build() to add the rules debug log to the page bottom.
  1245. */
  1246. function rules_page_build(&$page) {
  1247. // Invoke a the page redirect, in case the action has been executed.
  1248. // @see rules_action_drupal_goto()
  1249. if (isset($GLOBALS['_rules_action_drupal_goto_do'])) {
  1250. list($url, $force) = $GLOBALS['_rules_action_drupal_goto_do'];
  1251. drupal_goto($url);
  1252. }
  1253. if (isset($_SESSION['rules_debug'])) {
  1254. $region = rules_debug_log_region();
  1255. foreach ($_SESSION['rules_debug'] as $log) {
  1256. $page[$region]['rules_debug'][] = array(
  1257. '#markup' => $log,
  1258. );
  1259. $page[$region]['rules_debug']['#theme_wrappers'] = array('rules_log');
  1260. }
  1261. unset($_SESSION['rules_debug']);
  1262. }
  1263. if (rules_show_debug_output()) {
  1264. $region = rules_debug_log_region();
  1265. $page[$region]['rules_debug']['#pre_render'] = array('rules_debug_log_pre_render');
  1266. }
  1267. }
  1268. /**
  1269. * Pre-render callback for the debug log, which renders and then clears it.
  1270. */
  1271. function rules_debug_log_pre_render($elements) {
  1272. $logger = RulesLog::logger();
  1273. if ($log = $logger->render()) {
  1274. $logger = RulesLog::logger();
  1275. $logger->clear();
  1276. $elements[] = array('#markup' => $log);
  1277. $elements['#theme_wrappers'] = array('rules_log');
  1278. // Log the rules log to the system log if enabled.
  1279. if (variable_get('rules_debug_log', FALSE)) {
  1280. watchdog('rules', 'Rules debug information: !log', array('!log' => $log), WATCHDOG_NOTICE);
  1281. }
  1282. }
  1283. return $elements;
  1284. }
  1285. /**
  1286. * Implements hook_drupal_goto_alter().
  1287. *
  1288. * @see rules_action_drupal_goto()
  1289. */
  1290. function rules_drupal_goto_alter(&$path, &$options, &$http_response_code) {
  1291. // Invoke a the page redirect, in case the action has been executed.
  1292. if (isset($GLOBALS['_rules_action_drupal_goto_do'])) {
  1293. list($url, $force) = $GLOBALS['_rules_action_drupal_goto_do'];
  1294. if ($force || !isset($_GET['destination'])) {
  1295. $url = drupal_parse_url($url);
  1296. $path = $url['path'];
  1297. $options['query'] = $url['query'];
  1298. $options['fragment'] = $url['fragment'];
  1299. $http_response_code = 302;
  1300. }
  1301. }
  1302. }
  1303. /**
  1304. * Returns whether the debug log should be shown.
  1305. */
  1306. function rules_show_debug_output() {
  1307. if (variable_get('rules_debug', FALSE) == RulesLog::INFO && user_access('access rules debug')) {
  1308. return TRUE;
  1309. }
  1310. // For performance avoid unnecessary auto-loading of the RulesLog class.
  1311. return variable_get('rules_debug', FALSE) == RulesLog::WARN && user_access('access rules debug') && class_exists('RulesLog', FALSE) && RulesLog::logger()->hasErrors();
  1312. }
  1313. /**
  1314. * Implements hook_exit().
  1315. */
  1316. function rules_exit() {
  1317. // Bail out if this is cached request and modules are not loaded.
  1318. if (!module_exists('rules') || !module_exists('user')) {
  1319. return;
  1320. }
  1321. if (rules_show_debug_output()) {
  1322. if ($log = RulesLog::logger()->render()) {
  1323. // Keep the log in the session so we can show it on the next page.
  1324. $_SESSION['rules_debug'][] = $log;
  1325. }
  1326. }
  1327. // Log the rules log to the system log if enabled.
  1328. if (variable_get('rules_debug_log', FALSE) && $log = RulesLog::logger()->render()) {
  1329. watchdog('rules', 'Rules debug information: !log', array('!log' => $log), WATCHDOG_NOTICE);
  1330. }
  1331. }
  1332. /**
  1333. * Implements hook_element_info().
  1334. */
  1335. function rules_element_info() {
  1336. // A duration form element for rules. Needs ui.forms.inc included.
  1337. $types['rules_duration'] = array(
  1338. '#input' => TRUE,
  1339. '#tree' => TRUE,
  1340. '#default_value' => 0,
  1341. '#value_callback' => 'rules_ui_element_duration_value',
  1342. '#process' => array('rules_ui_element_duration_process', 'ajax_process_form'),
  1343. '#after_build' => array('rules_ui_element_duration_after_build'),
  1344. '#pre_render' => array('form_pre_render_conditional_form_element'),
  1345. );
  1346. $types['rules_data_selection'] = array(
  1347. '#input' => TRUE,
  1348. '#pre_render' => array('form_pre_render_conditional_form_element'),
  1349. '#process' => array('rules_data_selection_process', 'ajax_process_form'),
  1350. '#theme' => 'rules_autocomplete',
  1351. );
  1352. return $types;
  1353. }
  1354. /**
  1355. * Implements hook_modules_enabled().
  1356. */
  1357. function rules_modules_enabled($modules) {
  1358. // Re-enable Rules configurations that are dirty, because they require one of
  1359. // the enabled the modules.
  1360. $query = db_select('rules_dependencies', 'rd');
  1361. $query->join('rules_config', 'rc', 'rd.id = rc.id');
  1362. $query->fields('rd', array('id'))
  1363. ->condition('rd.module', $modules, 'IN')
  1364. ->condition('rc.dirty', 1);
  1365. $ids = $query->execute()->fetchCol();
  1366. // If there are some configurations that might work again, re-check all dirty
  1367. // configurations as others might work again too, e.g. consider a rule that is
  1368. // dirty because it requires a dirty component.
  1369. if ($ids) {
  1370. $rules_configs = rules_config_load_multiple(FALSE, array('dirty' => 1));
  1371. foreach ($rules_configs as $rules_config) {
  1372. try {
  1373. $rules_config->integrityCheck();
  1374. // If no exceptions were thrown we can set the configuration back to OK.
  1375. db_update('rules_config')
  1376. ->fields(array('dirty' => 0))
  1377. ->condition('id', $rules_config->id)
  1378. ->execute();
  1379. if ($rules_config->active) {
  1380. drupal_set_message(t('All dependencies for the Rules configuration %config are met again, so it has been re-activated.', array('%config' => $rules_config->label())));
  1381. }
  1382. }
  1383. catch (RulesIntegrityException $e) {
  1384. // The rule is still dirty, so do nothing.
  1385. }
  1386. }
  1387. }
  1388. rules_clear_cache();
  1389. }
  1390. /**
  1391. * Implements hook_modules_disabled().
  1392. */
  1393. function rules_modules_disabled($modules) {
  1394. // Disable Rules configurations that depend on one of the disabled modules.
  1395. $query = db_select('rules_dependencies', 'rd');
  1396. $query->join('rules_config', 'rc', 'rd.id = rc.id');
  1397. $query->fields('rd', array('id'))
  1398. ->distinct()
  1399. ->condition('rd.module', $modules, 'IN')
  1400. ->condition('rc.dirty', 0);
  1401. $ids = $query->execute()->fetchCol();
  1402. if (!empty($ids)) {
  1403. db_update('rules_config')
  1404. ->fields(array('dirty' => 1))
  1405. ->condition('id', $ids, 'IN')
  1406. ->execute();
  1407. // Tell the user about enabled rules that have been marked as dirty.
  1408. $count = db_select('rules_config', 'r')
  1409. ->fields('r')
  1410. ->condition('id', $ids, 'IN')
  1411. ->condition('active', 1)
  1412. ->execute()->rowCount();
  1413. if ($count > 0) {
  1414. $message = format_plural($count,
  1415. '1 Rules configuration requires some of the disabled modules to function and cannot be executed any more.',
  1416. '@count Rules configuration require some of the disabled modules to function and cannot be executed any more.'
  1417. );
  1418. drupal_set_message($message, 'warning');
  1419. }
  1420. }
  1421. rules_clear_cache();
  1422. }
  1423. /**
  1424. * Access callback for dealing with Rules configurations.
  1425. *
  1426. * @see entity_access()
  1427. */
  1428. function rules_config_access($op, $rules_config = NULL, $account = NULL) {
  1429. if (user_access('bypass rules access', $account)) {
  1430. return TRUE;
  1431. }
  1432. // Allow modules to grant / deny access.
  1433. $access = module_invoke_all('rules_config_access', $op, $rules_config, $account);
  1434. // Only grant access if at least one module granted access and no one denied
  1435. // access.
  1436. if (in_array(FALSE, $access, TRUE)) {
  1437. return FALSE;
  1438. }
  1439. elseif (in_array(TRUE, $access, TRUE)) {
  1440. return TRUE;
  1441. }
  1442. return FALSE;
  1443. }
  1444. /**
  1445. * Implements hook_rules_config_access().
  1446. */
  1447. function rules_rules_config_access($op, $rules_config = NULL, $account = NULL) {
  1448. // Instead of returning FALSE return nothing, so others still can grant
  1449. // access.
  1450. if (!isset($rules_config) || (isset($account) && $account->uid != $GLOBALS['user']->uid)) {
  1451. return;
  1452. }
  1453. if (user_access('administer rules', $account) && ($op == 'view' || $rules_config->access())) {
  1454. return TRUE;
  1455. }
  1456. }
  1457. /**
  1458. * Implements hook_menu().
  1459. */
  1460. function rules_menu() {
  1461. $items['admin/config/workflow/rules/upgrade'] = array(
  1462. 'title' => 'Upgrade',
  1463. 'page callback' => 'drupal_get_form',
  1464. 'page arguments' => array('rules_upgrade_form'),
  1465. 'access arguments' => array('administer rules'),
  1466. 'file' => 'includes/rules.upgrade.inc',
  1467. 'file path' => drupal_get_path('module', 'rules'),
  1468. 'type' => MENU_CALLBACK,
  1469. );
  1470. $items['admin/config/workflow/rules/upgrade/clear'] = array(
  1471. 'title' => 'Clear',
  1472. 'page callback' => 'drupal_get_form',
  1473. 'page arguments' => array('rules_upgrade_confirm_clear_form'),
  1474. 'access arguments' => array('administer rules'),
  1475. 'file' => 'includes/rules.upgrade.inc',
  1476. 'file path' => drupal_get_path('module', 'rules'),
  1477. 'type' => MENU_CALLBACK,
  1478. );
  1479. $items['admin/config/workflow/rules/autocomplete_tags'] = array(
  1480. 'title' => 'Rules tags autocomplete',
  1481. 'page callback' => 'rules_autocomplete_tags',
  1482. 'page arguments' => array(5),
  1483. 'access arguments' => array('administer rules'),
  1484. 'file' => 'ui/ui.forms.inc',
  1485. 'type' => MENU_CALLBACK,
  1486. );
  1487. return $items;
  1488. }
  1489. /**
  1490. * Helper function to keep track of external documentation pages for Rules.
  1491. *
  1492. * @param $topic
  1493. * The topic key for used for identifying help pages.
  1494. *
  1495. * @return
  1496. * Either a URL for the given page, or the full list of external help pages.
  1497. */
  1498. function rules_external_help($topic = NULL) {
  1499. $help = array(
  1500. 'rules' => 'http://drupal.org/node/298480',
  1501. 'terminology' => 'http://drupal.org/node/1299990',
  1502. 'condition-components' => 'http://drupal.org/node/1300034',
  1503. 'data-selection' => 'http://drupal.org/node/1300042',
  1504. 'chained-tokens' => 'http://drupal.org/node/1300042',
  1505. 'loops' => 'http://drupal.org/node/1300058',
  1506. 'components' => 'http://drupal.org/node/1300024',
  1507. 'component-types' => 'http://drupal.org/node/1300024',
  1508. 'variables' => 'http://drupal.org/node/1300024',
  1509. 'scheduler' => 'http://drupal.org/node/1300068',
  1510. 'coding' => 'http://drupal.org/node/878720',
  1511. );
  1512. if (isset($topic)) {
  1513. return isset($help[$topic]) ? $help[$topic] : FALSE;
  1514. }
  1515. return $help;
  1516. }
  1517. /**
  1518. * Implements hook_help().
  1519. */
  1520. function rules_help($path, $arg) {
  1521. // Only enable the help if the admin module is active.
  1522. if ($path == 'admin/help#rules' && module_exists('rules_admin')) {
  1523. $output['header'] = array(
  1524. '#markup' => t('Rules documentation is kept online. Please use the links below for more information about Rules. Feel free to contribute to improving the online documentation!'),
  1525. );
  1526. // Build a list of essential Rules help pages, formatted as a bullet list.
  1527. $link_list['rules'] = l(t('Rules introduction'), rules_external_help('rules'));
  1528. $link_list['terminology'] = l(t('Rules terminology'), rules_external_help('terminology'));
  1529. $link_list['scheduler'] = l(t('Rules Scheduler'), rules_external_help('scheduler'));
  1530. $link_list['coding'] = l(t('Coding for Rules'), rules_external_help('coding'));
  1531. $output['topic-list'] = array(
  1532. '#markup' => theme('item_list', array('items' => $link_list)),
  1533. );
  1534. return render($output);
  1535. }
  1536. }
  1537. /**
  1538. * Implements hook_token_info().
  1539. */
  1540. function rules_token_info() {
  1541. $cache = rules_get_cache();
  1542. $data_info = $cache['data_info'];
  1543. $types = array('text', 'integer', 'uri', 'token', 'decimal', 'date', 'duration');
  1544. foreach ($types as $type) {
  1545. $token_type = $data_info[$type]['token type'];
  1546. $token_info['types'][$token_type] = array(
  1547. 'name' => $data_info[$type]['label'],
  1548. 'description' => t('Tokens related to %label Rules variables.', array('%label' => $data_info[$type]['label'])),
  1549. 'needs-data' => $token_type,
  1550. );
  1551. $token_info['tokens'][$token_type]['value'] = array(
  1552. 'name' => t("Value"),
  1553. 'description' => t('The value of the variable.'),
  1554. );
  1555. }
  1556. return $token_info;
  1557. }
  1558. /**
  1559. * Implements hook_tokens().
  1560. */
  1561. function rules_tokens($type, $tokens, $data, $options = array()) {
  1562. // Handle replacements of primitive variable types.
  1563. if (substr($type, 0, 6) == 'rules_' && !empty($data[$type])) {
  1564. // Leverage entity tokens token processor by passing on as struct.
  1565. $info['property info']['value'] = array(
  1566. 'type' => substr($type, 6),
  1567. 'label' => '',
  1568. );
  1569. // Entity tokens uses metadata wrappers as values for 'struct' types.
  1570. $wrapper = entity_metadata_wrapper('struct', array('value' => $data[$type]), $info);
  1571. return entity_token_tokens('struct', $tokens, array('struct' => $wrapper), $options);
  1572. }
  1573. }
  1574. /**
  1575. * Helper function that retrieves a metadata wrapper with all properties.
  1576. *
  1577. * Note that without this helper, bundle-specific properties aren't added.
  1578. */
  1579. function rules_get_entity_metadata_wrapper_all_properties(RulesAbstractPlugin $element) {
  1580. return entity_metadata_wrapper($element->settings['type'], NULL, array(
  1581. 'property info alter' => 'rules_entity_metadata_wrapper_all_properties_callback',
  1582. ));
  1583. }
  1584. /**
  1585. * Callback that returns a metadata wrapper with all properties.
  1586. */
  1587. function rules_entity_metadata_wrapper_all_properties_callback(EntityMetadataWrapper $wrapper, $property_info) {
  1588. $info = $wrapper->info();
  1589. $properties = entity_get_all_property_info($info['type']);
  1590. $property_info['properties'] += $properties;
  1591. return $property_info;
  1592. }
  1593. /**
  1594. * Helper to enable or disable the invocation of rules events.
  1595. *
  1596. * Rules invocation is disabled by default, such that Rules does not operate
  1597. * when Drupal is not fully bootstrapped. It gets enabled in rules_init() and
  1598. * rules_enable().
  1599. *
  1600. * @param bool|NULL $enable
  1601. * NULL to leave the setting as is and TRUE / FALSE to change the behaviour.
  1602. *
  1603. * @return bool
  1604. * Whether the rules invocation is enabled or disabled.
  1605. */
  1606. function rules_event_invocation_enabled($enable = NULL) {
  1607. static $invocation_enabled = FALSE;
  1608. if (isset($enable)) {
  1609. $invocation_enabled = (bool) $enable;
  1610. }
  1611. // Disable invocation if configured or if site runs in maintenance mode.
  1612. return $invocation_enabled && !defined('MAINTENANCE_MODE');
  1613. }