<?php

//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 ("classes/MailGateway.php");

require_once 'classes/ServerPlugin.php';

/**
* @package Plugins
*/
class PluginCpanel extends ServerPlugin
{
    function getVariables()
    {
        /* 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
              encryptable - used to indicate the variable's value must be encrypted in the database
        */

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

    /**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 = $this->_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 = $this->_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 . "\r\n";
        }
        return $plansList;
    }

    function 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 = $this->_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 (isset($args['PassedUserName']) && $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 && isset($accts["$username"])) {
              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 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.";
            $this->logger->log(5, "plugin_cpanel::create::error: ".$errormsg);
            return new NE_Error($errormsg, 200);
        }
        $mailGateway = new MailGateway();
        if (($return = $this->CheckCpanelPlan($args['PackageNameOnServer'], $args)) !== true)
        {
            $planList = $this->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'];
                $mailGateway->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:\r\n". $planList,
                                                $args['plugin_cpanel_Failure_Email'],
                                                "Cpanel Plugin",
                                                $args['plugin_cpanel_Failure_Email'],
                                                "",
                                                "Cpanel Account Creation Failure");
            }
            $this->logger->log(5, "plugin_cpanel::create::error: ".$errormsg);
            return new NE_Error($errormsg, 201);
        }

        //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'];
                $mailGateway->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");
            }
            $this->logger->log(5, "plugin_cpanel::create::error: ".$errormsg);
            return new NE_Error($errormsg, 202);

        }
        //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 =
            $this->_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'];
                $mailGateway->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) {
                $this->_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'];
                $mailGateway->mailMessageEmail( $errormsg,
                                                $args['plugin_cpanel_Failure_Email'],
                                                "Cpanel Plugin",
                                                $args['plugin_cpanel_Failure_Email'],
                                                "",
                                                "Cpanel Account Creation Failure");
            }
        }
        $this->logger->log(5, "plugin_cpanel::create::error: ".$errormsg);
        return new NE_Error($errormsg, 203);
    }

    function 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.";
            $this->logger->log(5, "plugin_cpanel::update::error: ".$errormsg);
            return $errormsg;
        }

        $mailGateway = new MailGateway();
        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 = $this->_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'];
                        $mailGateway->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 (!$this->CheckCpanelPlan($args['PackageNameOnServer'], $args)) break;


            //let's go ahead and change the package
            $whmReq = "/scripts2/upacct?user=".$args['DomainUsername']."&pkg=".urlencode($args['PackageNameOnServer']);
            $changePlan = $this->_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'];
                    $mailGateway->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) {
                    $this->_addReseller($args);
                    $this->_setResellerACLs($args);
                } else {
                    $this->_removeReseller($args);
                }
            }
        break;

        case 'CHANGE_EMAIL':

            $whmReq = "/scripts2/dochangeemail?user=".$args['DomainUsername']."&domain=".$args['DomainName']."&email=".urlencode($args['CHANGE_EMAIL']);
            $changeEmail = $this->_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'];
                    $mailGateway->mailMessageEmail( $changePlan,
                                                    $args['plugin_cpanel_Failure_Email'],
                                                    "Cpanel Plugin",
                                                    $args['plugin_cpanel_Failure_Email'],
                                                    "",
                                                    "Cpanel Account Email Failure");
                }
            }
        break;

        }
        }
        $this->logger->log(5, "plugin_cpanel::update:: Message: ".$errormsg);
        return $errormsg;

    }

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

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

        $killacct =
            $this->_callFunction('killacct', array($args['ServerHostName'],
                                                   $args['plugin_cpanel_Username'],
                                                   $args['plugin_cpanel_Access_Hash'],
                                                   $args['plugin_cpanel_Use_SSL'],
                                                   $args['DomainUsername']));
        $mailGateway = new MailGateway();
        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'];
                $mailGateway->mailMessageEmail( $killacct,
                                                $args['plugin_cpanel_Failure_Email'],
                                                "Cpanel Plugin",
                                                $args['plugin_cpanel_Failure_Email'],
                                                "",
                                                "Cpanel Account Deletion Failure");
            }
        }
        $this->logger->log(5, "plugin_cpanel::delete:: Message: ".$errormsg);
        return $errormsg;
    }

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

        if (!function_exists('suspend')) {
            $errormsg = "Cpanel Suspend Account Failure for {$args['DomainName']}: CPanel not found in this server.";
            $this->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 =
                $this->_callFunction('whmreq', array($request,
                                                     $args['ServerHostName'],
                                                     $args['plugin_cpanel_Username'],
                                                     $args['plugin_cpanel_Access_Hash'],
                                                     $args['plugin_cpanel_Use_SSL']));
        } else {
            $suspend = $this->_callFunction('suspend', array($args['ServerHostName'],
                                                             $args['plugin_cpanel_Username'],
                                                             $args['plugin_cpanel_Access_Hash'],
                                                             $args['plugin_cpanel_Use_SSL'],
                                                             $args['DomainUsername']));
        }
        $mailGateway = new MailGateway();
        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'];
                $mailGateway->mailMessageEmail( $suspend,
                                                $args['plugin_cpanel_Failure_Email'],
                                                "Cpanel Plugin",
                                                $args['plugin_cpanel_Failure_Email'],
                                                "",
                                                "Cpanel Account Suspension Failure");
            }
        }
        $this->logger->log(5, "plugin_cpanel::suspend:: Message: ".$errormsg);
        return $errormsg;
    }

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

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

        $unsuspend = $this->_callFunction('unsuspend', array($args['ServerHostName'],
                                                             $args['plugin_cpanel_Username'],
                                                             $args['plugin_cpanel_Access_Hash'],
                                                             $args['plugin_cpanel_Use_SSL'],
                                                             $args['DomainUsername']));
        $mailGateway = new MailGateway();
        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'];
                $mailGateway->mailMessageEmail( $unsuspend,
                                                $args['plugin_cpanel_Failure_Email'],
                                                "Cpanel Plugin",
                                                $args['plugin_cpanel_Failure_Email'],
                                                "",
                                                "Cpanel Account Suspension Failure");
            }
        }
        $this->logger->log(5, "plugin_cpanel::unsuspend:: Message: ".$errormsg);
        return $errormsg;
    }


    // @access private
    function _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 =
            $this->_callFunction('whmreq', array($request,
                                                 $args['ServerHostName'],
                                                 $args['plugin_cpanel_Username'],
                                                 $args['plugin_cpanel_Access_Hash'],
                                                 $args['plugin_cpanel_Use_SSL']));
    }

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

    // @access private
    function _removeReseller($args)
    {
        $request = "/scripts/delres?remote=1&nohtml=1&res={$args['DomainUsername']}";
        $removeResellerResults =
            $this->_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 _callFunction($functionName, $functionParameters)
    {
        $this->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;
    }
}

?>
