? privatemsg_limits/translations
Index: privatemsg.pages.inc
===================================================================
RCS file: /cvs/drupal/contributions/modules/privatemsg/privatemsg.pages.inc,v
retrieving revision 1.14
diff -u -p -r1.14 privatemsg.pages.inc
--- privatemsg.pages.inc	16 Aug 2010 08:12:25 -0000	1.14
+++ privatemsg.pages.inc	7 Sep 2010 07:45:54 -0000
@@ -197,7 +197,7 @@ function privatemsg_new(&$form_state, $r
   $usercount = 0;
   $to = array();
   $to_plain = array();
-  $blocked = FALSE;
+  $blocked_messages = array();
   foreach ($recipients as $recipient) {
     if ($recipient->type == 'hidden') {
       continue;
@@ -223,12 +223,14 @@ function privatemsg_new(&$form_state, $r
       $to_plain[privatemsg_recipient_key($recipient)] = privatemsg_recipient_format($recipient, array('plain' => TRUE));
     }
     else {
-      // Recipient list contains blocked users.
-      $blocked = TRUE;
+      // Store blocked messages. These are only displayed if all recipients
+      // are blocked.
+      $first_reason = reset($user_blocked);
+      $blocked_messages[] = $first_reason['message'];
     }
   }
 
-  if (empty($to) && $usercount >= 1 && !$blocked) {
+  if (empty($to) && $usercount >= 1 && empty($blocked_messages)) {
     // Assume the user sent message to own account as if the usercount is one or less, then the user sent a message but not to self.
     $to['user_' . $user->uid] = privatemsg_recipient_format($user);
     $to_plain['user_' . $user->uid] = privatemsg_recipient_format($user, array('plain' => TRUE));
@@ -352,13 +354,24 @@ function privatemsg_new(&$form_state, $r
       '#default_value' => $subject,
     );
     $recipients_string_themed = implode(', ', $to);
-    $form['privatemsg']['recipient_display'] = array(
-      '#value' =>  '<p>'. t('<strong>Reply to thread</strong>:<br /> Recipients: !to', array('!to' => $recipients_string_themed)) .'</p>',
-      '#weight' => -10,
-    );
+    if (!empty($recipients_string_themed)) {
+      $form['privatemsg']['recipient_display'] = array(
+        '#value' =>  '<p>'. t('<strong>Reply to thread</strong>:<br /> Recipients: !to', array('!to' => $recipients_string_themed)) .'</p>',
+        '#weight' => -10,
+      );
+    }
     if (empty($recipients_string)) {
-      // If there are no valid recipients, unset the message reply form.
-      $form['privatemsg']['#access'] = FALSE;
+      // If there are no valid recipients, hide all visible parts of the form.
+      foreach (element_children($form['privatemsg']) as $element) {
+        $form['privatemsg'][$element]['#access'] = FALSE;
+      }
+
+      // Display a message if some users are blocked.
+      if (!empty($blocked_messages)) {
+        $blocked = t('You can not reply to this conversation because all recipients are blocked.');
+        $blocked .= theme('item_list', $blocked_messages);
+        $form['privatemsg']['blocked']['#value'] = $blocked;
+      }
     }
   }
   // Only set read all if it is a boolean TRUE. It might also be an integer set
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	7 Sep 2010 07:45:54 -0000
@@ -0,0 +1,142 @@
+<?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['conversation'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Conversation settings'),
+  );
+  $form['conversation']['privatemsg_limits_messages_per_thread'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Maximum number of messages in a conversation'),
+    '#description' => t('The maximum number of messages that can be included in a conversation. If this maximum has already been reached and a user attempts to add an additional message, then the action specified below shall be taken. Leave this set to 0 if you want unlimited messages per conversation.'),
+    '#default_value' => variable_get('privatemsg_limits_messages_per_thread', 0),
+    '#size' => '3',
+  );
+  $form['conversation']['privatemsg_limits_messages_per_thread_action'] = array(
+    '#type' => 'radios',
+    '#title' => t('Maximum messages action'),
+    '#description' => t('This action shall be taken once a thread has already reached its maximum number of messages.'),
+    '#default_value' => variable_get('privatemsg_limits_messages_per_thread_action', 'create-new'),
+    '#options' => array(
+      'create-new' => t('Create new conversation'),
+      '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 the total number of messages/conversations that a user may have.'),
+    '#default_value' => variable_get('privatemsg_limits_receive_enabled', FALSE),
+  );
+  $form['receive']['privatemsg_limits_receive_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 conversations a user can initiate? An exceeded conversation limit will allow users to still write individual messages in existing conversations, but not start new ones.'),
+    '#default_value' => variable_get('privatemsg_limits_receive_object', 'message'),
+    '#options' => array('message' => t('Messages'), 'thread' => t('Conversations')),
+  );
+  $form['receive']['privatemsg_limits_receive_amount'] = array(
+    '#type'  => 'textfield',
+    '#title' => t('Maximum number of messages/conversations per user'),
+    '#description' => t('The total number of messages/conversations that a user may have before he has to delete old messages/conversations. When this limit is reached, users are not allowed to receive or send new messages.'),
+    '#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 the total number of messages/conversations that a user can send in a given time period'),
+    '#default_value' => variable_get('privatemsg_limits_send_enabled', FALSE),
+  );
+  $form['send']['privatemsg_limits_send_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 conversations a user can initiate? An exceeded conversation limit will allow users to still write individual messages in existing conversations, but not start new ones.'),
+    '#default_value' => variable_get('privatemsg_limits_send_object', 'message'),
+    '#options' => array('message' => t('Messages'), 'thread' => t('Conversations')),
+  );
+  $form['send']['privatemsg_limits_send_amount'] = array(
+    '#type'  => 'textfield',
+    '#title' => t('Maximum number of messages/conversations per time period'),
+    '#description' => t('The total number of messages/conversations that a user may 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 to be used'),
+    '#description' => t("Specify the time period to be used when limiting a user's sent messages/threads."),
+    '#default_value' => variable_get('privatemsg_limits_send_timeframe', 3600),
+    '#options' => drupal_map_assoc(array(60, 300, 1800, 3600, 86400, 604800, 604800 * 4), '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 the total number of recipients that a user can include in a single message'),
+    '#default_value' => variable_get('privatemsg_limits_recipients_enabled', FALSE),
+  );
+  $form['recipients']['privatemsg_limits_recipients_amount'] = array(
+    '#type'  => 'textfield',
+    '#title' => t('Maximum number of recipients per message'),
+    '#description' => t('Defines the total number of recipients a user may include in a single message. This setting only affects new messages (and not replies on existing message threads). A role (just like any other recipient type) is considered to be a single recipient regardless of the number of users with that role.'),
+    '#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 may override the maximum limit specified above on a per-role basis. If a user has multiple roles, then the highest maximum value shall be used. Enter "unlimited" if a role may have unlimited messages/conversations. Enter "0" if you do not want to override the maximum limit setting.'),
+    '#title'  => t('Override maximum limit by role'),
+    '#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	7 Sep 2010 07:45:54 -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	7 Sep 2010 07:45:55 -0000
@@ -0,0 +1,347 @@
+<?php
+// $Id$
+
+/**
+ * @file
+ * Privatemsg Quota module
+ */
+
+/**
+ * Implements hook_perm()-
+ */
+function privatemsg_limits_perm() {
+  // Description for this permission:
+  // Enables a user to send a message to a recipient even when the recipient's
+  // message/conversation maximum limit has already been reached. Without this
+  // permission, the message would ordinarily be blocked.
+  return array('bypass recipient message limit');
+}
+
+/**
+ * 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_send_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));
+      $period = format_interval(variable_get('privatemsg_limits_send_timeframe', 3600));
+      if (variable_get('privatemsg_limits_receive_object', 'message') == 'message') {
+        $errors[] = t("Your message was not sent because you have exceeded your sending limit. You are allowed to send %limit messages every @period. You can send your next message in in @wait_time.", array('@wait_time' => $wait_time, '%limit' => $amount, '@period' => $period));
+      }
+      else {
+        $errors[] = t("Your message was not sent because you have exceeded your sending limit. You are allowed to start %limit conversations every @period. You can start your next conversation in in @wait_time.", array('@wait_time' => $wait_time, '%limit' => $amount, '@period' => $period));
+      }
+    }
+  }
+
+  if (variable_get('privatemsg_limits_receive_enabled', FALSE) && (empty($message['thread_id']) || variable_get('privatemsg_limits_receive_object', 'message') == 'message')) {
+    $amount = _privatemsg_limits_get_amount('receive_amount', $message['author']);
+    $used = _privatemsg_limits_get_received($message['author']);
+
+    $type = array('message' => t('messages'), 'thread' => t('conversations'));
+
+    if ($amount > 0 && $used >= $amount) {
+      if (variable_get('privatemsg_limits_receive_object', 'message') == 'message') {
+        $errors[] = t("Your message mailbox is currently full. You are allowed a maximum of %limit messages in your mailbox at one time. You won't be able to send or receive new messages until you delete some existing ones.", array('%limit' => $amount));
+      }
+      else {
+        $errors[] = t("Your message mailbox is currently full. You are allowed a maximum of %limit conversations in your mailbox at one time. You won't be able to start or receive new conversations until you delete some existing ones.", array('%limit' => $amount));
+      }
+    }
+  }
+
+  // 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("This message cannot be sent because the thread already contains %limit messages (the maximum number of messages permitted per thread). To send this message, please create a new message thread.", array('%limit' => variable_get('privatemsg_limits_messages_per_thread', 0)));
+      }
+    }
+  }
+  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_receive_object', 'message') == 'message') ) {
+    $blocked = array();
+
+    // Users that have the by-pass permission can send messages even if the
+    // mailbox of the recipient is full.
+    if (user_access('bypass recipient message limit', $author)) {
+      return $blocked;
+    }
+
+    foreach ($recipients as $recipient) {
+      // Only user recipients are supported.
+      if (!isset($recipient->type) || $recipient->type == 'user' || $recipient->type == 'hidden') {
+        $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("This message cannot be sent to !name because !name's mailbox is full.", 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']);
+      drupal_set_message(t("Your message would have exceeded our %limit messages per conversation limit. As a result, we've created a new conversation for your message.", array('%limit' => variable_get('privatemsg_limits_messages_per_thread', 0))));
+    }
+  }
+}
+
+/**
+ * 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', $form['account']['#value']);
+  if ($limit > 0) {
+    $used = _privatemsg_limits_get_received($form['account']['#value']);
+    if ($used < $limit) {
+      $percent = round(($used / $limit) * 100);
+    }
+    else {
+      $percent = 100;
+      if ($user->uid == $form['account']['#value']->uid) {
+        if (variable_get('privatemsg_limits_receive_object', 'message') == 'message') {
+          $error = t("Your message mailbox is currently full. You are allowed a maximum of %limit messages in your mailbox at one time. You won't be able to send or receive new messages until you delete some existing ones.", array('%limit' => $limit));
+        }
+        else {
+          $error = t("Your message mailbox is currently full. You are allowed a maximum of %limit conversations in your mailbox at one time. You won't be able to start or receive new conversations until you delete some existing ones.", array('%limit' => $limit));
+        }
+      }
+      else {
+        if (variable_get('privatemsg_limits_receive_object', 'message') == 'message') {
+          $error = t("This message mailbox is currently full. !user is allowed a maximum of %limit messages in his mailbox at one time. !user won't be able to send or receive new messages until you delete some existing ones.", array('%limit' => $limit, '!user' => theme('username', $form['account']['#value'])));
+        }
+        else {
+          $error = t("This message mailbox is currently full. !user is allowed a maximum of %limit conversations in his mailbox at one time. !user won't be able to start or receive new conversations until you delete some existing ones.", array('%limit' => $limit, '!user' => theme('username', $form['account']['#value'])));
+        }
+      }
+      drupal_set_message($error, 'error');
+    }
+    if (variable_get('privatemsg_limits_receive_object', 'message') == 'message') {
+      $message = format_plural($used, 'You are currently using %percent% (@count message) of your %limit messages limit.', 'You are currently using %percent% (@count messages) of your %limit messages limit.', array('%percent' => $percent, '%used' => $used, '%limit' => $limit));
+    }
+    else {
+      $message = format_plural($used, 'You are currently using %percent% (@count conversation) of your %limit conversations limit.', 'You are currently using %percent% (@count conversations) of your %limit conversations limit.', array('%percent' => $percent, '%used' => $used, '%limit' => $limit));
+    }
+    $form['limit'] = array(
+      '#type'  => 'markup',
+      '#value' => $message,
+      '#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_send_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_receive_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	7 Sep 2010 07:45:55 -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_send_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('You are currently using @percent% (@used messages) of your @limit messages limit.', array('@percent' => 0, '@used' => 0, '@limit' => 5)));
+
+    $this->drupalLogin($user);
+    $this->drupalGet('messages');
+    $this->assertText(t('You are currently using @percent% (@used messages) of your @limit messages 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("Your message mailbox is currently full. You are allowed a maximum of @limit messages in your mailbox at one time. You won't be able to send or receive new messages until you delete some existing ones.", array('@limit' => 3)), '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("Your message mailbox is currently full. You are allowed a maximum of @limit messages in your mailbox at one time. You won't be able to send or receive new messages until you delete some existing ones.", array('@limit' => 3)), 'Limit exceeded message displayed.');
+
+    // Check user limits.
+    $this->drupalGet('messages');
+    $this->assertText(t('You are currently using @percent% (@used messages) of your @limit messages limit.', array('@percent' => 100, '@used' => 3, '@limit' => 3)));
+
+    // Check admin limits.
+    $this->drupalLogin($admin);
+    $this->drupalGet('messages');
+    $this->assertText(t('You are currently using @percent% (@used messages) of your @limit messages 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("This message cannot be sent to @user because @user's mailbox is full.", 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_receive_object' => 'thread',
+    );
+    $this->drupalPost('admin/settings/messages/limits', $settings, t('Save configuration'));
+
+    // Check empty inbox.
+    $this->drupalGet('messages');
+    $this->assertText(t('You are currently using @percent% (@used conversations) of your @limit conversations limit.', array('@percent' => 0, '@used' => 0, '@limit' => 5)));
+
+    $this->drupalLogin($user);
+    $this->drupalGet('messages');
+    $this->assertText(t('You are currently using @percent% (@used conversations) of your @limit conversations 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("Your message mailbox is currently full. You are allowed a maximum of @limit conversations in your mailbox at one time. You won't be able to start or receive new conversations until you delete some existing ones.", array('@limit' => 3)), '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('You are currently using @percent% (@used conversations) of your @limit conversations limit.', array('@percent' => 100, '@used' => 3, '@limit' => 3)));
+
+    // Check admin limits.
+    $this->drupalLogin($admin);
+    $this->drupalGet('messages');
+    $this->assertText(t('You are currently using @percent% (@used conversations) of your @limit conversations 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("This message cannot be sent to @user because @user's mailbox is full.", 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("This message cannot be sent because the thread already contains @limit messages (the maximum number of messages permitted per thread). To send this message, please create a new message thread.", array('@limit' => 2)));
+  }
+
+  /**
+   * 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
