<?php
//version 1.0
//change the following path if you have moved the Accounting.php.inc file into your home dir path
$accountingPath = "/usr/local/cpanel/Cpanel/Accounting.php.inc";

//do not change anything below here unless you know what you are doing
if (@is_file($accountingPath)) {
    require_once $accountingPath;
} else {
    require_once dirname(__FILE__).'/Accounting.php.inc';
}

include_once ("common/mailfunctions.php");
require_once dirname(__FILE__).'/../../../classes/error_ce.php';

/*****************************************************************/
// function plugin_cpanel_variables - required function
/*****************************************************************/
function plugin_cpanel_variables($args){
    /* Specification
          itemkey     - used to identify variable in your other functions
          type        - text,textarea,yesno,password,hidden ( type hidden are variables used by CE and are required )
          description - description of the variable, displayed in ClientExec
    */

    $variables = array (
               "Name" => array (
                                    "type"=>"hidden",
                                    "description"=>"Used By CE to show plugin - must match how you call the action function names",
                                    "value"=>"CPanel"
                                   ),
               "Description" => array (
                                    "type"=>"hidden",
                                    "description"=>"Description visable by admin in server settings",
                                    "value"=>"CPanel control panel integration"
                                   ),
               "Username" => array (
                                    "type"=>"text",
                                    "description"=>"Username used to connect to server",
                                    "value"=>""
                                   ),
               "Access Hash" => array (
                                    "type"=>"textarea",
                                    "description"=>"Password used to connect to server",
                                    "value"=>""
                                   ),
               "Use SSL" => array (
                                    "type"=>"yesno",
                                    "description"=>"Set NO if you do not have PHP compiled with cURL.  YES if your PHP is compiled with cURL<br><b>NOTE:</b>It is suggested that you keep this as YES",
                                    "value"=>"1"
                                   ),
               "Failure E-mail" => array (
                                    "type"=>"text",
                                    "description"=>"E-mail address Cpanel error messages will be sent to",
                                    "value"=>""
                                    ),
               "Actions" => array (
                                    "type"=>"hidden",
                                    "description"=>"current actions that are active for this plugin_per server",
                                    "value"=>"Create,Delete,Update,Suspend,UnSuspend"
                                   ),
                'reseller'  => array(
                                    'type'          => 'hidden',
                                    'description'   => 'Whether this server plugin can set reseller accounts',
                                    'value'         => '1',
                                    ),
                'reseller_acl_fields' => array(
                                    'type'          => 'hidden',
                                    'description'   => 'ACL field for reseller account',
                                    'value'         => array(
                                                        'acl-rslimit-disk'      => 'Disk space in MB<br />(If you wish to set Disk space AND Bandwitdh as unlimited, leave this field empty.<br />if you wish to limit Bandwidth but not Disk Space, enter a very large number here)',
                                                        'acl-rsolimit-disk'     => 'Disk space overselling allowed',
                                                        'acl-rslimit-bw'        => 'Bandwidth in MB<br />(If you wish to set Disk space AND Bandwitdh as unlimited, leave this field empty.<br />if you wish to limit Disk Space but not Bandwidth, enter a very large number here)',
                                                        'acl-rsolimit-bw'       => 'Bandwidth overselling allowed',
                                                        'acl-list-accts'        => 'List Accounts',
                                                        'acl-show-bandwidth'    => 'View Account Bandwidth Usage',
                                                        'acl-create-acct'       => 'Account Creation',
                                                        'acl-edit-account'      => 'Account Modification',
                                                        'acl-suspend-acct'      => 'Account Suspension',
                                                        'acl-kill-acct'         => 'Acccount Termination',
                                                        'acl-upgrade-account'   => 'Account Upgrades',
                                                        'acl-limit-bandwidth'   => 'Bandwidth Limiting Modification',
                                                        'acl-edit-mx'           => 'Edit MX Entries',
                                                        'acl-frontpage'         => 'Enabling/Disabling FrontPage Extensions',
                                                        'acl-mod-subdomains'    => 'Enabling/Disabling SubDomains',
                                                        'acl-passwd'            => 'Password Modification',
                                                        'acl-quota'             => 'Quota Modification',
                                                        'acl-res-cart'          => 'Reset Shopping Cart',
                                                        'acl-ssl-gencrt'        => 'SSL CSR/CRT Generator',
                                                        'acl-ssl'               => 'SSL Site Management',
                                                        'acl-demo-setup'        => 'Turn an account into a demo account',
                                                        'acl-rearrange-accts'   => 'Rearrange Accounts',
                                                        'acl-clustering'        => 'Clustering',
                                                        'acl-create-dns'        => 'Add DNS',
                                                        'acl-edit-dns'          => 'Edit DNS',
                                                        'acl-park-dns'          => 'Park DNS',
                                                        'acl-kill-dns'          => 'Remove DNS',
                                                        'acl-add-pkg'           => 'Add/Remove Packages',
                                                        'acl-edit-pkg'          => 'Edit Packages',
                                                        'acl-add-pkg-shell'     => 'Allow Creation of Packages With Shell Access',
                                                        'acl-allow-unlimited-disk-pkgs' => 'Allow Creation of Packages with Unlimited Diskspace',
                                                        'acl-allow-unlimited-pkgs' => 'Allow Creation of Packages with Unlimited Features',
                                                        'acl-add-pkg-ip'        => 'Allow Creation of Packages With a Dedicated IP',
                                                        'acl-allow-addoncreate' => 'Allow Creation of Packages with Addon Domains',
                                                        'acl-allow-parkedcreate'=> 'Allow Creation of Packages With Parked Domains',
                                                        'acl-onlyselfandglobalpkgs' => 'Disallow creation of accounts with packages that are not global or not owned by this user',
                                                        'acl-disallow-shell'    => 'Never allow creation of accounts with shell access',
                                                        'acl-stats'             => 'View Account Statistics',
                                                        'acl-status'            => 'View Server Status',
                                                        'acl-restart'           => 'Restart Services',
                                                        'acl-mailcheck'         => 'Mail Trouble Shooter',
                                                        'acl-restftp'           => 'Resync Ftp Passwords',
                                                        'acl-news'              => 'News Modification',
                                                        // keep this one last because it's too powerful, and better think about users security
                                                        'acl-all'               => 'All Features (root access)',
                                                    ),
                                    ),
        'package_addons' => array(
            'type'          => 'hidden',
            'description'   => 'Supported signup addons variables',
            'value'         => array(
                'DISKSPACE', 'BANDWIDTH', 'SSL'
            ),
        ),
    );
    return $variables;
}

