rules.module 56 KB

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