? privatemsg_limits/translations
Index: privatemsg_limits/privatemsg_limits.admin.inc
===================================================================
RCS file: privatemsg_limits/privatemsg_limits.admin.inc
diff -N privatemsg_limits/privatemsg_limits.admin.inc
--- /dev/null	1 Jan 1970 00:00:00 -0000
+++ privatemsg_limits/privatemsg_limits.admin.inc	15 Aug 2010 12:55:45 -0000
@@ -0,0 +1,135 @@
+<?php
+// $Id$
+
+/**
+ * @file
+ * Admin menu callbacks for privatemsg_limits module.
+ */
+
+/**
+ * Menu callback for the admin configuration.
+ */
+function privatemsg_limits_admin(&$form_state) {
+  $default = array(
+    '#type'  => 'textfield',
+    '#size' => '10',
+  );
+
+  $form['general'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Generic settings'),
+  );
+  $form['general']['privatemsg_limits_object'] = array(
+    '#type'  => 'select',
+    '#title' => t('What should be limited'),
+    '#description' => t('Do you want to limit the number of individual messages a user can send, or limit the number of message threads a user can initiate? An exceeded thread limit will allow users to still write individual messages in existing threads, but not start new ones.'),
+    '#default_value' => variable_get('privatemsg_limits_object', 'message'),
+    '#options' => array('message' => t('Messages'), 'thread' => t('Threads')),
+  );
+  $form['general']['privatemsg_limits_messages_per_thread'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Number of messages in a thread'),
+    '#description' => t('When a thread reaches this number of messages, the specified action below will happen. 0 is unlimited. Hint: setting this to 1 will make this PrivateMsg module more like the old, single message interface.'),
+    '#default_value' => variable_get('privatemsg_limits_messages_per_thread', 0),
+    '#size' => '3',
+  );
+  $form['general']['privatemsg_limits_messages_per_thread_action'] = array(
+    '#type' => 'radios',
+    '#title' => t('Number of messages in a thread action'),
+    '#description' => t('This will happen when a thread has reached the maximum number of messages per-thread'),
+    '#default_value' => variable_get('privatemsg_limits_messages_per_thread_action', 'create-new'),
+    '#options' => array(
+      'create-new' => t('Create new thread'),
+      'block-message' => t('Block message from being sent')
+    ),
+  );
+
+  $form['receive'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Receive settings'),
+  );
+  $form['receive']['privatemsg_limits_receive_enabled'] = array(
+    '#type'  => 'checkbox',
+    '#title' => t('Limit number of messages a user can have.'),
+    '#default_value' => variable_get('privatemsg_limits_receive_enabled', FALSE),
+  );
+  $form['receive']['privatemsg_limits_receive_amount'] = array(
+    '#type'  => 'textfield',
+    '#title' => t('Number of allowed messages or threads'),
+    '#description' => t('How many messages/threads a users can receive before he has to delete old messages. When the limit is reached, users are not allowed to receive or send new messages/threads.'),
+    '#default_value' => variable_get('privatemsg_limits_receive_amount', 0),
+    '#size' => '10',
+  );
+  $form['receive'] += _privatemsg_qota_role_override_form('receive_amount', $default);
+
+  $form['send'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Send settings'),
+  );
+  $form['send']['privatemsg_limits_send_enabled'] = array(
+    '#type'  => 'checkbox',
+    '#title' => t('Limit how many messages/threads a user can send in a given time period'),
+    '#default_value' => variable_get('privatemsg_limits_send_enabled', FALSE),
+  );
+  $form['send']['privatemsg_limits_send_amount'] = array(
+    '#type'  => 'textfield',
+    '#title' => t('Number of allowed messages or threads'),
+    '#description' => t('Number of messages or new threads a user is allowed to send in a given time period.'),
+    '#default_value' => variable_get('privatemsg_limits_send_amount', 0),
+    '#size' => '10',
+  );
+  $form['send']['privatemsg_limits_send_timeframe'] = array(
+    '#type'  => 'select',
+    '#title' => t('Set the time period'),
+    '#description' => t('Users are not allowed to send more than the configured amound of messages/threads during the given period.'),
+    '#default_value' => variable_get('privatemsg_limits_send_timeframe', 3600),
+    '#options' => drupal_map_assoc(array(60, 300, 1800, 3600, 86400), 'format_interval'),
+  );
+  $form['send'] += _privatemsg_qota_role_override_form('send_amount', $default);
+
+  $form['recipients'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Recipient settings'),
+  );
+  $form['recipients']['privatemsg_limits_recipients_enabled'] = array(
+    '#type'  => 'checkbox',
+    '#title' => t('Limit how how many recipients a user can address in a single message'),
+    '#default_value' => variable_get('privatemsg_limits_recipients_enabled', FALSE),
+  );
+  $form['recipients']['privatemsg_limits_recipients_amount'] = array(
+    '#type'  => 'textfield',
+    '#title' => t('Number of recipients per message'),
+    '#description' => t('Defines how many recipients a user can address in a single message. Users are still able to reply to threads with more participants.'),
+    '#default_value' => variable_get('privatemsg_limits_recipients_amount', 0),
+    '#size' => '10',
+  );
+  $form['recipients'] += _privatemsg_qota_role_override_form('recipients_amount', $default);
+
+  return system_settings_form($form);
+}
+
+/**
+ * Provides a generic rules form to override the default values.
+ *
+ * @param string $name    Unique name for the value
+ * @param array  $default defaut form configuration
+ *
+ * @return array Form fieldset
+ */
+function _privatemsg_qota_role_override_form($name, $default) {
+  $form['roles'] = array(
+    '#type'   => 'fieldset',
+    '#description' => t('You can override the limits for each role. If a user has multiple roles, the highest value will be used. Use <em>unlimited</em>, if you do not want to limit a role.'),
+    '#title'  => t('Role-based limits'),
+    '#collapsible' => TRUE,
+    '#collapsed' => TRUE,
+  );
+
+  foreach (user_roles(TRUE) as $id => $role) {
+    $form['roles']["privatemsg_limits_{$name}_role_{$id}"] = $default + array(
+      '#title' => $role,
+      '#default_value' => variable_get("privatemsg_limits_{$name}_role_". $id, 0),
+    );
+  }
+  return $form;
+}
Index: privatemsg_limits/privatemsg_limits.info
===================================================================
RCS file: privatemsg_limits/privatemsg_limits.info
diff -N privatemsg_limits/privatemsg_limits.info
--- /dev/null	1 Jan 1970 00:00:00 -0000
+++ privatemsg_limits/privatemsg_limits.info	15 Aug 2010 12:55:45 -0000
@@ -0,0 +1,6 @@
+; $Id$
+name = Privatemsg Limits
+description = Allows to define limits for private messages including amount of sent messages per timeframe and number of recipients
+package = Mail
+core = 6.x
+dependencies[] = privatemsg
\ No newline at end of file
Index: privatemsg_limits/privatemsg_limits.module
===================================================================
RCS file: privatemsg_limits/privatemsg_limits.module
diff -N privatemsg_limits/privatemsg_limits.module
--- /dev/null	1 Jan 1970 00:00:00 -0000
+++ privatemsg_limits/privatemsg_limits.module	15 Aug 2010 12:55:45 -0000
@@ -0,0 +1,293 @@
+<?php
+// $Id$
+
+/**
+ * @file
+ * Privatemsg Quota module
+ */
+
+/**
+ * Implements hook_menu().
+ */
+function privatemsg_limits_menu() {
+  $items['admin/settings/messages/limits'] = array(
+    'title'            => 'Limits',
+    'description'      => 'Configure limits',
+    'page callback'    => 'drupal_get_form',
+    'page arguments'   => array('privatemsg_limits_admin'),
+    'file'             => 'privatemsg_limits.admin.inc',
+    'access arguments' => array('administer privatemsg settings'),
+    'type'             => MENU_LOCAL_TASK,
+  );
+  return $items;
+}
+
+/**
+ * Implements hook_privatemsg_message_validate().
+ */
+function privatemsg_limits_privatemsg_message_validate($message, $form = FALSE) {
+  $errors = array();
+
+  if (variable_get('privatemsg_limits_recipients_enabled', FALSE)) {
+    $amount = _privatemsg_limits_get_amount('recipients_amount', $message['author']);
+    if (!isset($message['thread_id']) && $amount > 0 && count($message['recipients']) > $amount) {
+      $errors[] = t("You are not allowed to send a message to more than @number recipients.", array('@number' => $amount));
+    }
+  }
+
+  // Only check sending limit if enabled and if this is either not a reply or
+  // messages should be checked and not threads. When the limit object are
+  // threads, users can send an unlimited amount of replies.
+  if (variable_get('privatemsg_limits_send_enabled', FALSE) && (empty($message['thread_id']) || variable_get('privatemsg_limits_object', 'message') == 'message')) {
+    $amount = _privatemsg_limits_get_amount('send_amount', $message['author']);
+    $used = _privatemsg_limits_get_sent($message['author'], variable_get('privatemsg_limits_send_timeframe', 3600));
+    if ($amount > 0 && $used >= $amount) {
+      $wait_time = _privatemsg_limits_get_oldest($message['author'], variable_get('privatemsg_limits_send_timeframe', 3600));
+
+      $errors[] = t("You have exceeded your message sending limit for now. You can send your next message in @wait_time.", array('@wait_time' => $wait_time));
+    }
+  }
+
+  if (variable_get('privatemsg_limits_receive_enabled', FALSE) && (empty($message['thread_id']) || variable_get('privatemsg_limits_object', 'message') == 'message')) {
+    $amount = _privatemsg_limits_get_amount('receive_amount', $message['author']);
+    $used = _privatemsg_limits_get_received($message['author']);
+    if ($amount > 0 && $used >= $amount) {
+      $errors[] = t("You have exceeded your message limit. You need to delete messages before you can send new ones.");
+    }
+  }
+
+  // Blocks message sending if over number of messages per-thread.
+  if (isset($message['thread_id']) && variable_get('privatemsg_limits_messages_per_thread', 0) > 0) {
+    // If we're not blocking the message.
+    if (variable_get('privatemsg_limits_messages_per_thread_action', 'create-new') == 'block-message') {
+      $query = "SELECT COUNT(*) FROM {pm_index} WHERE thread_id = %d AND recipient = %d AND type IN ('hidden', 'user')";
+      $result = db_result(db_query($query, $message['thread_id'], $message['author']->uid));
+
+      if ($result >= variable_get('privatemsg_limits_messages_per_thread', 0)) {
+        // If the number of messages per-thread has been exceeded, block message
+        // from being sent.
+        $errors[] = t('The message cannot be sent because the limit of messages per thread has been reached.');
+      }
+    }
+  }
+  if (!empty($errors)) {
+    if ($form) {
+      foreach ($errors as $error) {
+        form_set_error('recipient', $error);
+      }
+    }
+    else {
+      return array('error' => $errors);
+    }
+  }
+}
+
+/**
+ * Implements hook_privatemsg_block_message().
+ */
+function privatemsg_limits_privatemsg_block_message($author, $recipients, $context = array()) {
+  if (variable_get('privatemsg_limits_receive_enabled', FALSE) && (empty($context['thread_id']) || variable_get('privatemsg_limits_object', 'message') == 'message') ) {
+    $blocked = array();
+    foreach ($recipients as $recipient) {
+      // Only user recipients are supported.
+      if ($recipient->type == 'user') {
+        $amount = _privatemsg_limits_get_amount('receive_amount', $recipient);
+        $used = _privatemsg_limits_get_received($recipient);
+        if ($amount > 0 && $used >= $amount) {
+          $blocked[] = array(
+            'recipient' => privatemsg_recipient_key($recipient),
+            'message' =>  t("!name can't receive more messages because he reached the allowed limit.", array('!name' => theme('username', $recipient))),
+          );
+        }
+      }
+    }
+    return $blocked;
+  }
+}
+
+/**
+ * Implements hook_privatemsg_message_presave_alter().
+ */
+function privatemsg_limits_privatemsg_message_presave_alter(&$message) {
+  // Put message into new thread if over number of messages per-thread.
+  if (isset($message['thread_id']) && variable_get('privatemsg_limits_messages_per_thread', 0) > 0) {
+    // If we're not creating a new thread.
+    if (variable_get('privatemsg_limits_messages_per_thread_action', 'create-new') != 'create-new') {
+      return;
+    }
+
+    $query = "SELECT COUNT(*) FROM {pm_index} WHERE thread_id = %d AND recipient = %d AND type IN ('hidden', 'user')";
+    $result = db_result(db_query($query, $message['thread_id'], $message['author']->uid));
+
+    if ($result >= variable_get('privatemsg_limits_messages_per_thread', 0)) {
+      // If the number of messages per-thread has been exceeded, force message into new thread.
+      unset($message['thread_id']);
+    }
+  }
+}
+
+/**
+ * Implements hook_form_FORM_ID_alter().
+ *
+ * Displays a limit info in the message listing.
+ */
+function privatemsg_limits_form_privatemsg_list_alter(&$form, &$form_state) {
+  global $user;
+  $limit = _privatemsg_limits_get_amount('receive_amount', $user);
+  if ($limit > 0) {
+    $used = _privatemsg_limits_get_received($user);
+    if ($used < $limit) {
+      $percent = round(($used / $limit) * 100);
+    }
+    else {
+      $percent = 100;
+      drupal_set_message(t("Message limit reached, you can't send new messages until you delete some."), 'error');
+    }
+    $form['limit'] = array(
+      '#type'  => 'markup',
+      '#value' => t('Used limit: %percent% (%used/%limit)', array('%percent' => $percent, '%used' => $used, '%limit' => $limit)),
+      '#weight' => 15,
+    );
+  }
+}
+
+/**
+ * Loads the oldest message a user has written in the specified timeframe.
+ *
+ * @param $account
+ *   User object
+ * @param $timeframe
+ *   Defines how many seconds back should be considered.
+ */
+function _privatemsg_limits_get_oldest($account, $timeframe) {
+  $query = _privatemsg_assemble_query(array('sent', 'privatemsg_limits'),
+                                      $account, $timeframe);
+  $row = db_fetch_array(db_query($query['query']));
+
+  $wait_time = ($row['timestamp'] - (time() - $timeframe));
+  return format_interval($wait_time, 6);
+}
+
+/**
+ * Loads the maximum value of a treshold value, takes roles into account.
+ *
+ * @param string $name    Unique part of the name
+ * @param user   $account User object
+ *
+ * @return int A specific number or 0 for unlimited
+ */
+function _privatemsg_limits_get_amount($name, $account) {
+  // Don't limit uid 1.
+  if ($account->uid == 1) {
+    return 0;
+  }
+
+  // $account might not be a fully loaded user account, fetch the roles in that
+  // case.
+  // @todo: Remove once privatemsg_user_load_multiple() is implemented.
+  if (!isset($account->roles)) {
+    $account->roles = array(DRUPAL_AUTHENTICATED_RID => 'authenticated user');
+    $result = db_query('SELECT r.rid, r.name FROM {role} r INNER JOIN {users_roles} ur ON ur.rid = r.rid WHERE ur.uid = %d', $account->uid);
+    while ($role = db_fetch_object($result)) {
+      $account->roles[$role->rid] = $role->name;
+    }
+  }
+
+  $role_max = 0;
+  foreach ($account->roles as $id => $role) {
+    $new_max = variable_get("privatemsg_limits_{$name}_role_". $id, NULL);
+    if ($new_max == 'unlimited') {
+      return 0;
+    }
+    if ($new_max > $role_max) {
+      $role_max = $new_max;
+    }
+  }
+  if ($role_max == 0) {
+    return variable_get('privatemsg_limits_'. $name, 0);
+  }
+  return $role_max;
+}
+
+/**
+ * Returns the number of messages/threads a user has written.
+ *
+ * @param user $account   User object
+ * @param int  $timeframe How many seconds back should be considered
+ *
+ * @return int Number of messages/threads
+ */
+function _privatemsg_limits_get_sent($account, $timeframe) {
+  $query = _privatemsg_assemble_query(array('sent', 'privatemsg_limits'),
+                                      $account, $timeframe);
+  return db_result(db_query($query['count']));
+}
+
+/**
+ * SQL Function for amount of messages/threads a user has written in a timeframe.
+ *
+ * @param array $fragments Query array
+ * @param user  $account   User object
+ * @param int   $timeframe how many seconds to consider.
+ */
+function privatemsg_limits_sql_sent(&$fragments, $account,  $timeframe) {
+  $fragments['primary_table'] = '{pm_message} pm';
+
+  if (variable_get('privatemsg_limits_object', 'message') == 'thread') {
+    $fragments['select'][] = 'MAX(pm.timestamp) as timestamp';
+
+    $fragments['inner_join'][] = 'INNER JOIN {pm_index} pmi ON (pmi.mid = pm.mid)';
+    $fragments['group_by'][] = 'pmi.thread_id';
+  }
+  else {
+    $fragments['select'][] = 'pm.timestamp';
+  }
+
+  $fragments['where'][] = 'pm.author = %d';
+  $fragments['query_args']['where'][] = $account->uid;
+  $fragments['where'][] = 'pm.timestamp > %d';
+  $fragments['query_args']['where'][] = time() - $timeframe;
+
+  $fragments['order_by'][] = 'timestamp ASC';
+}
+
+/**
+ * Returns the number of messages/threads a user has received.
+ *
+ * @param user $account   User object
+ * @param int  $timeframe How many seconds back should be considered
+ *
+ * @return int Number of messages/threads
+ */
+function _privatemsg_limits_get_received($account) {
+  $query = _privatemsg_assemble_query(array('received', 'privatemsg_limits'),
+                                      $account);
+  return (int)db_result(db_query($query['count']));
+}
+
+/**
+ * SQL Function for amount of messages/threads a users has.
+ *
+ * @param array $fragments Query array
+ * @param user  $account   User object
+ * @param int   $timeframe how many seconds to consider.
+ */
+function privatemsg_limits_sql_received(&$fragments, $account) {
+  $fragments['primary_table'] = '{pm_index} pmi';
+
+  $fragments['select'][] = 'MAX(pm.timestamp) as timestamp';
+
+  $fragments['where'][] = 'pmi.recipient = %d';
+  $fragments['where'][] = 'pmi.deleted = 0';
+  $fragments['where'][] = "pmi.type IN ('hidden', 'user')";
+
+  $fragments['query_args']['where'][] = $account->uid;
+
+  if (variable_get('privatemsg_limits_object', 'message') == 'thread') {
+    $fragments['group_by'][] = 'pmi.thread_id';
+  }
+  else {
+    $fragments['group_by'][] = 'pmi.mid';
+  }
+  $fragments['order_by'][] = 'timestamp ASC';
+}
\ No newline at end of file
Index: privatemsg_limits/privatemsg_limits.test
===================================================================
RCS file: privatemsg_limits/privatemsg_limits.test
diff -N privatemsg_limits/privatemsg_limits.test
--- /dev/null	1 Jan 1970 00:00:00 -0000
+++ privatemsg_limits/privatemsg_limits.test	15 Aug 2010 12:55:46 -0000
@@ -0,0 +1,490 @@
+<?php
+// $Id$
+
+/**
+ * @file
+ * This file contains tests for the privatemsg limits module
+ */
+
+/**
+ * Test cases for the privatemsg_limits module.
+ */
+class PrivatemsgLimitsTestCase extends DrupalWebTestCase {
+  public static function getInfo() {
+    return array(
+      'name' => 'Privatemsg Limits',
+      'description' => 'Tests limits on sending and recieving messages.',
+      'group' => 'Privatemsg',
+    );
+  }
+
+  /**
+   * Install necessary modules.
+   */
+  function setUp() {
+    parent::setUp('privatemsg', 'privatemsg_limits', 'privatemsg_filter');
+  }
+
+  /**
+   * Test sending limits with threads as limits object.
+   */
+  function testSendLimitsMessages() {
+    $admin = $this->drupalCreateUser(array('administer privatemsg settings', 'write privatemsg', 'read privatemsg'));
+    $user = $this->drupalCreateUser(array('write privatemsg', 'read privatemsg'));
+
+    $this->drupalLogin($admin);
+
+    $settings = array(
+      'privatemsg_limits_send_enabled' => TRUE,
+      'privatemsg_limits_send_amount' => 3,
+      'privatemsg_limits_send_amount_role_3' => 5,
+    );
+    $this->drupalPost('admin/settings/messages/limits', $settings, t('Save configuration'));
+
+    $this->drupalLogin($user);
+    for ($i = 0; $i < 3; $i++) {
+      // Send three messages.
+      $edit = array(
+        'recipient'   => $user->name,
+        'subject'     => $this->randomName(20),
+        'body'        => $this->randomName(100),
+      );
+      $this->drupalPost('messages/new', $edit, t('Send message'));
+      $this->assertText(t('A message has been sent to @recipients.', array('@recipients' => $user->name)));
+    }
+
+    // Send a fourth message that fails.
+    $blocked = array(
+      'recipient'   => $user->name,
+      'subject'     => $this->randomName(20),
+      'body'        => $this->randomName(100),
+    );
+    $this->drupalPost('messages/new', $blocked, t('Send message'));
+    $this->assertText(t('You have exceeded your message sending limit for now.'));
+
+    // Verify that replies can't be sent either.
+    $this->drupalGet('messages');
+    $this->clickLink($edit['subject']);
+    $reply = array(
+      'body'        => $this->randomName(100),
+    );
+    $this->drupalPost(NULL, $reply, t('Send message'));
+    $this->assertText(t('You have exceeded your message sending limit for now.'));
+
+    // Now the same with admin, he should be able to send 5 messages.
+    $this->drupalLogin($admin);
+    for ($i = 0; $i < 5; $i++) {
+      // Send three messages.
+      $edit = array(
+        'recipient'   => $admin->name,
+        'subject'     => $this->randomName(20),
+        'body'        => $this->randomName(100),
+      );
+      $this->drupalPost('messages/new', $edit, t('Send message'));
+      $this->assertText(t('A message has been sent to @recipients.', array('@recipients' => $admin->name)));
+    }
+
+    // Send a sixth message that fails.
+    $blocked = array(
+      'recipient'   => $admin->name,
+      'subject'     => $this->randomName(20),
+      'body'        => $this->randomName(100),
+    );
+    $this->drupalPost('messages/new', $blocked, t('Send message'));
+    $this->assertText(t('You have exceeded your message sending limit for now.'));
+
+    // Verify that replies can't be sent either.
+    $this->drupalGet('messages');
+    $this->clickLink($edit['subject']);
+    $reply = array(
+      'body'        => $this->randomName(100),
+    );
+    $this->drupalPost(NULL, $reply, t('Send message'));
+    $this->assertText(t('You have exceeded your message sending limit for now.'));
+  }
+
+  /**
+   * Test sending limits with threads as limits object.
+   */
+  function testSendLimitsThreads() {
+    $admin = $this->drupalCreateUser(array('administer privatemsg settings', 'write privatemsg', 'read privatemsg'));
+    $user = $this->drupalCreateUser(array('write privatemsg', 'read privatemsg'));
+
+    $this->drupalLogin($admin);
+
+    $settings = array(
+      'privatemsg_limits_send_enabled' => TRUE,
+      'privatemsg_limits_send_amount' => 3,
+      'privatemsg_limits_send_amount_role_3' => 5,
+      'privatemsg_limits_object' => 'thread',
+    );
+    $this->drupalPost('admin/settings/messages/limits', $settings, t('Save configuration'));
+
+    $this->drupalLogin($user);
+    for ($i = 0; $i < 3; $i++) {
+      // Send three messages.
+      $edit = array(
+        'recipient'   => $user->name,
+        'subject'     => $this->randomName(20),
+        'body'        => $this->randomName(100),
+      );
+      $this->drupalPost('messages/new', $edit, t('Send message'));
+      $this->assertText(t('A message has been sent to @recipients.', array('@recipients' => $user->name)));
+    }
+
+    // Send a fourth message that fails.
+    $blocked = array(
+      'recipient'   => $user->name,
+      'subject'     => $this->randomName(20),
+      'body'        => $this->randomName(100),
+    );
+    $this->drupalPost('messages/new', $blocked, t('Send message'));
+    $this->assertText(t('You have exceeded your message sending limit for now.'));
+
+    // Verify that replies can still be sent.
+    $this->drupalGet('messages');
+    $this->clickLink($edit['subject']);
+    $reply = array(
+      'body'        => $this->randomName(100),
+    );
+    $this->drupalPost(NULL, $reply, t('Send message'));
+    $this->assertText(t('A message has been sent to @recipients.', array('@recipients' => $user->name)));
+
+    // Now the same with admin, he should be able to send 5 messages.
+    $this->drupalLogin($admin);
+    for ($i = 0; $i < 5; $i++) {
+      // Send three messages.
+      $edit = array(
+        'recipient'   => $admin->name,
+        'subject'     => $this->randomName(20),
+        'body'        => $this->randomName(100),
+      );
+      $this->drupalPost('messages/new', $edit, t('Send message'));
+      $this->assertText(t('A message has been sent to @recipients.', array('@recipients' => $admin->name)));
+    }
+
+    // Send a sixth message that fails.
+    $blocked = array(
+      'recipient'   => $admin->name,
+      'subject'     => $this->randomName(20),
+      'body'        => $this->randomName(100),
+    );
+    $this->drupalPost('messages/new', $blocked, t('Send message'));
+    $this->assertText(t('You have exceeded your message sending limit for now.'));
+
+    // Verify that replies can't be sent either.
+    $this->drupalGet('messages');
+    $this->clickLink($edit['subject']);
+    $reply = array(
+      'body'        => $this->randomName(100),
+    );
+    $this->drupalPost(NULL, $reply, t('Send message'));
+    $this->assertText(t('A message has been sent to @recipients.', array('@recipients' => $admin->name)));
+  }
+
+  /**
+    * Test receive limit with messages as limits object.
+    */
+  function testReceiveLimitsMessages() {
+    $admin = $this->drupalCreateUser(array('administer privatemsg settings', 'write privatemsg', 'read privatemsg'));
+    $user = $this->drupalCreateUser(array('write privatemsg', 'read privatemsg'));
+
+    $this->drupalLogin($admin);
+
+    $settings = array(
+      'privatemsg_limits_receive_enabled' => TRUE,
+      'privatemsg_limits_receive_amount' => 3,
+      'privatemsg_limits_receive_amount_role_3' => 5,
+    );
+    $this->drupalPost('admin/settings/messages/limits', $settings, t('Save configuration'));
+
+    // Check empty inbox.
+    $this->drupalGet('messages');
+    $this->assertText(t('Used limit: @percent% (@used/@limit)', array('@percent' => 0, '@used' => 0, '@limit' => 5)));
+
+    $this->drupalLogin($user);
+    $this->drupalGet('messages');
+    $this->assertText(t('Used limit: @percent% (@used/@limit)', array('@percent' => 0, '@used' => 0, '@limit' => 3)));
+
+    // Send three messages from user to admin.
+    for ($i = 0; $i < 3; $i++) {
+      $edit = array(
+        'recipient'   => $admin->name,
+        'subject'     => $this->randomName(20),
+        'body'        => $this->randomName(100),
+      );
+      $this->drupalPost('messages/new', $edit, t('Send message'));
+      $this->assertText(t('A message has been sent to @recipients.', array('@recipients' => $admin->name)));
+    }
+
+    // Try sending an additional message.
+    $blocked = array(
+      'recipient'   => $admin->name,
+      'subject'     => $this->randomName(20),
+      'body'        => $this->randomName(100),
+    );
+    $this->drupalPost('messages/new', $blocked, t('Send message'));
+    $this->assertText(t('You have exceeded your message limit. You need to delete messages before you can send new ones.'), 'Limit exceeded message displayed.');
+
+    // Try to reply to a sent message.
+    $this->drupalGet('messages/sent');
+    $this->clickLink($edit['subject']);
+    $reply = array(
+      'body' => $this->randomName(100),
+    );
+    $this->drupalPost(NULL, $reply, t('Send message'));
+    $this->assertText(t('You have exceeded your message limit. You need to delete messages before you can send new ones.'), 'Limit exceeded message displayed.');
+
+    // Check user limits.
+    $this->drupalGet('messages');
+    $this->assertText(t('Used limit: @percent% (@used/@limit)', array('@percent' => 100, '@used' => 3, '@limit' => 3)));
+
+    // Check admin limits.
+    $this->drupalLogin($admin);
+    $this->drupalGet('messages');
+    $this->assertText(t('Used limit: @percent% (@used/@limit)', array('@percent' => 60, '@used' => 3, '@limit' => 5)));
+
+    // Try to send a message to the user.
+    $blocked = array(
+      'recipient'   => $user->name,
+      'subject'     => $this->randomName(20),
+      'body'        => $this->randomName(100),
+    );
+    $this->drupalPost('messages/new', $blocked, t('Send message'));
+    $this->assertText(t("@user can't receive more messages because he reached the allowed limit.", array('@user' => $user->name)));
+
+    // Try to reply to a message.
+    $this->drupalGet('messages');
+    $this->clickLink($edit['subject']);
+    $this->assertNoText(t('Send message'));
+  }
+
+  /**
+    * Test receive limit with messages as limits object.
+    */
+  function testReceiveLimitsThreads() {
+    $admin = $this->drupalCreateUser(array('administer privatemsg settings', 'write privatemsg', 'read privatemsg'));
+    $user = $this->drupalCreateUser(array('write privatemsg', 'read privatemsg'));
+
+    $this->drupalLogin($admin);
+
+    $settings = array(
+      'privatemsg_limits_receive_enabled' => TRUE,
+      'privatemsg_limits_receive_amount' => 3,
+      'privatemsg_limits_receive_amount_role_3' => 5,
+      'privatemsg_limits_object' => 'thread',
+    );
+    $this->drupalPost('admin/settings/messages/limits', $settings, t('Save configuration'));
+
+    // Check empty inbox.
+    $this->drupalGet('messages');
+    $this->assertText(t('Used limit: @percent% (@used/@limit)', array('@percent' => 0, '@used' => 0, '@limit' => 5)));
+
+    $this->drupalLogin($user);
+    $this->drupalGet('messages');
+    $this->assertText(t('Used limit: @percent% (@used/@limit)', array('@percent' => 0, '@used' => 0, '@limit' => 3)));
+
+    // Send three messages from user to admin.
+    for ($i = 0; $i < 3; $i++) {
+      $edit = array(
+        'recipient'   => $admin->name,
+        'subject'     => $this->randomName(20),
+        'body'        => $this->randomName(100),
+      );
+      $this->drupalPost('messages/new', $edit, t('Send message'));
+      $this->assertText(t('A message has been sent to @recipients.', array('@recipients' => $admin->name)));
+    }
+
+    // Try sending an additional message.
+    $blocked = array(
+      'recipient'   => $admin->name,
+      'subject'     => $this->randomName(20),
+      'body'        => $this->randomName(100),
+    );
+    $this->drupalPost('messages/new', $blocked, t('Send message'));
+    $this->assertText(t('You have exceeded your message limit. You need to delete messages before you can send new ones.'), 'Limit exceeded message displayed.');
+
+    // Try to reply to a sent message.
+    $this->drupalGet('messages/sent');
+    $this->clickLink($edit['subject']);
+    $reply = array(
+      'body' => $this->randomName(100),
+    );
+    $this->drupalPost(NULL, $reply, t('Send message'));
+    $this->assertText(t('A message has been sent to @recipients.', array('@recipients' => $admin->name)));
+
+    // Check user limits.
+    $this->drupalGet('messages');
+    $this->assertText(t('Used limit: @percent% (@used/@limit)', array('@percent' => 100, '@used' => 3, '@limit' => 3)));
+
+    // Check admin limits.
+    $this->drupalLogin($admin);
+    $this->drupalGet('messages');
+    $this->assertText(t('Used limit: @percent% (@used/@limit)', array('@percent' => 60, '@used' => 3, '@limit' => 5)));
+
+    // Try to send a message to the user.
+    $blocked = array(
+      'recipient'   => $user->name,
+      'subject'     => $this->randomName(20),
+      'body'        => $this->randomName(100),
+    );
+    $this->drupalPost('messages/new', $blocked, t('Send message'));
+    $this->assertText(t("@user can't receive more messages because he reached the allowed limit.", array('@user' => $user->name)));
+
+    // Try to reply to a message.
+    $this->drupalGet('messages');
+    $this->clickLink($edit['subject']);
+    $reply = array(
+      'body' => $this->randomName(100),
+    );
+    $this->drupalPost(NULL, $reply, t('Send message'));
+    $this->assertText(t('A message has been sent to @recipients.', array('@recipients' => $user->name)));
+  }
+
+  /**
+   * Test limiting the number of recipients.
+   */
+  function testRecipientsLimits() {
+    $admin = $this->drupalCreateUser(array('administer privatemsg settings', 'write privatemsg', 'read privatemsg'));
+    $user1 = $this->drupalCreateUser(array('write privatemsg', 'read privatemsg'));
+    $user2 = $this->drupalCreateUser(array('write privatemsg', 'read privatemsg'));
+    $user3 = $this->drupalCreateUser(array('write privatemsg', 'read privatemsg'));
+
+    $this->drupalLogin($admin);
+
+    $settings = array(
+      'privatemsg_limits_recipients_enabled' => TRUE,
+      'privatemsg_limits_recipients_amount' => 1,
+      'privatemsg_limits_recipients_amount_role_3' => 2,
+    );
+    $this->drupalPost('admin/settings/messages/limits', $settings, t('Save configuration'));
+
+    // Send a message to a single user.
+    $edit = array(
+      'recipient'   => $user1->name,
+      'subject'     => $this->randomName(20),
+      'body'        => $this->randomName(100),
+    );
+    $this->drupalPost('messages/new', $edit, t('Send message'));
+    $this->assertText(t('A message has been sent to @recipients.', array('@recipients' => $user1->name)));
+
+    // Send a message to two users.
+    $edit = array(
+      'recipient'   => $user1->name . ', ' . $user2->name,
+      'subject'     => $this->randomName(20),
+      'body'        => $this->randomName(100),
+    );
+    $this->drupalPost('messages/new', $edit, t('Send message'));
+    $this->assertText(t('A message has been sent to @recipients.', array('@recipients' => $user1->name . ', ' . $user2->name)));
+
+    // Try sending a message to three users.
+    $edit = array(
+      'recipient'   => $user1->name . ', ' . $user2->name . ', ' . $user3->name,
+      'subject'     => $this->randomName(20),
+      'body'        => $this->randomName(100),
+    );
+    $this->drupalPost('messages/new', $edit, t('Send message'));
+    $this->assertText(t('You are not allowed to send a message to more than @number recipients.', array('@number' => 2)), 'Not allowed message displayed.');
+
+    // Login in as user.
+    $this->drupalLogin($user1);
+    // Send a message to a single users.
+    $edit = array(
+      'recipient'   => $user2->name,
+      'subject'     => $this->randomName(20),
+      'body'        => $this->randomName(100),
+    );
+    $this->drupalPost('messages/new', $edit, t('Send message'));
+    $this->assertText(t('A message has been sent to @recipients.', array('@recipients' => $user2->name)));
+
+    // Try sending a message to two users.
+    $edit = array(
+      'recipient'   => $user2->name . ', ' . $user3->name,
+      'subject'     => $this->randomName(20),
+      'body'        => $this->randomName(100),
+    );
+    $this->drupalPost('messages/new', $edit, t('Send message'));
+    $this->assertText(t('You are not allowed to send a message to more than @number recipients.', array('@number' => 1)), 'Not allowed message displayed.');
+  }
+
+  /**
+   * Tests for limiting the number of messages per thread.
+   */
+  function testNumberOfMessagesBlock() {
+    $admin = $this->drupalCreateUser(array('administer privatemsg settings', 'write privatemsg', 'read privatemsg'));
+    $user = $this->drupalCreateUser(array('write privatemsg', 'read privatemsg'));
+
+    $this->drupalLogin($admin);
+
+    $settings = array(
+      'privatemsg_limits_messages_per_thread' => 2,
+      'privatemsg_limits_messages_per_thread_action' => 'block-message',
+    );
+    $this->drupalPost('admin/settings/messages/limits', $settings, t('Save configuration'));
+
+    // Send a message to a user.
+    $edit = array(
+      'recipient'   => $user->name,
+      'subject'     => $this->randomName(20),
+      'body'        => $this->randomName(100),
+    );
+    $this->drupalPost('messages/new', $edit, t('Send message'));
+    $this->assertText(t('A message has been sent to @recipients.', array('@recipients' => $user->name)));
+
+    // Send a reply.
+    $this->drupalLogin($user);
+    $this->drupalGet('messages');
+    $this->clickLink($edit['subject']);
+    $edit = array(
+      'body' => $this->randomName(100),
+    );
+    $this->drupalPost(NULL, $edit, t('Send message'));
+    $this->assertText(t('A message has been sent to @recipients.', array('@recipients' => $admin->name)));
+
+    // Try to send another one.
+    $edit = array(
+      'body' => $this->randomName(100),
+    );
+    $this->drupalPost(NULL, $edit, t('Send message'));
+    $this->assertText(t('The message cannot be sent because the limit of messages per thread has been reached.'));
+  }
+
+  /**
+   * Tests for limiting the number of messages per thread.
+   */
+  function testNumberOfMessagesCreate() {
+    $admin = $this->drupalCreateUser(array('administer privatemsg settings', 'write privatemsg', 'read privatemsg'));
+    $user = $this->drupalCreateUser(array('write privatemsg', 'read privatemsg'));
+
+    $this->drupalLogin($admin);
+
+    $settings = array(
+      'privatemsg_limits_messages_per_thread' => 1,
+      'privatemsg_limits_messages_per_thread_action' => 'create-new',
+    );
+    $this->drupalPost('admin/settings/messages/limits', $settings, t('Save configuration'));
+
+    // Send a message to a user.
+    $edit = array(
+      'recipient'   => $user->name,
+      'subject'     => $this->randomName(20),
+      'body'        => $this->randomName(100),
+    );
+    $this->drupalPost('messages/new', $edit, t('Send message'));
+    $this->assertText(t('A message has been sent to @recipients.', array('@recipients' => $user->name)));
+
+    // Send a reply.
+    $this->drupalLogin($user);
+    $this->drupalGet('messages');
+    $this->clickLink($edit['subject']);
+    $reply = array(
+      'body' => $this->randomName(100),
+    );
+    $this->drupalPost(NULL, $reply, t('Send message'));
+    $this->assertText(t('A message has been sent to @recipients.', array('@recipients' => $admin->name)));
+    // Make sure we are in a new thread and the original thread body isn't
+    // displayed anymore.
+    $this->assertNoText($edit['body']);
+    $this->assertText($reply['body']);
+  }
+}
\ No newline at end of file