//function to do the checks necessary for this plugin
function DoNecessaryChecks(){
    $errormsg = "";
    if(!file_exists($accountingPath))
    {
        $errormsg = "The required file Accounting.php.inc could not be found";
    }
    return $errormsg;
}

/**this function checks to see if the plan exists in whm
* @parm $plan the plan clientexec is going to try to create on WHM
* @return boolean true if the package exists on whm, an error string otherwise.
*/
function CheckCpanelPlan($plan, $args){
    $whmPks = _cpanel_callFunction('listpkgs', array($args['ServerHostName'],
                                                     $args['plugin_cpanel_Username'],
                                                     $args['plugin_cpanel_Access_Hash'],
                                                     $args['plugin_cpanel_Use_SSL']));
    if (!is_array($whmPks)) {
        return "Connection to server ".$args['ServerHostName']." failed.";
    } elseif (array_key_exists($plan, $whmPks)) {
        return true;
    } else {
        foreach (array_keys($whmPks) as $line){
            if (strstr($line, "Web Host Manager Login") !== false) {
                return "Login to server failed.";
            }
        }
        return "The package was not found on the server.";
    }
}

function GetCpanelPlan($args){
    $pkgs = _cpanel_callFunction('listpkgs', array($args['ServerHostName'],
                                                   $args['plugin_cpanel_Username'],
                                                   $args['plugin_cpanel_Access_Hash'],
                                                   $args['plugin_cpanel_Use_SSL']));
    if (!is_array($pkgs)) return "";
    $plansList = '';
    foreach (array_keys($pkgs) as $plan)
    {
        $plansList .= $plan . "\n\r";
    }
    return $plansList;
}

