<?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';
}

require_once 'newedge/classes/NE_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 validateCredentials($args)
    {
        $args['DomainUsername'] = trim(strtolower($args['DomainUsername']));

        // if it's an update, skip username existance check
        if (!isset($args['isUpdate']) || !$args['isUpdate']) {
            $accts = $this->_callFunction('listaccts', array($args['ServerHostName'],
                                                             $args['plugin_cpanel_Username'],
                                                             $args['plugin_cpanel_Access_Hash'],
                                                             $args['plugin_cpanel_Use_SSL']));
            if (isset($accts[$args['DomainUsername']])) {
                $args['DomainUsername'] = $args['DomainUsername'] . '2';

                if (isset($accts[$args['DomainUsername']])) {
                    return new NE_Error(/*T*/'Invalid domain username'/*/T*/);
                }
            }
        }

        $errors = array();

        if (strpos(strtolower($args['DomainUsername']), 'test') !== false) {
            if (strtolower($args['DomainUsername']) != 'test') {
                $args['DomainUsername'] = str_replace('test', '', $args['DomainUsername']);
            } else {
                $errors[] = /*T*/'Domain username can\'t contain \'test\''/*/T*/;
            }
        }

        if (is_numeric(substr(trim($args['DomainUsername']), 0, 1))) {
            $args['DomainUsername'] = preg_replace("/^\d*/", '', $args['DomainUsername']);

            if (is_numeric(substr(trim($args['DomainUsername']), 0, 1)) || strlen(trim($args['DomainUsername'])) == 0) {
                $errors[] = /*T*/'Domain username can\'t start with a number'/*/T*/;
            }
        }

        if (strpos($args['DomainPassword'], $args['DomainUsername']) !== false) {
            $errors[] = /*T*/'Domain password can\'t contain domain username'/*/T*/;
        }

        if ($errors) {
            return new NE_Error($errors);
        }

        return $args['DomainUsername'];
    }

    //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 (@$args['is_reseller'] && isset($args['package_addons']['DISKSPACE'])) {
            $args['acl-rslimit-disk'] += ((int)$args['package_addons']['DISKSPACE']);
        }
        if (@$args['is_reseller'] && isset($args['package_addons']['BANDWIDTH'])) {
            $args['acl-rslimit-bw'] += ((int)$args['package_addons']['BANDWIDTH']) * 1024; // Convert from Gigs to MB
        }
        if (@$args['is_reseller'] && 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 NE_MailGateway();
        if (($return = $this->CheckCpanelPlan($args['PackageNameOnServer'], $args)) !== true)
        {
            $planList = $this->GetCpanelPlan($args);
            $errormsg = "Cpanel Account Creation Failure: ".$return;
            if($args['plugin_cpanel_Failure_E-mail']!=""){
                $errormsg .= "  An email with the details was sent to ".$args['plugin_cpanel_Failure_E-mail'];
                $body = 'Sorry, we could not create the account. The following error was produced: ' . $return;
                if ($return == 'The package was not found on the server.') {
                    $body .= "\r\n\r\nHere is the list of plans found on the server:\r\n". $planList;
                }
                $mailGateway->mailMessageEmail( $body,
                                                $args['plugin_cpanel_Failure_E-mail'],
                                                "Cpanel Plugin",
                                                $args['plugin_cpanel_Failure_E-mail'],
                                                "",
                                                "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_E-mail']!=""){
                $errormsg .= "A email with the Details was sent to ".$args['plugin_cpanel_Failure_E-mail'];
                $mailGateway->mailMessageEmail( "At this time we can not create Accounts that do not use the Shared IP",
                                                $args['plugin_cpanel_Failure_E-mail'],
                                                "Cpanel Plugin",
                                                $args['plugin_cpanel_Failure_E-mail'],
                                                "",
                                                "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_E-mail']!=""){
                $errormsg .= "A email with the Details was sent to ".$args['plugin_cpanel_Failure_E-mail'];
                $mailGateway->mailMessageEmail( $createacct,
                                                $args['plugin_cpanel_Failure_E-mail'],
                                                "Cpanel Plugin",
                                                $args['plugin_cpanel_Failure_E-mail'],
                                                "",
                                                "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";
        }
        $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 NE_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_E-mail'];
                        $mailGateway->mailMessageEmail( $changePlan,
                                                        $args['plugin_cpanel_Failure_E-mail'],
                                                        "Cpanel Plugin",
                                                        $args['plugin_cpanel_Failure_E-mail'],
                                                        "",
                                                        "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_E-mail']!=""){
                    $errormsg .= "A email with the Details was sent to ".$args['plugin_cpanel_Failure_E-mail'];
                    $mailGateway->mailMessageEmail( $changePlan,
                                                    $args['plugin_cpanel_Failure_E-mail'],
                                                    "Cpanel Plugin",
                                                    $args['plugin_cpanel_Failure_E-mail'],
                                                    "",
                                                    "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_E-mail']!=""){
                    $errormsg .= "A email with the Details was sent to ".$args['plugin_cpanel_Failure_E-mail'];
                    $mailGateway->mailMessageEmail( $changePlan,
                                                    $args['plugin_cpanel_Failure_E-mail'],
                                                    "Cpanel Plugin",
                                                    $args['plugin_cpanel_Failure_E-mail'],
                                                    "",
                                                    "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 NE_MailGateway();
        if(strpos($killacct, "error.gif") == true){
            $errormsg = "Cpanel Account Deletion Failed. ";
            if($args['plugin_cpanel_Failure_E-mail']!=""){
                $errormsg .= "A email with the Details was sent to ". $args['plugin_cpanel_Failure_E-mail'];
                $mailGateway->mailMessageEmail( $killacct,
                                                $args['plugin_cpanel_Failure_E-mail'],
                                                "Cpanel Plugin",
                                                $args['plugin_cpanel_Failure_E-mail'],
                                                "",
                                                "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 NE_MailGateway();
        if (strpos($suspend, "error.gif") == true) {
            $errormsg = "Cpanel Account Suspension Failed. ";
            if ($args['plugin_cpanel_Failure_E-mail']!=""){
                $errormsg .= "A email with the details was sent to ". $args['plugin_cpanel_Failure_E-mail'];
                $mailGateway->mailMessageEmail( $suspend,
                                                $args['plugin_cpanel_Failure_E-mail'],
                                                "Cpanel Plugin",
                                                $args['plugin_cpanel_Failure_E-mail'],
                                                "",
                                                "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 NE_MailGateway();
        if (strpos($unsuspend, "error.gif") == true) {
            $errormsg = "Cpanel Account Unsuspension Failed. ";
            if ($args['plugin_cpanel_Failure_E-mail']!=""){
                $errormsg .= "A email with the details was sent to ". $args['plugin_cpanel_Failure_E-mail'];
                $mailGateway->mailMessageEmail( $unsuspend,
                                                $args['plugin_cpanel_Failure_E-mail'],
                                                "Cpanel Plugin",
                                                $args['plugin_cpanel_Failure_E-mail'],
                                                "",
                                                "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;
    }
}

?>
