You are here

function rules_action_mail_to_users_of_role in Rules 6

Same name and namespace in other branches
  1. 7.2 modules/system.eval.inc \rules_action_mail_to_users_of_role()

Action: Send mail to all users of a specific role group(s).

Related topics

File

rules/modules/system.rules.inc, line 142
rules integration for the system module

Code

function rules_action_mail_to_users_of_role($settings) {
  $recipients = $settings['recipients'];
  $from = $settings['from'] ? str_replace(array(
    "\r",
    "\n",
  ), '', $settings['from']) : NULL;

  // All authenticated users, which is everybody.
  if (in_array(DRUPAL_AUTHENTICATED_RID, $recipients)) {
    $result = db_query('SELECT mail FROM {users} WHERE uid > 0');
  }
  else {
    $rids = implode(',', $recipients);

    // Avoid sending emails to members of two or more target role groups.
    $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 . ')');
  }

  // Now, actually send the mails.
  $message = array(
    'result' => TRUE,
  );
  while (($account = db_fetch_object($result)) && $message['result']) {
    $message = drupal_mail('rules', 'rules_action_role_mail', $account->mail, language_default(), $settings, $from);
  }
  if ($message['result']) {
    $roles = array_intersect_key(user_roles(TRUE), drupal_map_assoc($recipients));
    watchdog('rules', 'Successfully sent email to the role(s) %roles.', array(
      '%roles' => implode(', ', $roles),
    ));
  }
}