function Plugin_cpanel_CreateUsername($args){

      if (!function_exists('listaccts')) {
          return $args['DomainUsername'];
      }

      $bolCheckCpanelServer=true;
      //function used to determine how you want CE to create usernames on this server
      //if it does not matter on this server you can return $args['DomainUsername']
      $accts = _cpanel_callFunction('listaccts', array($args['ServerHostName'],
                                                       $args['plugin_cpanel_Username'],
                                                       $args['plugin_cpanel_Access_Hash'],
                                                       $args['plugin_cpanel_Use_SSL']));

      //check to see if the username passed is valid already
      if ($args['PassedUserName'] != "") {
         $username = str_replace(".", "", $args['PassedUserName']);
         $bolCheckCpanelServer=false;
      } else {
         $username = str_replace(".", "", $args['DomainName']);
         $bolCheckCpanelServer=true;
      }

      // Usernames cannot begin with a number.
      $username = preg_replace("/^\d*/", '', $username);

      $username = substr($username,0,8);
      $username = str_replace('-','',$username); //make sure there are no - characters in the username

      if ($bolCheckCpanelServer) {
          while(count($accts["$username"]) > 0) {
               $cnt = 1;
               $username = substr($username,0,7).$cnt++;
          }
      }
      return $username;
}

//TODO: need to define a way to get package attributes

