rules.module 46 KB

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