system.eval.inc 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. <?php
  2. /**
  3. * @file
  4. * Contains rules integration for the system module needed during evaluation.
  5. *
  6. * @addtogroup rules
  7. * @{
  8. */
  9. /**
  10. * Action: Show a drupal message.
  11. */
  12. function rules_action_drupal_message($message, $status, $repeat) {
  13. drupal_set_message(filter_xss_admin($message), $status, $repeat);
  14. }
  15. /**
  16. * Action: Page redirect.
  17. *
  18. * @see rules_page_build()
  19. * @see rules_drupal_goto_alter()
  20. */
  21. function rules_action_drupal_goto($url, $force = FALSE, $destination = FALSE) {
  22. // Don't let administrators lock them out from Rules administration pages.
  23. if (isset($_GET['q']) && strpos($_GET['q'], 'admin/config/workflow/rules') === 0) {
  24. rules_log('Skipped page redirect on Rules administration page.', array(), RulesLog::WARN);
  25. return;
  26. }
  27. // Do not redirect during batch processing.
  28. if (($batch = batch_get()) && isset($batch['current_set'])) {
  29. rules_log('Skipped page redirect during batch processing.');
  30. return;
  31. }
  32. // Keep the current destination parameter if there is one set.
  33. if ($destination) {
  34. $url .= strpos($url, '?') === FALSE ? '?' : '&';
  35. $url .= drupal_http_build_query(drupal_get_destination());
  36. }
  37. // If force is enabled, remove any destination parameter.
  38. if ($force && isset($_GET['destination'])) {
  39. unset($_GET['destination']);
  40. }
  41. // We don't invoke drupal_goto() right now, as this would end the the current
  42. // page execution unpredictly for modules. So we'll take over drupal_goto()
  43. // calls from somewhere else via hook_drupal_goto_alter() and make sure
  44. // a drupal_goto() is invoked before the page is output with
  45. // rules_page_build().
  46. $GLOBALS['_rules_action_drupal_goto_do'] = array($url, $force);
  47. }
  48. /**
  49. * Action: Set breadcrumb.
  50. */
  51. function rules_action_breadcrumb_set(array $titles, array $paths) {
  52. $trail = array(l(t('Home'), ''));
  53. foreach ($titles as $i => $title) {
  54. // Skip empty titles.
  55. if ($title = trim($title)) {
  56. // Output plaintext instead of a link if there is a title
  57. // without a path.
  58. $path = trim($paths[$i]);
  59. if (!empty($paths[$i]) && $paths[$i] != '<none>') {
  60. $trail[] = l($title, trim($paths[$i]));
  61. }
  62. else {
  63. $trail[] = check_plain($title);
  64. }
  65. }
  66. }
  67. drupal_set_breadcrumb($trail);
  68. }
  69. /**
  70. * Action Implementation: Send mail.
  71. */
  72. function rules_action_mail($to, $subject, $message, $from = NULL, $langcode, $settings, RulesState $state, RulesPlugin $element) {
  73. $to = str_replace(array("\r", "\n"), '', $to);
  74. $from = !empty($from) ? str_replace(array("\r", "\n"), '', $from) : NULL;
  75. $params = array(
  76. 'subject' => $subject,
  77. 'message' => $message,
  78. 'langcode' => $langcode,
  79. );
  80. // Set a unique key for this mail.
  81. $name = isset($element->root()->name) ? $element->root()->name : 'unnamed';
  82. $key = 'rules_action_mail_' . $name . '_' . $element->elementId();
  83. $languages = language_list();
  84. $language = isset($languages[$langcode]) ? $languages[$langcode] : language_default();
  85. $message = drupal_mail('rules', $key, $to, $language, $params, $from);
  86. if ($message['result']) {
  87. watchdog('rules', 'Successfully sent email to %recipient', array('%recipient' => $to));
  88. }
  89. }
  90. /**
  91. * Action: Send mail to all users of a specific role group(s).
  92. */
  93. function rules_action_mail_to_users_of_role($roles, $subject, $message, $from = NULL, $settings, RulesState $state, RulesPlugin $element) {
  94. $from = !empty($from) ? str_replace(array("\r", "\n"), '', $from) : NULL;
  95. // All authenticated users, which is everybody.
  96. if (in_array(DRUPAL_AUTHENTICATED_RID, $roles)) {
  97. $result = db_query('SELECT mail FROM {users} WHERE uid > 0');
  98. }
  99. else {
  100. $rids = implode(',', $roles);
  101. // Avoid sending emails to members of two or more target role groups.
  102. $result = db_query('SELECT DISTINCT u.mail FROM {users} u INNER JOIN {users_roles} r ON u.uid = r.uid WHERE r.rid IN ('. $rids .')');
  103. }
  104. // Now, actually send the mails.
  105. $params = array(
  106. 'subject' => $subject,
  107. 'message' => $message,
  108. );
  109. // Set a unique key for this mail.
  110. $name = isset($element->root()->name) ? $element->root()->name : 'unnamed';
  111. $key = 'rules_action_mail_to_users_of_role_' . $name . '_' . $element->elementId(); $languages = language_list();
  112. $message = array('result' => TRUE);
  113. foreach ($result as $row) {
  114. $message = drupal_mail('rules', $key, $row->mail, language_default(), $params, $from);
  115. // If $message['result'] is FALSE, then it's likely that email sending is
  116. // failing at the moment, and we should just abort sending any more. If
  117. // however, $mesage['result'] is NULL, then it's likely that a module has
  118. // aborted sending this particular email to this particular user, and we
  119. // should just keep on sending emails to the other users.
  120. // For more information on the result value, see drupal_mail().
  121. if ($message['result'] === FALSE) {
  122. break;
  123. }
  124. }
  125. if ($message['result'] !== FALSE) {
  126. $role_names = array_intersect_key(user_roles(TRUE), array_flip($roles));
  127. watchdog('rules', 'Successfully sent email to the role(s) %roles.', array('%roles' => implode(', ', $role_names)));
  128. }
  129. }
  130. /**
  131. * Implements hook_mail().
  132. *
  133. * Set's the message subject and body as configured.
  134. */
  135. function rules_mail($key, &$message, $params) {
  136. $message['subject'] .= str_replace(array("\r", "\n"), '', $params['subject']);
  137. $message['body'][] = $params['message'];
  138. }
  139. /**
  140. * Action: Block an IP address.
  141. */
  142. function rules_action_block_ip($ip_address = NULL) {
  143. if (empty($ip_address)) {
  144. $ip_address = ip_address();
  145. }
  146. db_insert('blocked_ips')->fields(array('ip' => $ip_address))->execute();
  147. watchdog('rules', 'Banned IP address %ip', array('%ip' => $ip_address));
  148. }
  149. /**
  150. * A class implementing a rules input evaluator processing tokens.
  151. */
  152. class RulesTokenEvaluator extends RulesDataInputEvaluator {
  153. public function prepare($text, $var_info) {
  154. $text = is_array($text) ? implode('', $text) : $text;
  155. // Skip this evaluator if there are no tokens.
  156. $this->setting = token_scan($text) ? TRUE : NULL;
  157. }
  158. /**
  159. * We replace the tokens on our own as we cannot use token_replace(), because
  160. * token usually assumes that $data['node'] is a of type node, which doesn't
  161. * hold in general in our case.
  162. * So we properly map variable names to variable data types and then run the
  163. * replacement ourself.
  164. */
  165. public function evaluate($text, $options, RulesState $state) {
  166. $var_info = $state->varInfo();
  167. $options += array('sanitize' => FALSE);
  168. $replacements = array();
  169. $data = array();
  170. // We also support replacing tokens in a list of textual values.
  171. $whole_text = is_array($text) ? implode('', $text) : $text;
  172. foreach (token_scan($whole_text) as $var_name => $tokens) {
  173. $var_name = str_replace('-', '_', $var_name);
  174. if (isset($var_info[$var_name]) && ($token_type = _rules_system_token_map_type($var_info[$var_name]['type']))) {
  175. // We have to key $data with the type token uses for the variable.
  176. $data = rules_unwrap_data(array($token_type => $state->get($var_name)), array($token_type => $var_info[$var_name]));
  177. $replacements += token_generate($token_type, $tokens, $data, $options);
  178. }
  179. else {
  180. $replacements += token_generate($var_name, $tokens, array(), $options);
  181. }
  182. // Remove tokens if no replacement value is found. As token_replace() does
  183. // if 'clear' is set.
  184. $replacements += array_fill_keys($tokens, '');
  185. }
  186. // Optionally clean the list of replacement values.
  187. if (!empty($options['callback']) && function_exists($options['callback'])) {
  188. $function = $options['callback'];
  189. $function($replacements, $data, $options);
  190. }
  191. // Actually apply the replacements.
  192. $tokens = array_keys($replacements);
  193. $values = array_values($replacements);
  194. if (is_array($text)) {
  195. foreach ($text as $i => $text_item) {
  196. $text[$i] = str_replace($tokens, $values, $text_item);
  197. }
  198. return $text;
  199. }
  200. return str_replace($tokens, $values, $text);
  201. }
  202. /**
  203. * Create documentation about the available replacement patterns.
  204. *
  205. * @param array $var_info
  206. * Array with the available variables.
  207. *
  208. * @return array
  209. * Renderable array with the replacement pattern documentation.
  210. */
  211. public static function help($var_info) {
  212. $render = array(
  213. '#type' => 'fieldset',
  214. '#title' => t('Replacement patterns'),
  215. '#collapsible' => TRUE,
  216. '#collapsed' => TRUE,
  217. '#description' => t('Note that token replacements containing chained objects – such as [node:author:uid] – are not listed here, but are still available. The <em>data selection</em> input mode may help you find more complex replacement patterns. See <a href="@url">the online documentation</a> for more information about complex replacement patterns.',
  218. array('@url' => rules_external_help('chained-tokens'))),
  219. );
  220. $token_info = token_info();
  221. foreach ($var_info as $name => $info) {
  222. $token_types[$name] = _rules_system_token_map_type($info['type']);
  223. }
  224. foreach ($token_types as $name => $token_type) {
  225. if (isset($token_info['types'][$token_type])) {
  226. $render[$name] = array(
  227. '#theme' => 'table',
  228. '#header' => array(t('Token'), t('Label'), t('Description')),
  229. '#prefix' => '<h3>' . t('Replacement patterns for %label', array('%label' => $var_info[$name]['label'])) . '</h3>',
  230. );
  231. foreach ($token_info['tokens'][$token_type] as $token => $info) {
  232. $token = '[' . str_replace('_', '-', $name) . ':' . $token . ']';
  233. $render[$name]['#rows'][$token] = array(
  234. check_plain($token),
  235. check_plain($info['name']),
  236. check_plain($info['description']),
  237. );
  238. }
  239. }
  240. }
  241. return $render;
  242. }
  243. }
  244. /**
  245. * Looks for a token type mapping. Defaults to passing through the type.
  246. */
  247. function _rules_system_token_map_type($type) {
  248. $entity_info = entity_get_info();
  249. if (isset($entity_info[$type]['token type'])) {
  250. return $entity_info[$type]['token type'];
  251. }
  252. $cache = rules_get_cache();
  253. if (isset($cache['data_info'][$type]['token type'])) {
  254. return $cache['data_info'][$type]['token type'];
  255. }
  256. return $type;
  257. }
  258. /**
  259. * @}
  260. */