//plugin function called after new account is activated ( approved )
function Plugin_cpanel_Create($args){
    if (!$args['plugin_cpanel_Create'] == 1) return;
    if ($args['PackageNameOnServer'] == null) return; //the package is not a cpanel package

    // package add-ons handling
    if (isset($args['package_addons']['DISKSPACE'])) {
        $args['acl-rslimit-disk'] += ((int)$args['package_addons']['DISKSPACE']);
    }
    if (isset($args['package_addons']['BANDWIDTH'])) {
        $args['acl-rslimit-bw'] += ((int)$args['package_addons']['BANDWIDTH']) * 1024; // Convert from Gigs to MB
    }
    if (isset($args['package_addons']['SSL']) && $args['package_addons']['SSL'] == 1) {
        $args['acl-ssl'] = 1;
    }

    $errormsg="";
    if (!function_exists('listpkgs')) {
        $errormsg = "Cpanel Account Creation Failure for {$args['DomainName']}: CPanel not found in this server.";
        $GLOBALS['logger']->log(5, "plugin_cpanel::create::error: ".$errormsg);
        return new Error_CE(200, $errormsg);
    }

    if (($return = CheckCpanelPlan($args['PackageNameOnServer'], $args)) !== true)
    {
        $planList = GetCpanelPlan($args);
        $errormsg = "Cpanel Account Creation Failure: ".$return;
                if($args['plugin_cpanel_Failure_Email']!=""){
                    $errormsg .= "  An email with the details was sent to ".$args['plugin_cpanel_Failure_Email'];
                    MailMessageEmail("Sorry, we could not create the account.  That Package was not found on the server".
                            "here is the list of plans found on the server: ". $planList,
                            $args['plugin_cpanel_Failure_Email'],
                            "Cpanel Plugin",
                            $args['plugin_cpanel_Failure_Email'],
                            "",
                            "Cpanel Account Creation Failure",
                            "",
                            "");
        }
        $GLOBALS['logger']->log(5, "plugin_cpanel::create::error: ".$errormsg);
        return new Error_CE(201, $errormsg);
    }

    //available values in args array

    //ServerHostName - contains the server host name the admin entered in the server config section
    //DomainName - the domain that is being activated
    //DomainUsername - the username for the domain
    //DomainPassword - the password requested to be used for this domain
    //DomainSharedIP - Will be set to 1 or 0, check DomainIP for actual IP address if value =0
    //DomainIP - IP address this domain is installed on

    //Retrieving Plugin specific variables use the following key structures
    //$args['plugin_cpanel_VARIABLENAME'] example: $args['plugin_cpanel_Username']


    if($args['DomainSharedIP']==0)
    {
        $errormsg = "Cpanel Account Creation Failure.";
                if($args['plugin_cpanel_Failure_Email']!=""){
            $errormsg .= "A email with the Details was sent to ".$args['plugin_cpanel_Failure_Email'];
            MailMessageEmail("At this time we can not create Accounts that do not use the Shared IP",
                            $args['plugin_cpanel_Failure_Email'],
                            "Cpanel Plugin",
                            $args['plugin_cpanel_Failure_Email'],
                            "",
                            "Cpanel Account Creation Failure",
                            "",
                            "");
        }
        $GLOBALS['logger']->log(5, "plugin_cpanel::create::error: ".$errormsg);
        return new Error_CE(202, $errormsg);

    }
    //try to create the account
    if (@$args['is_reseller']) {
        $reseller = '&reseller=1&ownerself=1';
    } else {
        $reseller = '';
    }
    $whmReq = "/scripts/wwwacct?remote=1&nohtml=1&username={$args['DomainUsername']}&password=".urlencode($args['DomainPassword'])
            ."&domain={$args['DomainName']}&plan=".urlencode($args['PackageNameOnServer']) . $reseller;
    $createacct =
        _cpanel_callFunction('whmreq', array($whmReq,
                                             $args['ServerHostName'],
                                             $args['plugin_cpanel_Username'],
                                             $args['plugin_cpanel_Access_Hash'],
                                             $args['plugin_cpanel_Use_SSL']));

    //there is no good way to know if it fails because WHM always says 'Account Creation Complete!!!'
    //the only thing consistant about the failure is that WHM displays error.gif
    if (strpos($createacct, "error.gif") == true)
        {
                $errormsg = "Cpanel Account Creation Failure.";
                if($args['plugin_cpanel_Failure_Email']!=""){
                $errormsg .= "A email with the Details was sent to ".$args['plugin_cpanel_Failure_Email'];
                MailMessageEmail($createacct,
                            $args['plugin_cpanel_Failure_Email'],
                            "Cpanel Plugin",
                            $args['plugin_cpanel_Failure_Email'],
                            "",
                            "Cpanel Account Creation Failure",
                            "",
                            "");
                }
        }

    //check to see that we got part of the 'account creation complete messasge
    else if (strpos($createacct, "Complete") == true)
    {
        $errormsg = "Cpanel Account Creation Successful";
        //set the account email address
        $emailRequest = "/scripts2/dochangeemail?user=".$args['DomainUsername']."&domain=".$args['DomainName']."&email=".$args['UserEmail'];
        $emailResponse = $changePass = whmreq($emailRequest,
                            $args['ServerHostName'],
                            $args['plugin_cpanel_Username'],
                            $args['plugin_cpanel_Access_Hash'],
                            $args['plugin_cpanel_Use_SSL']);

        // setup the reseller permissions if necessary
        if ($reseller) {
            _cpanel_setResellerACLs($args);
        }

    }
    //If we did not get a failure or success assume we were not able to connect
    else
    {
        $errormsg = "Error connecting to cpanel server";
        if($args['plugin_cpanel_Failure_Email']!="")
        {
            $errormsg .= "A email with the Details was sent to ".$args['plugin_cpanel_Failure_Email'];
            MailMessageEmail($errormsg,
                            $args['plugin_cpanel_Failure_Email'],
                            "Cpanel Plugin",
                            $args['plugin_cpanel_Failure_Email'],
                            "",
                            "Cpanel Account Creation Failure",
                            "",
                            "");
        }
    }
    $GLOBALS['logger']->log(5, "plugin_cpanel::create::error: ".$errormsg);
    return new Error_CE(203, $errormsg);
}

