<?php
// $Id: cpanel.module,v 1.1.2.4 2006/05/26 13:29:10 yecarrillo Exp $

/**
 * @file
 * Syncronize users with cPanel email and FTP accounts.
 */

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

  if ($may_cache) {
  $items[] = array(
    'path' => 'admin/settings/cpanel',
    'title' => t('cpanel'),
    'description' => t('Set your cPanel server settings.'),
    'callback' => 'drupal_get_form',
    'callback arguments' => array('cpanel_admin_settings'),
    'access' => user_access('administer site configuration'),
    'type' => MENU_NORMAL_ITEM, // optional
   );
    $items[] = array('path' => 'admin/cpanel', 'title' => t('cpanel'),
      'callback' => 'cpanel_admin');

    $items[] = array('path' => 'admin/cpanel/email', 'title' => t('email'),
      'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => 1);

    $items[] = array('path' => 'admin/cpanel/ftp', 'title' => t('ftp'),
      'type' => MENU_LOCAL_TASK, 'weight' => 2);
  } else {
    
  }

  return $items;
}

/**
 * Implementation of hook_help().
 */
function cpanel_help($section) {
  switch ($section) {
      case 'admin/settings/cpanel':
      $output = '<p>' . t('Integration with cPanel (<a href="%cpanel_url">%cpanel_url</a>)', array('%cpanel_url' => 'http://www.cpanel.net/')) . '</p>';
      $output .= '<p>' . t('cPanel is a next generation web hosting control panel system. cPanel is extremely feature rich as well as include an easy to use web based interface (GUI).') . '</p>';
      $output .= '<p>' . t('cPanel is designed for the end users of your system and allows them to control everything from adding / removing email accounts to administering MySQL databases.') . '</p>';
      $output .= '<p>' . t('This module provides the factility to automatically create email and FTP accounts for every Drupal user using cPanel administrative interface.') . '</p>';
      break;
  }
  return $output;
}

/**
 * Implementation of hook_perm().
 */
function cpanel_perm() {
  return array('have email account', 'have FTP account');
}

/**
 * cpanel admin settings which are called by the _menu function here above ('callback arguments' => array('cpanel_admin_settings'),
 */
