You are here

function privatemsg_service_send in Privatemsg 6.2

Send a private message to one or more recipients.

Parameters

$recipients: String. A comma separated list of usernames for recipients of the message.

$subject: String. A message subject

$body: String. A message body

Return value

Boolean. Return TRUE if sending the message was successful.

1 string reference to 'privatemsg_service_send'
privatemsg_service_service in privatemsg_service/privatemsg_service.module
Implementation of hook_service().

File

privatemsg_service/privatemsg_service.inc, line 159
Link general private message module functionalities to services module.

Code

function privatemsg_service_send($recipients, $subject, $body = '') {

  // Make sure the message author is logged in.
  if (!user_is_logged_in()) {
    return services_error(t('Author is not logged in.'), 403);
  }

  // Validate at least 1 recipient has been passed in.
  if ($recipients == '') {
    return services_error(t('There are no recipients, please enter a recipient for the message.'), 400);
  }

  // Validate that this messages has a subject.
  if ($subject == '') {
    return services_error(t('Please specify a subject line.'), 400);
  }

  // Load the full user object.
  global $user;
  $account = user_load($user->uid);

  // Convert the recipients string to an array of user objects.
  list($recipients, $invalid, $duplicates, $denieds) = _privatemsg_parse_userstring($recipients);

  // Problem: At least one of the recipients could not be found.
  if (!empty($invalid)) {
    $invalid_usernames = array(
      '@names' => implode(', ', $invalid),
    );
    return services_error(t('One or more recipients are invalid: @names', $invalid_usernames), 400);
  }

  // Problem: At least one of the recipients could not be found.
  if (!empty($duplicates)) {
    $duplicate_usernames = array(
      '@names' => implode(', ', $duplicates),
    );
    return services_error(t('One or more recipients are not unique: @names', $duplicate_usernames), 400);
  }

  // Problem: At least one of the recipients could not be found.
  if (!empty($denieds)) {
    $denied_usernames = array(
      '@names' => implode(', ', $denied_usernames),
    );
    return services_error(t('Not allowed to write to the following recipients: @names', $denied_usernames), 400);
  }

  // Attempt to send a new message.
  $result = privatemsg_new_thread($recipients, $subject, $body, array(
    'author' => $account,
  ));

  // Return success status.
  if ($result['success']) {
    return TRUE;
  }
  else {
    return services_error(implode("\n", $result['messages']['error']), 400);
  }
}