function Plugin_cpanel_Update($args){
    //same args as above except anychanges will be prefixed with CHANGE_
    //i.e. CHANGE_IP, CHANGE_USERNAME, CHANGE_PACKAGE, CHANGE_PASSWORD
    //be advised that if CHANGE_IP is changed but the domain var to specify it is shared is checked
    //you should grab the ip from the DomainIP and not CHANGE_IP
    //This function will not get called unless there is an update to the domain and you have specified to call update events on that server

    //double check that we are supposed to be here
    if(!$args['plugin_cpanel_Update']==1)exit;
    $errormsg = "";

    if (!function_exists('listpkgs') || !function_exists('whmreq')) {
        $errormsg = "Cpanel Account Update Failure for {$args['DomainName']}: CPanel not found in this server.";
        $GLOBALS['logger']->log(5, "plugin_cpanel::update::error: ".$errormsg);
        return $errormsg;
    }


    foreach (array_keys($args) as $keys){
    switch ($keys) {
    //see if we are supposed to change the password
    case 'CHANGE_PASSWORD':

        //just to be sure, let's make sure we don't pass a blank password
        if($args['CHANGE_PASSWORD']=="")break;

        //go ahead and change the password
        $whmReq = "/scripts/passwd?user=".$args['DomainUsername']."&password=".urlencode($args['CHANGE_PASSWORD']);
        $changePass = _cpanel_callFunction('whmreq', array($whmReq,
                                                           $args['ServerHostName'],
                                                           $args['plugin_cpanel_Username'],
                                                           $args['plugin_cpanel_Access_Hash'],
                                                           $args['plugin_cpanel_Use_SSL']));

        if (strpos($changePass, "Error") == true){
            $errormsg .= "There was an error changing the Password on Cpanel ";
            if($args['plugin_cpanel_Failure_Email']!=""){
                    $errormsg .= "A email with the Details was sent to ".$args['plugin_cpanel_Failure_Email'];
                    MailMessageEmail($changePlan,
                                $args['plugin_cpanel_Failure_Email'],
                                "Cpanel Plugin",
                                $args['plugin_cpanel_Failure_Email'],
                                "",
                                "Cpanel Account Password Change Failure",
                                "",
                                "");
                }
            }
    break;


    // see if we are supposed to change the package
    // try always to leave the case last
    case 'CHANGE_PACKAGE':

        //does CE think this is a cpanel plan?
        if ($args['PackageNameOnServer'] == null) break;

        //Is this actually a valid WHM Plan?
        if (!CheckCpanelPlan($args['PackageNameOnServer'], $args)) break;


        //let's go ahead and change the package
        $whmReq = "/scripts2/upacct?user=".$args['DomainUsername']."&pkg=".urlencode($args['PackageNameOnServer']);
        $changePlan = _cpanel_callFunction('whmreq', array($whmReq,
                                                           $args['ServerHostName'],
                                                           $args['plugin_cpanel_Username'],
                                                           $args['plugin_cpanel_Access_Hash'],
                                                           $args['plugin_cpanel_Use_SSL']));

        if (strpos($changePlan, "Error") == true){
            $errormsg .= " There was an error changing the Plan on Cpanel ";
            if($args['plugin_cpanel_Failure_Email']!=""){
                $errormsg .= "A email with the Details was sent to ".$args['plugin_cpanel_Failure_Email'];
                MailMessageEmail($changePlan,
                            $args['plugin_cpanel_Failure_Email'],
                            "Cpanel Plugin",
                            $args['plugin_cpanel_Failure_Email'],
                            "",
                            "Cpanel Account Plan Change Failure",
                            "",
                            "");
             }
        } else {
            // setup or delete the reseller permissions if necessary
            if (isset($args['is_reseller']) && $args['is_reseller'] == 1) {
                _cpanel_addReseller($args);
                _cpanel_setResellerACLs($args);
            } else {
                _cpanel_removeReseller($args);
            }
        }
    break;

    case 'CHANGE_EMAIL':

        $whmReq = "/scripts2/dochangeemail?user=".$args['DomainUsername']."&domain=".$args['DomainName']."&email=".urlencode($args['CHANGE_EMAIL']);
        $changeEmail = _cpanel_callFunction('whmreq', array($whmReq,
                                                            $args['ServerHostName'],
                                                            $args['plugin_cpanel_Username'],
                                                            $args['plugin_cpanel_Access_Hash'],
                                                            $args['plugin_cpanel_Use_SSL']));

        if (strpos($changeEmail, "Error") == true){
            $errormsg .= " There was an error changing the Email on Cpanel ";
            if($args['plugin_cpanel_Failure_Email']!=""){
                $errormsg .= "A email with the Details was sent to ".$args['plugin_cpanel_Failure_Email'];
                MailMessageEmail($changePlan,
                            $args['plugin_cpanel_Failure_Email'],
                            "Cpanel Plugin",
                            $args['plugin_cpanel_Failure_Email'],
                            "",
                            "Cpanel Account Email Failure",
                            "",
                            "");
             }
        }
    break;

    }
    }
    $GLOBALS['logger']->log(5, "plugin_cpanel::update:: Message: ".$errormsg);
    return $errormsg;

}

