system.eval.inc 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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']) {
  116. break;
  117. }
  118. }
  119. if ($message['result']) {
  120. $role_names = array_intersect_key(user_roles(TRUE), array_flip($roles));
  121. watchdog('rules', 'Successfully sent email to the role(s) %roles.', array('%roles' => implode(', ', $role_names)));
  122. }
  123. }
  124. /**
  125. * Implements hook_mail().
  126. *
  127. * Set's the message subject and body as configured.
  128. */
  129. function rules_mail($key, &$message, $params) {
  130. $message['subject'] .= str_replace(array("\r", "\n"), '', $params['subject']);
  131. $message['body'][] = $params['message'];
  132. }
  133. /**
  134. * A class implementing a rules input evaluator processing tokens.
  135. */
  136. class RulesTokenEvaluator extends RulesDataInputEvaluator {
  137. public function prepare($text, $var_info) {
  138. $text = is_array($text) ? implode('', $text) : $text;
  139. // Skip this evaluator if there are no tokens.
  140. $this->setting = token_scan($text) ? TRUE : NULL;
  141. }
  142. /**
  143. * We replace the tokens on our own as we cannot use token_replace(), because
  144. * token usually assumes that $data['node'] is a of type node, which doesn't
  145. * hold in general in our case.
  146. * So we properly map variable names to variable data types and then run the
  147. * replacement ourself.
  148. */
  149. public function evaluate($text, $options, RulesState $state) {
  150. $var_info = $state->varInfo();
  151. $options += array('sanitize' => FALSE);
  152. $replacements = array();
  153. $data = array();
  154. // We also support replacing tokens in a list of textual values.
  155. $whole_text = is_array($text) ? implode('', $text) : $text;
  156. foreach (token_scan($whole_text) as $var_name => $tokens) {
  157. $var_name = str_replace('-', '_', $var_name);
  158. if (isset($var_info[$var_name]) && ($token_type = _rules_system_token_map_type($var_info[$var_name]['type']))) {
  159. // We have to key $data with the type token uses for the variable.
  160. $data = rules_unwrap_data(array($token_type => $state->get($var_name)), array($token_type => $var_info[$var_name]));
  161. $replacements += token_generate($token_type, $tokens, $data, $options);
  162. }
  163. else {
  164. $replacements += token_generate($var_name, $tokens, array(), $options);
  165. }
  166. // Remove tokens if no replacement value is found. As token_replace() does
  167. // if 'clear' is set.
  168. $replacements += array_fill_keys($tokens, '');
  169. }
  170. // Optionally clean the list of replacement values.
  171. if (!empty($options['callback']) && function_exists($options['callback'])) {
  172. $function = $options['callback'];
  173. $function($replacements, $data, $options);
  174. }
  175. // Actually apply the replacements.
  176. $tokens = array_keys($replacements);
  177. $values = array_values($replacements);
  178. if (is_array($text)) {
  179. foreach ($text as $i => $text_item) {
  180. $text[$i] = str_replace($tokens, $values, $text_item);
  181. }
  182. return $text;
  183. }
  184. return str_replace($tokens, $values, $text);
  185. }
  186. /**
  187. * Create documentation about the available replacement patterns.
  188. *
  189. * @param array $var_info
  190. * Array with the available variables.
  191. *
  192. * @return array
  193. * Renderable array with the replacement pattern documentation.
  194. */
  195. public static function help($var_info) {
  196. $render = array(
  197. '#type' => 'fieldset',
  198. '#title' => t('Replacement patterns'),
  199. '#collapsible' => TRUE,
  200. '#collapsed' => TRUE,
  201. '#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.',
  202. array('@url' => rules_external_help('chained-tokens'))),
  203. );
  204. $token_info = token_info();
  205. foreach ($var_info as $name => $info) {
  206. $token_types[$name] = _rules_system_token_map_type($info['type']);
  207. }
  208. foreach ($token_types as $name => $token_type) {
  209. if (isset($token_info['types'][$token_type])) {
  210. $render[$name] = array(
  211. '#theme' => 'table',
  212. '#header' => array(t('Token'), t('Label'), t('Description')),
  213. '#prefix' => '<h3>' . t('Replacement patterns for %label', array('%label' => $var_info[$name]['label'])) . '</h3>',
  214. );
  215. foreach ($token_info['tokens'][$token_type] as $token => $info) {
  216. $token = '[' . str_replace('_', '-', $name) . ':' . $token . ']';
  217. $render[$name]['#rows'][$token] = array(
  218. check_plain($token),
  219. check_plain($info['name']),
  220. check_plain($info['description']),
  221. );
  222. }
  223. }
  224. }
  225. return $render;
  226. }
  227. }
  228. /**
  229. * Looks for a token type mapping. Defaults to passing through the type.
  230. */
  231. function _rules_system_token_map_type($type) {
  232. $entity_info = entity_get_info();
  233. if (isset($entity_info[$type]['token type'])) {
  234. return $entity_info[$type]['token type'];
  235. }
  236. $cache = rules_get_cache();
  237. if (isset($cache['data_info'][$type]['token type'])) {
  238. return $cache['data_info'][$type]['token type'];
  239. }
  240. return $type;
  241. }
  242. /**
  243. * @}
  244. */