<?php
// $Id: privatemsg.module,v 1.52.2.7 2006/08/11 22:52:44 mindless Exp $

/**
 * Implementation of hook_help().
 */
function privatemsg_help($section) {
  switch ($section) {
    case 'admin/help#privatemsg':
      $output = '<p>'. t('The private messaging module allows users to send messages to each other without having to share email addresses. An inbox link will appear in the navigation menu. The "write to author" links are included in posts, allowing users to write a private message instead of commenting openly.  Allowing users to communicate directly is an important  part of building the strength of the community.') .'</p>';
      $output .= '<p>'. t('Users can also select whether to receive email notices of new messages by editing their user profile.  The contacts list contains only users that you have previously messaged. To contact users not in your list, you need to know their local user name.  Administrators can set messaging options such as frequency of emails, message status display, and number of messages to display per page.   They can also configure \'Write to Author\' options.') .'</p>';
      $output .= t('<p>You can</p>
<ul>
<li>administer privatemsg at <a href="%admin-settings-privatemsg">administer &gt;&gt; settings &gt;&gt; private message</a>.</li>
<li>view your private messages at <a href="%privatemsg">view inbox</a>.</li>
', array('%admin-settings-privatemsg' => url('admin/settings/privatemsg'), '%privatemsg' => url('privatemsg'))) .'</ul>';
      $output .= '<p>'. t('For more information please read the configuration and customization handbook <a href="%privatemsg">Privatemsg page</a>.', array('%privatemsg' => 'http://www.drupal.org/handbook/modules/privatemsg/')) .'</p>';
      return $output;
    case 'admin/modules#description':
      return t('Allows private messages between users.');
  }
}

/**
 * Implementation of hook_link().
 */
function privatemsg_link($type, $node = 0, $main = 0) {
  global $user;
  static $access = array();
  if (user_access('access private messages') && ($type == 'node' || $type == 'comment') && variable_get("privatemsg_link_$type", 0) && (isset($user->privatemsg_allow) ? $user->privatemsg_allow : 1)) {
    if (!isset($access[$node->uid])) {
      $author = user_load(array('uid' => $node->uid));
      $access[$node->uid] = user_access('access private messages', $author) && $author->uid && (isset($author->privatemsg_allow) ? $author->privatemsg_allow : 1);
    }
    if ($access[$node->uid]) {
      return array(l(t('write to author'), "privatemsg/msgto/$node->uid"));
    }
  }
}

/**
 * Implementation of hook_menu().
 */
function privatemsg_menu($may_cache) {
  $items = array();
  global $user;

  if ($may_cache) {
    $items[] = array('path' => 'admin/settings/privatemsg',
        'title' => 'privatemsg',
        'callback' => 'privatemsg_configure');
  }
  else {
    $items[] = array('path' => 'privatemsg',
                     'title' => t('my inbox') . ' ('. (int)_privatemsg_get_new_messages() .')',
                     'callback' => 'privatemsg_page',
                     'access' => user_access('access private messages'),
                     'type' => $user->uid && (isset($user->privatemsg_allow) ? $user->privatemsg_allow : 1) ? MENU_DYNAMIC_ITEM : MENU_CALLBACK);
  }
  return $items;
}

/**
 * Implementation of hook_user().
 */
function privatemsg_user($type, &$edit, &$user, $category = NULL) {
  switch ($type) {
    case 'view':
      if (user_access('access private messages') && (isset($user->privatemsg_allow) ? $user->privatemsg_allow : 1)) {
        return array(t('Private messages') => array(array(
          'value' => l(t('send private message'), 'privatemsg/msgto/'. $user->uid),
          'class' => 'send-message')));
      }
      else if ($GLOBALS['user']->uid) {
        return;
      }
      else if (isset($user->privatemsg_allow) ? $user->privatemsg_allow : 1) {
        if (variable_get('user_register', 1)) {
          return array(t('Private messages') => array(array(
            'value' => t('<a href="%login">login</a> or <a href="%register">register</a> to send private messages to this user', array('%login' => url('user/login'), '%register' => url('user/register'))),
            'class' => 'need-login')));
        }
        else {
          return array(t('Private messages') => array(array(
            'value' => t('<a href="%login">login</a> to send private messages to this user', array('%login' => url('user/login'))),
            'class' => 'need-login')));
        }
      }
      break;

    case 'form':
      if (user_access('access private messages') && $category == 'account') {
        $form = array();
        $form['privatemsg_settings'] = array(
            '#type' => 'fieldset',
            '#title' => t('Private message settings'),
            '#weight' => 4,
            '#collapsible' => TRUE
            );
        $form['privatemsg_settings']['privatemsg_allow'] = array(
            '#type' => 'checkbox',
            '#title' => t('Allow private messages'),
            '#default_value' => isset($edit['privatemsg_allow']) ? $edit['privatemsg_allow'] : 1,
            '#description' => t('Check this box to allow users to send you private messages.')
            );
        $form['privatemsg_settings']['privatemsg_mailalert'] = array(
            '#type' => 'checkbox',
            '#title' => t('Receive daily e-mail for unread messages'),
            '#default_value' => isset($edit['privatemsg_mailalert']) ? $edit['privatemsg_mailalert'] : 0,
            '#description' => t('Check this box to receive e-mail notification for unread messages. Only one e-mail will be sent per day.')
            );

        return $form;
      }
      break;
  }
}

function privatemsg_configure() {
  $form = array();

  $form['privatemsg_max_rate'] = array(
      '#type' => 'select',
      '#title' => t('Private messaging max rate'),
      '#default_value' => variable_get('privatemsg_max_rate', 15),
      '#options' => drupal_map_assoc(array(5, 10, 15, 20, 30, 60), 'format_interval'),
      '#description' => t('Max submit rate for private messaging. To prevent abuse.')
      );
  $form['privatemsg_sent_status'] = array(
      '#type' => 'select',
      '#title' => t('Sent message status'),
      '#default_value' => variable_get('privatemsg_sent_status', 1),
      '#options' => array(t('Disabled'), t('Enabled')),
      '#description' => t('If enabled users can see whether a message has been read or not.')
      );
  $form['privatemsg_per_page'] = array(
      '#type' => 'select',
      '#title' => t('Messages per page'),
      '#default_value' => variable_get('privatemsg_per_page', 10),
      '#options' => drupal_map_assoc(array(5, 10, 15, 20, 25, 30, 35, 40, 50, 60, 80, 100)),
      '#description' => t('The maximum number of messages displayed per page; links to browse messages automatically appear.')
      );

  $form['links'] = array(
      '#type' => 'fieldset',
      '#title' => t('"Write to author" links')
      );
  $form['links']['privatemsg_link_node'] = array(
      '#type' => 'checkbox',
      '#title' => t('Display link with posts'),
      '#return_value' => 1,
      '#default_value' => variable_get('privatemsg_link_node', 0),
      '#description' => t('Provide a link to send private messages to users with posts they start.')
      );
  $form['links']['privatemsg_link_comment'] = array(
      '#type' => 'checkbox',
      '#title' => t('Display link with comments'),
      '#return_value' => 1,
      '#default_value' => variable_get('privatemsg_link_comment', 0),
      '#description' => t('Provide a link to send private messages to users with their comments.')
      );

  return system_settings_form('privatemsg_settings', $form);
}

/**
 * Implementation of hook_perm().
 */
function privatemsg_perm() {
  return array('access private messages');
}

/**
 * Implementation of hook_cron().
 */
function privatemsg_cron() {
  // perform these actions just once per day
  if (variable_get('privatemsg_last_cron', 0) < (time() - 3600*24)) {
    _privatemsg_prune();
    _privatemsg_mailalert();
    variable_set('privatemsg_last_cron', time());
  }
}

function _privatemsg_prune() {
  // move deleted message older than 1 month to archive table, and optimize table
  $result = db_query("SELECT * FROM {privatemsg} WHERE author_del = 1 AND recipient_del = 1 AND timestamp < '%d'", (time() - 3600*24*30));
  while ($message = db_fetch_object($result)) {
    db_query("INSERT INTO {privatemsg_archive} (id, author, recipient, subject, message, timestamp, hostname, format, folder) VALUES ('%d', '%d', '%d', '%s', '%s', '%d', '%s', '%d', '%d')", $message->id, $message->author, $message->recipient, $message->subject, $message->message, $message->timestamp, $message->hostname, $message->format, $message->folder);
    db_query("DELETE FROM {privatemsg} WHERE id = '%d'", $message->id);
  }

  // this is MySQL-specific
  if ($GLOBALS['db_type'] == 'mysql') {
    db_query("OPTIMIZE TABLE {privatemsg}");
  }
}

function _privatemsg_mailalert() {
  global $locale;
  $initial_locale = $locale;
  if (function_exists('locale')) {
    $languages = locale_supported_languages();
    $languages = $languages['name'];
  }

  $from = variable_get('site_mail', ini_get('sendmail_from'));
  $result = db_query('SELECT COUNT(*) AS c, recipient FROM {privatemsg} WHERE newmsg = 1 AND recipient_del = 0 GROUP BY recipient');

  while ($alert = db_fetch_object($result)) {
    $user = user_load(array('uid' => $alert->recipient));

    if ((isset($user->privatemsg_allow) ? $user->privatemsg_allow : 1) && (isset($user->privatemsg_mailalert) ? $user->privatemsg_mailalert : 0) && $user->status != 0) {
      // use each user's individual locale
      if (function_exists('locale') && $languages[$user->language]) {
        $locale = $user->language;
      }

      $subject = t('New private messages at %site.', array('%site' => variable_get('site_name', 'drupal')));
      $message = t('Hi %name,
This is an automatic reminder from the site %site. You have %new unread private messages.

To read your messages, follow this link:
%link1

If you don\'t want to receive these email again, change your preferences here:
%link2', array('%name' => $user->name, '%site' => variable_get('site_name', 'drupal'), '%new' => $alert->c, '%link1' => url('user/login', 'destination=privatemsg', NULL, 1), '%link2' => url('user/'. $user->uid .'/edit', NULL, NULL, 1)));

      user_mail($user->mail, $subject, $message, "From: $from\nReply-to: $from\nX-Mailer: Drupal\nReturn-path: $from\nErrors-to: $from");

      // revert to previous (site default) locale
      $locale = $initial_locale;
    }
  }
}

function privatemsg_page() {
  global $user;

  $breadcrumb = NULL;
  $op = $_POST["op"];
  $edit = $_POST["edit"];
  $recipient = $_POST["recipient"];
  if (isset($edit['messages'])) {
    $msg = array_keys($edit['messages']);
  }
  else {
    $msg = array();
  }

  if (empty($op)) {
    $op = arg(1);
  }
  $arg = arg(2);

  if (!$user->uid && !in_array($op, array('form', 'msgto', 'send', t('Send private message')))) {
    // If guest is given access to privatemsg, only allow sending messages
    return drupal_access_denied();
  }

  switch ($op) {
    case 'list':
      $output = _privatemsg_list($arg);
      $title = t('Private messages');
      break;
    case 'view':
      $output = _privatemsg_view($arg);
      $title = t("Read message");
      $breadcrumb = array(l(t('Home'), ''), l(t('private messages'), 'privatemsg'));
      break;
    case t('Write a new message'):
      $arg = "";
    case 'form':
    case 'reply':
      $output = _privatemsg_form($arg);
      $title = t("Write a new message");
      $breadcrumb = array(l(t('Home'), ''), l(t('private messages'), 'privatemsg'));
      break;
    case 'msgto':
      $msg = (object)$msg;
      $msg->recipient = db_result(db_query("SELECT name FROM {users} WHERE uid = '%d'", $arg));
      $output = _privatemsg_form($msg);
      $title = t("Write a new message");
      $breadcrumb = array(l(t('Home'), ''), l(t('private messages'), 'privatemsg'));
      break;
    case 'send':
    case t('Send private message'):
      if (!$edit["recipient"]) {
        $edit["recipient"] = $recipient;
      }
      $breadcrumb = array(l(t('Home'), ''), l(t('private messages'), 'privatemsg'));
      $output = _privatemsg_edit($edit);
      break;
    case t('Move to folder'):
      if ($edit["folder"] == 0 || db_result(db_query("SELECT fid FROM {privatemsg_folder} WHERE fid = '%d' AND uid = '%d'", $edit["folder"], $user->uid))) {
        // this folder belongs to him
        if ($msg) {
          foreach ($msg as $mid) {
            _privatemsg_move($mid, $edit["folder"]);
          }
          drupal_goto('privatemsg/list/'. $edit['folder']);
          break;
        }
      }

      $output = _privatemsg_list();
      break;
    case t('Delete messages'):
      if ($msg) {
        foreach ($msg as $id) {
          _privatemsg_delete($id);
        }
      }
      $output = _privatemsg_list();
      break;

    case 'delete':
      _privatemsg_delete($arg);
      $output = _privatemsg_list();
      break;

    case t('New folder'):
    case t('Add folder'):
      if ($edit["name"]) {
        // check for uniqueness
        if (!db_result(db_query("SELECT name FROM {privatemsg_folder} WHERE name = '%s' AND uid = '%d'", $edit["name"], $user->uid))) {
          db_query("INSERT INTO {privatemsg_folder} (uid, name) VALUES ('%d', '%s')", $user->uid, $edit["name"]);
        }
        $output = _privatemsg_list();
      }
      else {
        $title = t('Create new folder');
        $breadcrumb = array(l(t('Home'), ''), l('Private messages', 'privatemsg'));
        $output = _privatemsg_new_folder($edit);
      }
      break;

    case t('Delete folder'):
      // check ownership
      if (db_result(db_query("SELECT fid FROM {privatemsg_folder} WHERE fid = '%d' AND uid = '%d'", $edit["current_folder"], $user->uid))) {
        db_query("DELETE FROM {privatemsg_folder} WHERE fid = '%d'", $edit["current_folder"]);
        db_query("UPDATE {privatemsg} SET recipient_del = 1 WHERE folder = '%d'", $edit["current_folder"]);
      }

      $output = _privatemsg_list();
      break;
    case t('Empty folder'):
      $fid = $edit["current_folder"];

      if ($fid == 1) {
        db_query("UPDATE {privatemsg} SET author_del = 1 WHERE author = '%d'", $user->uid);
      }
      else if ($fid == 0 || db_result(db_query("SELECT fid FROM {privatemsg_folder} WHERE fid = '%d' AND uid = '%d'", $fid, $user->uid))) {
        // check ownership
        db_query("UPDATE {privatemsg} SET recipient_del = 1 WHERE folder = '%d' AND recipient = '%d'", $edit["current_folder"], $user->uid);
      }

      $output = _privatemsg_list();
      break;
    default;
      $output = _privatemsg_list();
      $title = t('Private messages');
      break;
  }
  drupal_set_title($title);
  drupal_set_breadcrumb($breadcrumb);
  return $output;
}

function _privatemsg_list($current_folder = 0) {
  global $user;

  if ($current_folder != 1) {
    $result = pager_query("SELECT id, subject, p.timestamp, u.uid, u.name, newmsg FROM {privatemsg} p, {users} u WHERE p.author = u.uid AND p.recipient = %d AND folder = '%s' AND p.recipient_del = 0 ORDER BY p.timestamp DESC", variable_get("privatemsg_per_page", 10), 0, NULL, $user->uid, $current_folder);

    if ($current_folder > 0) {
      $folder_name = db_result(db_query("SELECT name FROM {privatemsg_folder} WHERE fid = %d AND uid = %d", $current_folder, $user->uid));
    }
    else {
      $folder_name = t("Inbox");
    }
  }
  else {
    // sent messages
    $result = pager_query("SELECT id, subject, p.timestamp, u.uid, u.name, newmsg FROM {privatemsg} p, {users} u WHERE p.recipient = u.uid AND p.author = %d AND p.author_del = 0 ORDER BY p.timestamp DESC", variable_get("privatemsg_per_page", 10), 0, NULL, $user->uid);

    $folder_name = t("Sent messages");
  }

  $messages = array();
  while ($message = db_fetch_object($result)) {
    $messages[] = $message;
  }

  $folders[] = array(0, t("Inbox"));
  $result = db_query("SELECT fid, name FROM {privatemsg_folder} WHERE uid = %d", $user->uid);
  while ($folder = db_fetch_object($result)) {
    $folders[] = array($folder->fid, $folder->name);
  }
  $folders[] = array(1, t("Sent messages"));

  return theme("privatemsg_list", $current_folder, $messages, $folders);
}

function _privatemsg_format_folder($current, $fid, $name) {
  if ($current == $fid) {
    return "<strong>$name</strong>";
  }
  else {
    return l($name, "privatemsg/list/$fid");
  }
}

function _privatemsg_form($message = 0) {
  global $user;
  $form = array();

  if ($message) {
    // This is a reply to another message
    if (!is_object($message)) {
      $message = db_fetch_object(db_query("SELECT subject, message, u.name AS recipient FROM {privatemsg} p, {users} u WHERE u.uid = p.author AND id = '%d' AND recipient = '%d'", $message, $user->uid));

      if (!stristr($message->subject, t("Re:"))) {
        $message->subject = t("Re:").' '.$message->subject;
      }

      // quoting
      $message->message = "\n".str_replace("\n", "\n> ", "\n".$message->message);
    }
  }

  drupal_add_js(drupal_get_path('module', 'privatemsg') .'/privatemsg.js');

  $form['recipient'] = array(
      '#prefix' => '<div class="container-inline">',
      '#type' => 'textfield',
      '#title' => t("To"),
      '#default_value' => $message->recipient,
      '#size' => 50,
      '#maxlength' => 64
      );
  $result = db_query("SELECT DISTINCT(name) AS name FROM {privatemsg} p, {users} u WHERE p.author = u.uid AND recipient = '%d' AND p.timestamp > (UNIX_TIMESTAMP(NOW()) - (3600 * 24 * 30)) ORDER BY name", $user->uid);
  $contacts = array(t('Contacts'));
  while ($name = db_fetch_object($result)) {
    $contacts[] = check_plain($name->name);
  }
  $form['quick'] = array(
      '#type' => 'select',
      '#options' => drupal_map_assoc($contacts),
      '#attributes' => array('style' => 'display: none;'), // hidden unless JS is working
      '#suffix' => '</div>'
      );

  $form['subject'] = array(
      '#type' => 'textfield',
      '#title' => t("Subject"),
      '#default_value' => $message->subject,
      '#size' => 50,
      '#maxlength' => 64
      );
  $form['privatemsgbody'] = array(
      '#type' => 'textarea',
      '#title' => t("Message"),
      '#default_value' => $message->message,
      '#cols' => 80,
      '#rows' => 5
      );
  $form[] = filter_form($message->format);
  $form['op'] = array(
      '#type' => 'submit',
      '#value' => t("Send private message"),
      '#name' => 'op'
      );

  return drupal_get_form('privatemsg_message_form', $form);
}

function _privatemsg_edit($edit) {
  global $user;

  if ($edit['recipient'] == '') {
    form_set_error('recipient', t('The <em>Recipient</em> field is required.'));
    return _privatemsg_form((object)$edit);
  }
  else {
    $recipient = user_load(array('name' => $edit['recipient']));
  }
  
  if (!$recipient->uid) {
    form_set_error('recipient', t('The <em>Recipient</em> does not exist.'));
    return _privatemsg_form((object)$edit);
  }
  else if (!(isset($recipient->privatemsg_allow) ? $recipient->privatemsg_allow : 1)) {
    form_set_error('recipient', t('%name does not accept private messages.', array('%name' => $recipient->name)));
    return _privatemsg_form((object)$edit);
  }
  else if (trim($edit['subject']) == '') {
    form_set_error('subject', t('The <em>Subject</em> field is required.'));
    return _privatemsg_form((object)$edit);
  }
  if (trim($edit['privatemsgbody']) == '') {
    form_set_error('privatemsgbody', t('The <em>Message</em> field is required.'));
    return _privatemsg_form((object)$edit);
  }
  else if (array_key_exists('format', $edit) && !filter_access($edit['format'])) {
    form_set_error('format', t('The supplied input format is invalid.'));
    return _privatemsg_form((object)$edit);
  }
  else {
    $result = db_query("INSERT INTO {privatemsg} (author, recipient, subject, message, timestamp, newmsg, hostname, format) VALUES ('%d', '%d', '%s', '%s', '%d', '%d', '%s', '%d')", $user->uid, $recipient->uid, $edit['subject'], $edit['privatemsgbody'], time(), 1, getenv("REMOTE_ADDR"), $edit['format']);
    drupal_set_message(t('Message sent.'));
    drupal_goto($user->uid ? 'privatemsg' : '');
  }
}

function _privatemsg_view($message_id) {
  global $user;

  $result = db_query("SELECT p.id, u.uid, u.name, p.author, p.timestamp, p.subject, p.message, p.newmsg, p.recipient, p.format FROM {privatemsg} p, {users} u WHERE (recipient = '%d' OR author = '%d') AND author = u.uid AND id = '%d'", $user->uid, $user->uid, $message_id);

  $message = db_fetch_object($result);
  if (($message->newmsg) && ($user->uid == $message->recipient)) {
    $result = db_query("UPDATE {privatemsg} SET newmsg = 0 WHERE id = %d", $message_id);
  }

  return theme("privatemsg_view", $message);
}

function _privatemsg_delete($id) {
  global $user;

  $result = db_query("SELECT author, recipient FROM {privatemsg} WHERE (recipient = %d OR author = %d) AND id = %d", $user->uid, $user->uid, $id);

  if ($message = db_fetch_object($result)) {
    if ($message->author == $user->uid) {
      db_query("UPDATE {privatemsg} SET author_del = 1 WHERE id = '%d'", $id);
    }
    if ($message->recipient == $user->uid) {
      db_query("UPDATE {privatemsg} SET recipient_del = 1 WHERE id = '%d'", $id);
    }

    return true;
  }
  else {
    return false;
  }
}

function _privatemsg_get_new_messages($uid = 0) {
  global $user;
  static $cache = array();
  if ($uid == 0) {
    $uid = $user->uid;
  }
  if (!isset($cache[$uid])) {
    $cache[$uid] = db_result(db_query("SELECT COUNT(*) FROM {privatemsg} WHERE recipient = '%d' AND newmsg = 1 AND recipient_del = 0", $uid));
  }
  return $cache[$uid];
}

function _privatemsg_new_folder($edit) {
  $form = array();

  $form['name'] = array(
      '#type' => 'textfield',
      '#title' => t('Name'),
      '#size' => 50,
      '#maxlength' => 64
      );
  $form['op'] = array(
      '#type' => 'submit',
      '#value' => t('Add folder'),
      '#name' => 'op'
      );

  return drupal_get_form('privatemsg_new_folder', $form);
}

function _privatemsg_move($mid, $fid) {
  global $user;
  db_query("UPDATE {privatemsg} SET folder = '%d' WHERE id = '%d' AND recipient = '%d'", $fid, $mid, $user->uid);
}

/**
  @addtogroup theme_system

  Privatemsg module specific theme functions
  @{
**/

/**
 Returns content to view a private message

 @param message
**/
function theme_privatemsg_view($message) {
  global $user;

  if ($message) {
    $body = '
      <p><strong>'.t('From').':</strong> '. theme('username', $message) .'<br />
      <strong>'.t('To').':</strong> '. theme('username', user_load(array('uid' => $message->recipient))) .'<br />
      <strong>'.t('Subject').':</strong> '.check_plain($message->subject) .'<br />
      <strong>'.t('Date').':</strong> '. format_date($message->timestamp) .'</p>
       <div class="privatemsgbody">
      '. check_markup($message->message, $message->format, FALSE).
      '</div>';
    $links = array();
    if ($message->recipient == $user->uid) {
      $author = user_load(array('uid' => $message->uid));
      if ($author->uid && (isset($author->privatemsg_allow) ? $author->privatemsg_allow : 1)) {
        $links[] = l(t('Reply to this message'), "privatemsg/reply/$message->id");
      }
      else {
        $links[] = t('Sender does not accept replies');
      }
    }
    if (($message->recipient == $user->uid) || (variable_get("privatemsg_sent_status", 1))) {
      $links[] = l(t('Delete this message'), "privatemsg/delete/$message->id", array('onClick' => "return confirm('".t('Are you sure to delete this message?')."')"));
    }

    $links[] = l(t('List messages'), 'privatemsg');
    $body .= '<div class="links">'. theme('links', $links) .'</div>';
  } 
  else {
    drupal_set_message(t('Error: you can\'t read this message'), 'error');
    $body = '';
  }

  return $body;
}

/**
 Returns content to view a list of private messages

 @param current_folder
 @param messages
 @param folders
**/
function theme_privatemsg_list($current_folder, $messages, $folders) {
  $form = array();

  $extra_folders = array();
  foreach ($folders as $folder) {
    $folder_list[] = _privatemsg_format_folder($current_folder, $folder[0], $folder[1]);
    if ($folder[0] != 1 && $folder[0] != $current_folder) {
      $extra_folders[$folder[0]] = $folder[1];
    }
  }
  $out = theme('links', $folder_list);

  $form['messages'] = array(
      '#theme' => 'privatemsg_message_table',
      '#tree' => TRUE
      );
  $form['messages']['current_folder'] = array(
      '#type' => 'value',
      '#value' => $current_folder
      );
  foreach ($messages as $message) {
    if ($current_folder != 1) {
      $new = $message->newmsg;
    }
    else {
      if (variable_get("privatemsg_sent_status", 1)) {
        $new = $message->newmsg;
      }
      else {
        $new = 0;
      }
    }

    $form['messages'][$message->id] = array();
    $form['messages'][$message->id]['selected'] = array(
        '#type' => 'checkbox',
        );
    $form['messages'][$message->id]['date'] = array(
        '#type' => 'value',
        '#value' => format_date($message->timestamp, 'small')
        );
    $form['messages'][$message->id]['user'] = array(
        '#type' => 'value',
        '#value' => theme('username', $message)
        );
    $form['messages'][$message->id]['subject'] = array(
        '#type' => 'value',
        '#value' => l($message->subject, 'privatemsg/view/'. $message->id) . ($new ? (' '. theme('mark')) : '')
        );
  }
  $form[] = array('#type' => 'markup', '#value' => theme('pager', array(), variable_get('privatemsg_per_page', 10)));

  if (count($messages) > 0) {
    $form['delete_messages'] = array(
        '#type' => 'submit',
        '#value' => t('Delete messages'),
        '#name' => 'op',
        '#attributes' => array('onclick' => "return confirm('". t('Are you sure you want to delete these messages?') ."')")
        );
  }
  // folder management
  if ((count($extra_folders) > 0) && ($current_folder != 1) && (count($messages) > 0)) {
    $form['folder'] = array(
        '#prefix' => '<div class="container-inline">',
        '#type' => 'select',
        '#options' => $extra_folders
        );
    $form['move_messages'] = array(
        '#type' => 'submit',
        '#value' => t('Move to folder'),
        '#name' => 'op',
        '#suffix' => '</div>'
        );
  }

  $form[] = array('#type' => 'markup', '#value' => '<br />');

  $form['new_message'] = array(
      '#type' => 'submit',
      '#value' => t('Write a new message'),
      '#name' => 'op'
      );

  $form[] = array('#type' => 'markup', '#value' => '<br />');

  if ($current_folder > 1) {
    // you can't delete Inbox
    $form['delete_folder'] = array(
        '#type' => 'submit',
        '#value' => t('Delete folder'),
        '#name' => 'op',
        '#attributes' => array('onclick' => "return confirm('". t('Are you sure you want to delete this folder and all its messages?') ."')")
        );
  }
  if (count($messages) > 0) {
    $form['empty_folder'] = array(
        '#type' => 'submit',
        '#value' => t('Empty folder'),
        '#name' => 'op',
        '#attributes' => array('onclick' => "return confirm('". t('Are you sure you want to delete every message in this folder?') ."')")
        );
  }
  $form['current_folder'] = array(
      '#type' => 'hidden',
      '#value' => $current_folder
      );
  $form['new_folder'] = array(
      '#type' => 'submit',
      '#value' => t('New folder'),
      '#name' => 'op'
      );

  return $out . drupal_get_form('privatemsg_list_form', $form);
}

function theme_privatemsg_message_table($form) {
  $rows = array();

  foreach (element_children($form) as $key) {
    if ($key != 'current_folder') {
      $row = array();
      $row[] = form_render($form[$key]['selected']);
      $row[] = $form[$key]['date']['#value'];
      $row[] = $form[$key]['user']['#value'];
      $row[] = $form[$key]['subject']['#value'];
      $rows[] = $row;
    }
  }

  if (count($rows) == 0) {
    $rows[] = array(array('data' => t('No messages.'), 'colspan' => 4));
  }

  $header = array(
      NULL,
      t('Date'),
      ($form['current_folder']['#value'] == 1 ? t('To') : t('From')),
      t('Subject'),
      );

  return theme('table', $header, $rows);
}

/**  @} End of addtogroup theme_system **/

?>