function Plugin_cpanel_Delete($args){
    $errormsg="";

    if (!function_exists('killacct')) {
        $errormsg = "Cpanel Account Deletion Failure for {$args['DomainName']}: CPanel not found in this server.";
        return $errormsg;
    }

    $killacct =
        _cpanel_callFunction('killacct', array($args['ServerHostName'],
                                               $args['plugin_cpanel_Username'],
                                               $args['plugin_cpanel_Access_Hash'],
                                               $args['plugin_cpanel_Use_SSL'],
                                               $args['DomainUsername']));

    if(strpos($killacct, "error.gif") == true){
        $errormsg = "Cpanel Account Deletion Failed. ";
        if($args['plugin_cpanel_Failure_Email']!=""){
            $errormsg .= "A email with the Details was sent to ". $args['plugin_cpanel_Failure_Email'];
            MailMessageEmail($killacct,
                            $args['plugin_cpanel_Failure_Email'],
                            "Cpanel Plugin",
                            $args['plugin_cpanel_Failure_Email'],
                            "",
                            "Cpanel Account Deletion Failure",
                            "",
                            "");
        }
    }
    $GLOBALS['logger']->log(5, "plugin_cpanel::delete:: Message: ".$errormsg);
    return $errormsg;
}

function Plugin_cpanel_Suspend($args){
    $errormsg="";

    if (!function_exists('suspend')) {
        $errormsg = "Cpanel Suspend Account Failure for {$args['DomainName']}: CPanel not found in this server.";
        $GLOBALS['logger']->log(5, "plugin_cpanel::suspend:: Message: ".$errormsg);
        return $errormsg;
    }

    if (@$args['is_reseller']) {
        // if reseller, suspend all children accounts as well
        $request = "/scripts/suspendreseller?remote=1&nohtml=1&resalso=1&reseller=".$args['DomainUsername'];
        $suspend =
            _cpanel_callFunction('whmreq', array($request,
                                                 $args['ServerHostName'],
                                                 $args['plugin_cpanel_Username'],
                                                 $args['plugin_cpanel_Access_Hash'],
                                                 $args['plugin_cpanel_Use_SSL']));
    } else {
        $suspend = _cpanel_callFunction('suspend', array($args['ServerHostName'],
                                                         $args['plugin_cpanel_Username'],
                                                         $args['plugin_cpanel_Access_Hash'],
                                                         $args['plugin_cpanel_Use_SSL'],
                                                         $args['DomainUsername']));
    }

    if (strpos($suspend, "error.gif") == true) {
        $errormsg = "Cpanel Account Suspension Failed. ";
        if ($args['plugin_cpanel_Failure_Email']!=""){
            $errormsg .= "A email with the details was sent to ". $args['plugin_cpanel_Failure_Email'];
            MailMessageEmail($suspend,
                            $args['plugin_cpanel_Failure_Email'],
                            "Cpanel Plugin",
                            $args['plugin_cpanel_Failure_Email'],
                            "",
                            "Cpanel Account Suspension Failure",
                            "",
                            "");
        }
    }
    $GLOBALS['logger']->log(5, "plugin_cpanel::suspend:: Message: ".$errormsg);
    return $errormsg;
}

