rules.module 54 KB

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