You are here

function privatemsg_rules_new in Privatemsg 7

Same name and namespace in other branches
  1. 6.2 privatemsg_rules/privatemsg_rules.rules.inc \privatemsg_rules_new()
  2. 7.2 privatemsg_rules/privatemsg_rules.rules.inc \privatemsg_rules_new()

Helper function for sending a new message.

File

privatemsg_rules/privatemsg_rules.rules.inc, line 207
Hooks and callback functions for rules.module integration.

Code

function privatemsg_rules_new($args, $element) {

  // Recipient could be a wrapped entity. They do not play nice
  // together with the Privatemsg API because that one assumes recipient
  // objects which have additional properties like type.
  $recipient = $args['recipient'];
  if ($recipient instanceof EntityDrupalWrapper) {
    $recipient = user_load($recipient
      ->getIdentifier());
  }

  // Enforce recipient type values.
  $recipient->recipient = $recipient->uid;
  $recipient->type = 'user';

  // Replace token placeholders.
  $args['subject'] = privatemsg_rules_replace_tokens($args['subject']);
  $args['body'] = privatemsg_rules_replace_tokens($args['body']);
  rules_log('Writing new message with subject %subject to %user from %author', array(
    '%subject' => $args['subject'],
    '%user' => $recipient->name,
    '%author' => $args['author']->name,
  ));
  $result = privatemsg_new_thread(array(
    $recipient,
  ), $args['subject'], $args['body'], $args);
  if ($result['success']) {
    rules_log('New message sucessfully sent, !link', array(
      '!link' => l($args['subject'], 'messages/view/' . $result['message']->thread_id),
    ));
  }
  else {
    foreach ($result['messages']['error'] as $args) {
      rules_log('Message not sent, reported error: !error', array(
        '!error' => $args,
      ), RulesLog::ERROR);
    }
  }
  foreach ($result['messages']['warning'] as $args) {
    rules_log('Warning message reported when trying to send message: !warning', array(
      '!warning' => $args,
    ), RulesLog::WARN);
  }

  // Return thread ID of new thread (or NULL if failed).
  if ($result['success']) {
    return array(
      'thread_id' => $result['message']->thread_id,
    );
  }
  else {
    return array(
      'thread_id' => NULL,
    );
  }
}