function cpanel_admin_settings() {

  $form['server'] = array(
    '#type' => 'fieldset',
    '#title' => t('cPanel server settings'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );
  $form['server']['cpanel_server'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#default_value' => variable_get('cpanel_server', 'cpanel.example.com'),
    '#size' => 25,
    '#maxlength' => 80,
    '#description' => t('Name of the cPanel administrative server.'),
  );
  $form['server']['cpanel_port'] = array(
    '#type' => 'textfield',
    '#title' => t('Port'),
    '#default_value' => variable_get('cpanel_port', '2082'),
    '#size' => 4,
    '#maxlength' => 4,
    '#description' => t('cPanel server port.'),
  );
  $form['server']['cpanel_user'] = array(
    '#type' => 'textfield',
    '#title' => t('Username'),
    '#default_value' => variable_get('cpanel_user', ''),
    '#size' => 25,
    '#maxlength' => 64,
    '#description' => t('Username for cpanel administrative account.'),
  );
  $form['server']['cpanel_pass'] = array(
    '#type' => 'password',
    '#title' => t('Password'),
    '#default_value' => variable_get('cpanel_pass', ''),
    '#size' => 25,
    '#maxlength' => 64,
    '#description' => t('User password for cpanel administrative account.'),
  );

  $form['email'] = array(
    '#type' => 'fieldset',
    '#title' => t('eMail accounts settings'),
    '#description' => t('This module automatically creates email accounts in the form <strong>username@%domain</strong> for each Drupal user.', array('%domain' => variable_get('cpanel_mail_domain', 'example.com'))),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $form['email']['cpanel_mail_enabled'] = array(
    '#type' => 'radios',
    '#title' => t('Email Accounts Creation Status'),
    '#default_value' => variable_get('cpanel_mail_enabled', 0),
    '#options' => array(t('Disabled'), t('Enabled')),
  );
  $form['email']['cpanel_mail_quota'] = array(
    '#type' => 'textfield',
    '#title' => t('Mail quota'),
    '#default_value' => variable_get('cpanel_mail_quota', 2),
    '#size' => 3,
    '#maxlength' => 2,
    '#description' => t('Amount of disk space the account can use (Mb).'),
  );
  $form['email']['cpanel_mail_domain'] = array(
    '#type' => 'textfield',
    '#title' => t('Mail domain'),
    '#default_value' => variable_get('cpanel_mail_domain', 'example.com'),
    '#size' => 40,
    '#maxlength' => 100,
    '#description' => t('Domain or subdomain under email accounts will be created. This domain <a href="http://%cpanel_server:%cpanel_port/frontend/x/subdomain/index.html">must be created previously</a>.', array('%cpanel_server' => variable_get('cpanel_server', 'cpanel.example.com'), '%cpanel_port' => variable_get('cpanel_port', '2082'))),
  );

  $form['ftp'] = array(
    '#type' => 'fieldset',
    '#title' => t('FTP accounts settings'),
    '#description' => t('You users may need to transfer files from a computer to the computer that contains your web site. If they need to transfer may files, using a <a href="http://en.wikipedia.org/wiki/File_Transfer_Protocol">FTP</a> client is the quickest way to accomplish this. This module automatically creates <a href="http://en.wikipedia.org/wiki/File_Transfer_Protocol">FTP</a> accounts in the form <strong>username@%domain</strong> which allow users to access the folder <strong>/home/%cpanel_user/public_html%cpanel_ftp_subrootusername</strong> with a <a href="http://en.wikipedia.org/wiki/File_Transfer_Protocol">FTP</a> client.', array('%domain' => variable_get('cpanel_ftp_domain', 'example.com'), '%cpanel_user' => variable_get('cpanel_user', 'user'), '%cpanel_ftp_subroot' => variable_get('cpanel_ftp_subroot', '/'))),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $form['ftp']['cpanel_ftp_enabled'] = array(
    '#type' => 'radios',
    '#title' => t('FTP Accounts Creation Status'),
    '#default_value' => variable_get('cpanel_ftp_enabled', 0),
    '#options' => array(t('Disabled'), t('Enabled')),
  );
  $form['ftp']['cpanel_ftp_quota'] = array(
    '#type' => 'textfield',
    '#title' => t('FTP quota'),
    '#default_value' => variable_get('cpanel_ftp_quota', 10),
    '#size' => 3,
    '#maxlength' => 2,
    '#description' => t('Amount of disk space the account can use (Mb).'),
  );
  $form['ftp']['cpanel_ftp_subroot'] = array(
    '#type' => 'textfield',
    '#title' => t('FTP directory root'),
    '#default_value' => variable_get('cpanel_ftp_subroot', '/'),
    '#size' => 40,
    '#maxlength' => 100,
    '#description' => t('Directory which the account will have access under <i>/home/%cpanel_user/public_html</i> folder. This folder <a href="http://%cpanel_server:%cpanel_port/frontend/x/files/index.html">must be created previously</a>.', array('%cpanel_user' => variable_get('cpanel_user', 'user'), '%cpanel_server' => variable_get('cpanel_server', 'cpanel.example.com'), '%cpanel_port' => variable_get('cpanel_port', '2082'))),
  );
  $form['ftp']['cpanel_ftp_domain'] = array(
    '#type' => 'textfield',
    '#title' => t('FTP global domain'),
    '#default_value' => variable_get('cpanel_ftp_domain', 'example.com'),
    '#size' => 40,
    '#maxlength' => 100,
    '#description' => t('Global domain of your website.'),
  );
  
   return system_settings_form($form);
}

/**
 * Implementation of hook_user
 */
function cpanel_user($type, &$edit, &$user, $category = NULL) {
  
  $cpanel_mail_domain = variable_get('cpanel_mail_domain', '');
  $cpanel_ftp_domain = variable_get('cpanel_ftp_domain', '');
  $cpanel_username = cpanel_formatname($user->name);

  $form['cpanel'] = array(
    '#type' => 'fieldset',
    '#title' => t('eMail & FTP accounts'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
    '#weight' => 10,
  );
  
  if ($cpanel_mail_domain != '' && variable_get('cpanel_mail_enabled', 0) && user_access('have email account', $user)) {
    $form['cpanel']['cpanel_email'] = array(
      '#type' => 'checkbox',
      '#title' => t('Create an email account with my username'),
      '#return_value' => 1,
      '#default_value' => $edit['cpanel_email'],
      '#description' => t('Check to create an email account with your username. You can connect to <i>%server</i> with your <a href="http://en.wikipedia.org/wiki/Internet_Message_Access_Protocol" target="_blank">IMAP</a>/<a href="http://en.wikipedia.org/wiki/Post_Office_Protocol" target="_blank">POP3</a> client.', array('%server' => 'mail.' . $cpanel_ftp_domain)),
    );
    $form['cpanel']['cpanel_email_info'] = array(
      '#value' => '<div align="center"><strong>' . $cpanel_username . '@' . $cpanel_mail_domain . '</strong></div>',
    );
  } 
  if ($cpanel_ftp_domain != '' && variable_get('cpanel_ftp_enabled', 0) && user_access('have FTP account', $user)) {
    $form['cpanel']['cpanel_ftp'] = array(
      '#type' => 'checkbox',
      '#title' => t('Create a FTP account with my username'),
      '#return_value' => 1,
      '#default_value' => $edit['cpanel_ftp'],
      '#description' => t('Check to create a FTP account with your username. You can connect to <i>%server</i> with your <a href="http://en.wikipedia.org/wiki/File_Transfer_Protocol" target="_blank">FTP</a> client.', array('%server' => 'ftp.' . $cpanel_ftp_domain)),
    );
    $form['cpanel']['cpanel_ftp_info'] = array(
      '#value' => '<div align="center"><strong>' . $cpanel_username . '@' . $cpanel_ftp_domain . '</strong> (<a href="' . variable_get('cpanel_ftp_subroot', '/') . $cpanel_username . '" target="blank">' . variable_get('cpanel_ftp_subroot', '/') . $cpanel_username . '</a>) </div>',
    );
  }

  if ($type == 'form' && $category == 'account' && count($form, COUNT_RECURSIVE) > 5) {
    // when user tries to edit his own data
    return $form;
  }
  if ($type == 'validate') {
    // validate user data editing
    return array('cpanel_email' => $edit['cpanel_email'], 'cpanel_ftp' => $edit['cpanel_ftp']);
  }
  if ($type == 'insert') {
    //Create an account when a new user is inserted
    if ($cpanel_mail_domain != '' && variable_get('cpanel_mail_enabled', 0) && user_access('have email account', $user)) {
      $ret = _cpanel_handle_request('/frontend/x/mail/doaddpop.html', array('email' => $cpanel_username, 'password' => $edit['pass'], 'domain' => $cpanel_mail_domain, 'quota' => variable_get('cpanel_mail_quota', 2)));
      
      if (!$ret) {
        watchdog('user', t('Error creating cPanel email account <em>%username@%domain</em>', array('%username' => $cpanel_username,'%domain' => $cpanel_mail_domain)), WATCHDOG_ERROR);
      } else {
        watchdog('user', t('Created cPanel email account <em>%username@%domain</em> with password : %pass at %date' , array('%username' => $cpanel_username, '%domain' => $cpanel_mail_domain, '%pass' => $edit['pass'],'%date' => date("H:i:s"))), WATCHDOG_NOTICE);
      }
    }
    if ($cpanel_ftp_domain != '' && variable_get('cpanel_ftp_enabled', 0) && user_access('have FTP account', $user)) {
      $ret = _cpanel_handle_request('/frontend/x/ftp/doaddftp.html', array('login' => $cpanel_username, 'password' => $edit['pass'], 'homedir' => variable_get('cpanel_ftp_subroot', '/') . $cpanel_username, 'quota' => variable_get('cpanel_ftp_quota', 2)));
      
      if (!$ret) {
        watchdog('user', t('Error creating cPanel FTP account <em>%username@%domain</em>', array('%username' => $cpanel_username,'%domain' => $cpanel_ftp_domain)), WATCHDOG_ERROR);
      } else {
        watchdog('user', t('Created cPanel FTP account <em>%username@%domain</em> with password : %pass at %date' , array('%username' => $cpanel_username, '%domain' => $cpanel_ftp_domain, '%pass' => $edit['pass'],'%date' => date("H:i:s"))), WATCHDOG_NOTICE);
      }
    }
  }
  if ($type == 'update' && $account = user_load(array('uid' => $user->uid, 'status' => 1))) {  
    if ($cpanel_mail_domain != '' && variable_get('cpanel_mail_enabled', 0) && user_access('have email account', $user)) {
        if (isset($account->cpanel_email) && $account->cpanel_email) {
          if ($edit['cpanel_email'] && $edit['pass'] != '') {
            $ret = _cpanel_handle_request('/frontend/x/mail/dopasswdpop.html', array('email' => $cpanel_username, 'password' => $edit['pass'], 'domain' => $cpanel_mail_domain, 'quota' => variable_get('cpanel_mail_quota', 2)));
            if (!$ret) {
              watchdog('user', t('Error updating password fo cPanel email account <em>%username@%domain</em>', array('%username' => $cpanel_username, '%domain' => $cpanel_mail_domain)), WATCHDOG_ERROR);
            } else {
              watchdog('user', t('Password updated for cPanel email account <em>%username@%domain</em> with password : %pass at %date' , array('%username' => $cpanel_username, '%domain' => $cpanel_mail_domain, '%pass' => $edit['pass'],'%date' => date("H:i:s"))), WATCHDOG_NOTICE);
            }
          } elseif (!$edit['cpanel_email']) {
            $ret = _cpanel_handle_request('/frontend/x/mail/realdelpop.html', array('email' => $cpanel_username, 'domain' => $cpanel_mail_domain));
            if (!$ret) {
              watchdog('user', t('Error deleting cPanel email account <em>%username@%domain</em>', array('%username' => $cpanel_username, '%domain' => $cpanel_mail_domain)), WATCHDOG_ERROR);
            } else {
              watchdog('user', t('Deleted cPanel email account <em>%username@%domain</em>' , array('%username' => $cpanel_username, '%domain' => $cpanel_mail_domain)), WATCHDOG_NOTICE);            	
            }
          }
        } else {
          if ($edit['cpanel_email']) {
            $ret = _cpanel_handle_request('/frontend/x/mail/doaddpop.html', array('email' => $cpanel_username, 'password' => $edit['pass'] == '' ? $user->name : $edit['pass'], 'domain' => $cpanel_mail_domain, 'quota' => variable_get('cpanel_mail_quota', 2)));
            if (!$ret) {
              watchdog('user', t('Error creating cPanel email account <em>%username@%domain</em>', array('%username' => $cpanel_username, '%domain' => $cpanel_mail_domain)), WATCHDOG_ERROR);
            } else {
              watchdog('user', t('Created cPanel email account <em>%username@%domain</em> with password : %pass at %date' , array('%username' => $cpanel_username, '%domain' => $cpanel_mail_domain, '%pass' => $edit['pass'] == '' ? $user->name : $edit['pass'], '%date' => date("H:i:s"))), WATCHDOG_NOTICE);
            }
          }      
        }
    }
    if ($cpanel_ftp_domain != '' && variable_get('cpanel_ftp_enabled', 0) && user_access('have FTP account', $user)) {
        if (isset($account->cpanel_ftp) && $account->cpanel_ftp) {
          if ($edit['cpanel_ftp'] && $edit['pass'] != '') {
            $ret = _cpanel_handle_request('/frontend/x/ftp/dopasswdftp.html', array('acct' => $cpanel_username, 'password' => $edit['pass']));
            if (!$ret) {
              watchdog('user', t('Error updating password fo cPanel FTP account <em>%username@%domain</em>', array('%username' => $cpanel_username, '%domain' => $cpanel_ftp_domain)), WATCHDOG_ERROR);
            } else {
              watchdog('user', t('Password updated for cPanel FTP account <em>%username@%domain</em> with password : %pass at %date' , array('%username' => $cpanel_username, '%domain' => $cpanel_ftp_domain, '%pass' => $edit['pass'],'%date' => date("H:i:s"))), WATCHDOG_NOTICE);
            }
          } elseif (!$edit['cpanel_ftp']) {
            $ret = _cpanel_handle_request('/frontend/x/ftp/realdodelftp.html', array('login' => $cpanel_username));
            if (!$ret) {
              watchdog('user', t('Error deleting cPanel FTP account <em>%username@%domain</em>', array('%username' => $cpanel_username, '%domain' => $cpanel_ftp_domain)), WATCHDOG_ERROR);
            } else {
              watchdog('user', t('Deleted cPanel FTP account <em>%username@%domain</em>' , array('%username' => $cpanel_username, '%domain' => $cpanel_ftp_domain)), WATCHDOG_NOTICE);            	
            }
          }
        } else {
          if ($edit['cpanel_ftp']) {
            $ret = _cpanel_handle_request('/frontend/x/ftp/doaddftp.html', array('login' => $cpanel_username, 'password' => $edit['pass'] == '' ? $user->name : $edit['pass'], 'homedir' => variable_get('cpanel_ftp_subroot', '/') . $cpanel_username, 'quota' => variable_get('cpanel_ftp_quota', 2)));
            if (!$ret) {
              watchdog('user', t('Error creating cPanel FTP account <em>%username@%domain</em>', array('%username' => $cpanel_username, '%domain' => $cpanel_ftp_domain)), WATCHDOG_ERROR);
            } else {
              watchdog('user', t('Created cPanel FTP account <em>%username@%domain</em> with password : %pass at %date' , array('%username' => $cpanel_username, '%domain' => $cpanel_ftp_domain, '%pass' => $edit['pass'] == '' ? $user->name : $edit['pass'], '%date' => date("H:i:s"))), WATCHDOG_NOTICE);
            }
          }      
        }
    }
  }
  if ($type == 'delete' && $account = user_load(array('uid' => $user->uid, 'status' => 1))) {
    if ($cpanel_mail_domain != '' && variable_get('cpanel_mail_enabled', 0) && user_access('have email account', $user)) {
      if (isset($account->cpanel_email) && $account->cpanel_email) {
        $ret = _cpanel_handle_request('/frontend/x/mail/realdelpop.html', array('email' => $cpanel_username, 'domain' => $cpanel_mail_domain));
        if (!$ret) {
          watchdog('user', t('Error deleting cPanel email account <em>%username@%domain</em>', array('%username' => $cpanel_username, '%domain' => $cpanel_mail_domain)), WATCHDOG_ERROR);
        } else {
          watchdog('user', t('Deleted cPanel email account <em>%username@%domain</em>' , array('%username' => $cpanel_username, '%domain' => $cpanel_mail_domain)), WATCHDOG_NOTICE);            	
        }
      }
    }
    if ($cpanel_ftp_domain != '' && variable_get('cpanel_ftp_enabled', 0) && user_access('have FTP account', $user)) {
      if (isset($account->cpanel_ftp) && $account->cpanel_ftp) {
        $ret = _cpanel_handle_request('/frontend/x/ftp/realdodelftp.html', array('login' => $cpanel_username));
        if (!$ret) {
          watchdog('user', t('Error deleting cPanel FTP account <em>%username@%domain</em>', array('%username' => $cpanel_username, '%domain' => $cpanel_ftp_domain)), WATCHDOG_ERROR);
        } else {
          watchdog('user', t('Deleted cPanel FTP account <em>%username@%domain</em>' , array('%username' => $cpanel_username, '%domain' => $cpanel_ftp_domain)), WATCHDOG_NOTICE);            	
        }
      }
    }
  }
}

/**
 * Menu callback; dispatches to the proper cPanel administration function.
 */
function cpanel_admin() {
  $op = $_POST['op'];
  $edit = $_POST['edit'];

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

  switch ($op) {

    case t('Change Email Quota'):
    case t('Change Email Aging'):
    case t('Delete Email Accounts'):
      cpanel_save_site($op, $edit);
      drupal_goto('admin/cpanel');  
      break;

    case t('Change FTP Quota'):
    case t('Delete FTP Accounts'):
      cpanel_save_site($op, $edit);
      drupal_goto('admin/cpanel/ftp');  
      break;

    default:
      $output = cpanel_form_site($op);
$output = drupal_get_form('cpanel_form_site', $op);	  
  }
  
  return $output;
}

/**
 * Massive Form
 */
function cpanel_form_site($op) {

  switch ($op) {
    case t('ftp'):  
      $form['ftp_quota'] = array(
        '#type' => 'fieldset',
        '#title' => t('Massive quota change'),
        '#description' => t('A FTP quota is the amount of space reserved on the server to house files.'),
        '#weight' => 0,
      );
      $form['ftp_quota']['cpanel_ftp_quota'] = array(
        '#type' => 'textfield',
        '#title' => t('FTP quota'),
        '#default_value' => variable_get('cpanel_ftp_quota', 2),
        '#size' => 3,
        '#maxlength' => 2,
        '#description' => t('FTP quota for each user account (Mb).'),
      );
      $form['ftp_quota']['op'] = array(
        '#type' => 'button',
        '#value' => t('Change FTP Quota'),
        '#button_type' => 'submit',
      );

      $form['ftp_delete'] = array(
        '#type' => 'fieldset',
        '#title' => t('Massive accounts deletion'),
        '#weight' => 1,
      );
      $form['ftp_delete']['op'] = array(
        '#type' => 'button',
        '#value' => t('Delete FTP Accounts'),
        '#button_type' => 'submit',
      );
      break;
      
    default:
      $form['email_quota'] = array(
        '#type' => 'fieldset',
        '#title' => t('Massive quota change'),
        '#description' => t('A mail quota is the amount of space reserved on the server to house email messages.'),
        '#weight' => 0,
      );
      $form['email_quota']['cpanel_mail_quota'] = array(
        '#type' => 'textfield',
        '#title' => t('Mail quota') . $op,
        '#default_value' => variable_get('cpanel_mail_quota', 2),
        '#size' => 3,
        '#maxlength' => 2,
        '#description' => t('Mailbox quota for each user account (Mb).'),
      );
      $form['email_quota']['op'] = array(
        '#type' => 'button',
        '#value' => t('Change Email Quota'),
        '#button_type' => 'submit',
      );

      $form['email_aging'] = array(
        '#type' => 'fieldset',
        '#title' => t('Massive aging change'),
        '#description' => t('Mail aging is the process in which e-mails will be removed from the server automatically, upon successful log out of a pop3 session. This deletion will only occur if the messages are older then a specified amount of days.'),
        '#weight' => 1,
      );      
      $form['email_aging']['cpanel_aging_days'] = array(
        '#type' => 'textfield',
        '#title' => t('Days'),
        '#default_value' => variable_get('cpanel_aging_days', 8),
        '#size' => 3,
        '#maxlength' => 2,
        '#description' => t('Number of days to keep e-mail.'),
      );
      $form['email_aging']['op'] = array(
        '#type' => 'button',
        '#value' => t('Change Email Aging'),
        '#button_type' => 'submit',
      );
    
      $form['email_delete'] = array(
        '#type' => 'fieldset',
        '#title' => t('Massive accounts deletion'),
        '#weight' => 2,
      );
      $form['email_delete']['op'] = array(
        '#type' => 'button',
        '#value' => t('Delete Email Accounts'),
        '#button_type' => 'submit',
      );

  }
    return $form;  
}

/**
 * Massive Operations
 */
function cpanel_save_site($op, $edit) {

  $cpanel_mail_domain = variable_get('cpanel_mail_domain', '');
  $cpanel_ftp_domain = variable_get('cpanel_ftp_domain', '');

  switch ($op) {
    case t('Delete Email Accounts'):
      $result = db_query("SELECT * FROM {users}");
      while ($user = db_fetch_object($result)) {
        $cpanel_username = cpanel_formatname($user->name);
        $account = user_load(array('uid' => $user->uid, 'status' => 1));
        if (isset($account->cpanel_email) && $account->cpanel_email) {
          $ret = _cpanel_handle_request('/frontend/x/mail/realdelpop.html', array('email' => $cpanel_username, 'domain' => $cpanel_mail_domain));
          //TODO: Set cpanel_email to 0 in user data field
          if (!$ret) {
            drupal_set_message(t('Error deleting cPanel email account <em>%username@%domain</em>', array('%username' => $cpanel_username, '%domain' => $cpanel_mail_domain)));
            watchdog('user', t('Error deleting cPanel email account <em>%username@%domain</em>', array('%username' => $cpanel_username, '%domain' => $cpanel_mail_domain)), WATCHDOG_ERROR);
          } else {
            drupal_set_message(t('Deleted cPanel email account <em>%username@%domain</em>' , array('%username' => $cpanel_username, '%domain' => $cpanel_mail_domain)));         
            watchdog('user', t('Deleted cPanel email account <em>%username@%domain</em>' , array('%username' => $cpanel_username, '%domain' => $cpanel_mail_domain)), WATCHDOG_NOTICE);            	
          }
        }
      }
      drupal_set_message(t('cPanel email accounts deleted.'));
      break;

    case t('Change Email Aging'):
      $result = db_query("SELECT * FROM {users}");
      while ($user = db_fetch_object($result)) {
        $cpanel_username = cpanel_formatname($user->name);
        $account = user_load(array('uid' => $user->uid, 'status' => 1));
        if (isset($account->cpanel_email) && $account->cpanel_email) {
          $ret = _cpanel_handle_request('/frontend/x/mail/doaging.html', array('user' => $cpanel_username . '@' . $cpanel_mail_domain, 'numdays' => $edit['cpanel_aging_days']));
          if (!$ret) {
            drupal_set_message(t('Error changing aging of cPanel email account <em>%username@%domain</em>', array('%username' => $cpanel_username, '%domain' => $cpanel_mail_domain)));
            watchdog('user', t('Error changing aging of cPanel email account <em>%username@%domain</em>', array('%username' => $cpanel_username, '%domain' => $cpanel_mail_domain)), WATCHDOG_ERROR);
          } else {
            drupal_set_message(t('Aging changed for cPanel email account <em>%username@%domain</em>' , array('%username' => $cpanel_username, '%domain' => $cpanel_mail_domain)));         
            watchdog('user', t('Aging changed for cPanel email account <em>%username@%domain</em>' , array('%username' => $cpanel_username, '%domain' => $cpanel_mail_domain)), WATCHDOG_NOTICE);            	
          }
        }
      }
      break;

    case t('Change Email Quota'):
      $result = db_query("SELECT * FROM {users}");
      while ($user = db_fetch_object($result)) {
        $cpanel_username = cpanel_formatname($user->name);
        $account = user_load(array('uid' => $user->uid, 'status' => 1));
        if (isset($account->cpanel_email) && $account->cpanel_email) {
          $ret = _cpanel_handle_request('/frontend/x/mail/doeditquota.html', array('email' => $cpanel_username, 'domain' => $cpanel_mail_domain, 'quota' => $edit['cpanel_mail_quota']));
          if (!$ret) {
            drupal_set_message(t('Error changing quota for cPanel email account <em>%username@%domain</em>', array('%username' => $cpanel_username, '%domain' => $cpanel_mail_domain)));
            watchdog('user', t('Error changing quota for cPanel email account <em>%username@%domain</em>', array('%username' => $cpanel_username, '%domain' => $cpanel_mail_domain)), WATCHDOG_ERROR);
          } else {
            drupal_set_message(t('Quota changed for cPanel email account <em>%username@%domain</em>' , array('%username' => $cpanel_username, '%domain' => $cpanel_mail_domain)));
            watchdog('user', t('Quota changed for cPanel email account <em>%username@%domain</em>' , array('%username' => $cpanel_username, '%domain' => $cpanel_mail_domain)), WATCHDOG_NOTICE);            	
          }
        }
      }
      break;

    case t('Delete FTP Accounts'):
      $result = db_query("SELECT * FROM {users}");
      while ($user = db_fetch_object($result)) {
        $cpanel_username = cpanel_formatname($user->name);
        $account = user_load(array('uid' => $user->uid, 'status' => 1));
        if (isset($account->cpanel_ftp) && $account->cpanel_ftp) {
          $ret = _cpanel_handle_request('/frontend/x/ftp/realdodelftp.html', array('login' => $cpanel_username));
          if (!$ret) {
            drupal_set_message(t('Error deleting cPanel FTP account <em>%username@%domain</em>', array('%username' => $cpanel_username, '%domain' => $cpanel_ftp_domain)));
            watchdog('user', t('Error deleting cPanel FTP account <em>%username@%domain</em>', array('%username' => $cpanel_username, '%domain' => $cpanel_ftp_domain)), WATCHDOG_ERROR);
          } else {
            drupal_set_message(t('Deleted cPanel FTP account <em>%username@%domain</em>' , array('%username' => $cpanel_username, '%domain' => $cpanel_ftp_domain)));         
            watchdog('user', t('Deleted cPanel FTP account <em>%username@%domain</em>' , array('%username' => $cpanel_username, '%domain' => $cpanel_ftp_domain)), WATCHDOG_NOTICE);            	
          }
        }
      }
      drupal_set_message(t('cPanel FTP accounts deleted.'));
      break;

    case t('Change FTP Quota'):
      $result = db_query("SELECT * FROM {users}");
      while ($user = db_fetch_object($result)) {
        $cpanel_username = cpanel_formatname($user->name);
        $account = user_load(array('uid' => $user->uid, 'status' => 1));
        if (isset($account->cpanel_ftp) && $account->cpanel_ftp) {
          $ret = _cpanel_handle_request('/frontend/x/ftp/doeditquota.html', array('acct' => $cpanel_username, 'quota' => $edit['cpanel_ftp_quota']));
          if (!$ret) {
            drupal_set_message(t('Error changing quota for cPanel FTP account <em>%username@%domain</em>', array('%username' => $cpanel_username, '%domain' => $cpanel_ftp_domain)));
            watchdog('user', t('Error changing quota for cPanel FTP account <em>%username@%domain</em>', array('%username' => $cpanel_username, '%domain' => $cpanel_ftp_domain)), WATCHDOG_ERROR);
          } else {
            drupal_set_message(t('Quota changed for cPanel FTP account <em>%username@%domain</em>' , array('%username' => $cpanel_username, '%domain' => $cpanel_ftp_domain)));
            watchdog('user', t('Quota changed for cPanel FTP account <em>%username@%domain</em>' , array('%username' => $cpanel_username, '%domain' => $cpanel_ftp_domain)), WATCHDOG_NOTICE);            	
          }
        }
      }
      break;
    
  }
  return $op;
}

/******************************************************************
 * Other functions
 ******************************************************************/

function cpanel_formatname($username) {
  return eregi_replace("[^a-z0-9_-]", "", strtolower($username));
}

function _cpanel_handle_request($path, $params) {
  
  foreach ($params as $key => $value) {
    $request .= $key . '=' . $value . '&';
  }

  // Generate POST headers.
  $headers = array();
  if (variable_get('cpanel_user', '') != '') {
    $headers['Authorization'] = 'Basic ' . base64_encode(variable_get('cpanel_user', '') . ':' . variable_get('cpanel_pass', ''));
  }
  $headers['Content-Type'] = 'application/x-www-form-urlencoded';

  // Request
  $result = drupal_http_request('http://' . variable_get('cpanel_server', '') . ':' . variable_get('cpanel_port', '2082') . $path . '?' . $request, $headers, 'POST');
  
  // Process HTTP response code.
  switch ($result->code) {
    case 304:
      return false;
      break;
    
    case 301:
      return false;
      break;
    
    case 200:
    case 302:
    case 307:
      return true;
      break;
    default:
      return false;
  }
}