function Plugin_cpanel_UnSuspend($args){
    $errormsg="";

    if (!function_exists('unsuspend')) {
        $errormsg = "Cpanel Unsuspend Account Failure for {$args['DomainName']}: CPanel not found in this server.";
        $GLOBALS['logger']->log(5, "plugin_cpanel::unsuspend:: Message: ".$errormsg);
        return $errormsg;
    }

    $unsuspend = _cpanel_callFunction('unsuspend', array($args['ServerHostName'],
                                                         $args['plugin_cpanel_Username'],
                                                         $args['plugin_cpanel_Access_Hash'],
                                                         $args['plugin_cpanel_Use_SSL'],
                                                         $args['DomainUsername']));

    if (strpos($unsuspend, "error.gif") == true) {
        $errormsg = "Cpanel Account Unsuspension Failed. ";
        if ($args['plugin_cpanel_Failure_Email']!=""){
            $errormsg .= "A email with the details was sent to ". $args['plugin_cpanel_Failure_Email'];
            MailMessageEmail($unsuspend,
                            $args['plugin_cpanel_Failure_Email'],
                            "Cpanel Plugin",
                            $args['plugin_cpanel_Failure_Email'],
                            "",
                            "Cpanel Account Suspension Failure",
                            "",
                            "");
        }
    }
    $GLOBALS['logger']->log(5, "plugin_cpanel::unsuspend:: Message: ".$errormsg);
    return $errormsg;
}


// @access private
function _cpanel_setResellerACLs($args)
{
    $resellerAcls = '';
    $resourceLimits = array('acl-rslimit-disk', 'acl-rsolimit-disk', 'acl-rslimit-bw', 'acl-rsolimit-bw');
    if ((isset($args['acl-rslimit-disk']) && $args['acl-rslimit-disk'])
        || (isset($args['acl-rslimit-bw']) && $args['acl-rslimit-bw']))
    {
        $resellerAcls .= '&resreslimit=1';
    }
    foreach ($args as $key => $value) {
        if (substr($key, 0, 4) == 'acl-') {
            if (in_array($key, $resourceLimits)) {
                $key = substr($key, 4);
            }
            $resellerAcls .= "&$key=$value";
        }
    }

    $request = "/scripts2/editressv?remote=1&nohtml=1&res={$args['DomainUsername']}$resellerAcls";
    $setACLs =
        _cpanel_callFunction('whmreq', array($request,
                                             $args['ServerHostName'],
                                             $args['plugin_cpanel_Username'],
                                             $args['plugin_cpanel_Access_Hash'],
                                             $args['plugin_cpanel_Use_SSL']));
}

// @access private
function _cpanel_addReseller($args)
{
    $request = "/scripts/addres?remote=1&nohtml=1&res={$args['DomainUsername']}&cowner=1";
    $removeResellerResults =
        _cpanel_callFunction('whmreq', array($request,
                                             $args['ServerHostName'],
                                             $args['plugin_cpanel_Username'],
                                             $args['plugin_cpanel_Access_Hash'],
                                             $args['plugin_cpanel_Use_SSL']));
}

// @access private
function _cpanel_removeReseller($args)
{
    $request = "/scripts/delres?remote=1&nohtml=1&res={$args['DomainUsername']}";
    $removeResellerResults =
        _cpanel_callFunction('whmreq', array($request,
                                             $args['ServerHostName'],
                                             $args['plugin_cpanel_Username'],
                                             $args['plugin_cpanel_Access_Hash'],
                                            $args['plugin_cpanel_Use_SSL']));
}


// CPanel throws a lot of E_NOTICES...
function _cpanel_callFunction($functionName, $functionParameters)
{
    $GLOBALS['logger']->log(5, "CPanel::$functionName -> ".$functionParameters[0]);
    $errorReporting = error_reporting();
    error_reporting(E_ALL & ~E_NOTICE);
    $result = call_user_func_array($functionName, $functionParameters);
    error_reporting($errorReporting);

    return $result;
}

?>
