<?php
// +----------------------------------------------------------------------+
// | NEXCESS.NET InterWorx                                                |
// +----------------------------------------------------------------------+
// | Copyright (c) 2000-2003 NEXCESS.NET L.L.C., All Rights Reserved.     |
// +----------------------------------------------------------------------+
// | Redistribution and use in source form, with or without modification  |
// | is NOT permitted without consent from the copyright holder.          |
// |                                                                      |
// | THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND |
// | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,    |
// | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A          |
// | PARTICULAR PURPOSE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,    |
// | EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,  |
// | PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR   |
// | PROFITS; OF BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY  |
// | OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT         |
// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE    |
// | USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH     |
// | DAMAGE.                                                              |
// +----------------------------------------------------------------------+
// | Authors: Chris Wells <clwells@nexcess.net>                           |
// |          Paul Oehler <poehler@nexcess.net>                           |
// +----------------------------------------------------------------------+
//

require_once ('lib/php-xmlrpc/xmlrpc.inc'); // Include xml-rpc library.
require_once ('newedge/classes/NE_MailGateway.php');
/* Currently, accounts can only be set up on shared IPs, not dedicated.
 * This is due to a limitation in ClientExec. Also, for similar reasons,
 * the only support IP retrieval rules are: first and least. The default
 * setting is to least. However, this may be changed to first, as
 * desired (below).
 */

global $ip_type;
global $ip_rule;

$ip_type = 'shared';
$ip_rule = 'least';

/* This procedure takes in a remote method name and a message to send to
 * remote xml-rpc server, creates an xml-rpc client, encodes the message
 * and send the request using cURL over HTTP or HTTPS.
 *
 * @param  $host          Hostname or IP of xml-rpc server.
 * @param  $protocol      Transport protocol; either HTTP or HTTPS for
 *                        insecure or secure connections, respectively;
 *                        default is HTTP.
 * @param  $port          Port number of xml-rpc server; default is 2443.
 * @param  $remote_method Name of remote method to call.
 * @param  $message       Message or data to send to remote server.
 * @param  $verify_cert   Whether to vefiry peer certificate or not.
 * @return                Return value is the result of executing a given,
 *                        supported command (create, suspend, unsuspend, or
 *                        delete account). The value is a message indicating
 *                        successful proccessing of command or failure to do
 *                        so.
 */

function xmlrpc_request ($host, 
			 $protocol, 
			 $port, 
			 $remote_method,
                         &$message, 
			 $verify_cert) {
  /* Begin xml-rpc code here to connect to InterWorx server to either create,
   * suspend, unsuspend, or delete account by creating xml-rpc client first:
   */

  $client_xmlrpc = 
    new xmlrpc_client ('/nodeworx/xmlrpc-api.php', 
		       $host,
		       $port
		       );
  
  /* If users set to verify the peer certificate as recorded in the
   * variable $interworx_config_5, then set the corresponding cURL option:
   */
  $client_xmlrpc->setSSLVerifyPeer ($verify_cert);
  $client_xmlrpc->setDebug(false);

  /* Create new xml-rpc message to send the xml-rpc encoded version of
   * the data and send that data using cURL over HTTPS:
   */

  $client_xmlrpc_msg = new xmlrpcmsg ($remote_method,
                                      array (_xmlrpc_encode ($message))
				      );
  
  $xmlrpc_srvr_resp = $client_xmlrpc->send ($client_xmlrpc_msg,
                                            0, 
					    $protocol);

  /* Check the return value of the response we received fromt the
   * xml-rpc server and proceed accordingly:
   */

  if (!$xmlrpc_srvr_resp) { // Did not connect.
    return('[ERROR:]  Failed to establish connection to xml-rpc server. Exiting...<br />');
  } else if ($xmlrpc_srvr_resp->faultCode ()) {
    return $xmlrpc_srvr_resp->faultString ();
  } else { // No faults.
    /* Now that no faults have occurred, the response we got should be
     * what we need or an error message indicating what went wrong on
     * the server side:
     */

    $srvr_xml_resp = $xmlrpc_srvr_resp->value (); // Response in XML format.
    $srvr_php_resp = $srvr_xml_resp->scalarval (); // Response in PHP format.

    return ($srvr_php_resp);
  }
}

/* This function returns an error message and e-mail the admin about the
 * error, if a failure e-mail was specified when setting up the server.
 *
 * @param  $msg_body Message body.
 * @param  $args     Array of available arguments/variables.
 * @return           Error message.
 */

function error_message ($msg_body, &$args) {
    $error_msg = 'Failed to create SiteWorx account. ';
    $mailGateway = new NE_MailGateway();
    if (!empty ($args ['plugin_interworx_Failure_E-mail'])) { // Send e-mail to admin.
        $error_msg .= 'An e-mail with the details was sent to ' .
            $args ['plugin_interworx_Failure_E-mail'] . '.';
        
        $mailGateway->mailMessageEmail (    $msg_body,
                                            $args ['plugin_interworx_Failure_E-mail'],
                                            'ClientExec InterWorx Plugin',
                                            $args ['plugin_interworx_Failure_E-mail'],
                                            '',
                                            'InterWorx account-creation failure.');
    }
    
    return ($error_msg);
}

/* This function sets the connection protocol and port number given the
 * settings of the config variable "Use Secure Connections":
 *
 * @param  $protocol Protocol to be used with this connection.
 * @param  $port     Port associated with protocol.
 * @return           Parameters set by reference..
 */

function set_connection_params (&$protocol, &$port, &$args) {
  $protocol = $args ['plugin_interworx_Use_Secure_Connections'] ? 'https' : 'http';
  $port = ($protocol == 'https') ? 2443 : 2080;
}

/* This function checks to see if the associated package already exists
 * on the InterWorx box and returns 1, if it does. Otherwise, 0.
 *
 * @param  $package_name Name of associated package.
 * @param  $args         Array of available arguments/variables.
 * @return               1, if package exists; 0, otherwise.
 */

function package_exists ($package_name, &$args) {
  $protocol = $port = $exists = '';
  $pkg_exists_msg = array ('access_key'    => $args ['plugin_interworx_Access_Key'],
                           'package_name'  => $package_name
                          );

  set_connection_params ($protocol, $port, $args); // Set protocol and port.

  $exists = xmlrpc_request ($args ['ServerHostName'], 
			    $protocol, 
			    $port,
                            'iworx.packageexists', 
			    $pkg_exists_msg,
                            $args ['plugin_interworx_Verify_Certificate']);
  
  return ($exists);
}

/* This function retrieves an IP from the InterWorx box where the new
 * account is going to be set up on.
 *
 * @param  $ip   IP to retrieve.
 * @param  $args Array of available arguments/variables.
 * @return       IP or error message (by reference).
 */

function get_ip (&$ip, &$args) {
  global $ip_type, $ip_rule;
  $got_ip = false;
  $protocol = $port = '';
  $get_ip_msg = array ('access_key' => $args ['plugin_interworx_Access_Key'],
                       'type'       => $ip_type,
                       'rule'       => $ip_rule
                      );

  set_connection_params ($protocol, $port, $args); // Set protocol and port.

  // Get IP from the InterWorx box to set up new account on:

  $ip = xmlrpc_request ($args ['ServerHostName'], 
			$protocol, 
			$port,
                        'iworx.getip', 
			$get_ip_msg,
                        $args ['plugin_interworx_Verify_Certificate']);

  /* Check to make sure what we got back is an IP and not an error
   * message:
   */

  if (ereg ('[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}', $ip)) {
    $got_ip = true;
  }

  return ($got_ip);
}

/* This function creates a new account on the InterWorx server with IP
 * $ip (first argument).
 *
 * @param  $create Success or error message.
 * @param  $ip     IP to set up account on.
 * @param  $args   Array of available arguments/variables.
 * @return         True, if account created; False, otherwise.
 */

function create_acct (&$create, $ip, &$args) {
  $acct_created = false;
  $protocol = $port = '';
  $create_acct_msg = array ('access_key'   => 
			    $args ['plugin_interworx_Access_Key'],
                            'account_info' => 
			    array ($args ['UserEmail'],
				   $args ['UserEmail'],
				   $args ['DomainPassword'],
				   $args ['DomainName'],
				   $ip),
                            'package_name' => 
			    $args ['PackageNameOnServer']
			    );
  
  set_connection_params ($protocol, $port, $args); // Set protocol and port.

  /* With all the data/message ready to go, we can go ahead and create the
   * account:
   */

  $create = xmlrpc_request ($args ['ServerHostName'], $protocol, $port,
                            'iworx.createaccount', $create_acct_msg,
                            $args ['plugin_interworx_Verify_Certificate']);

  if (($create == 'Account Created') || ($create == 'Domain Name Already Exists') ||
      ($create == 'Subdomain Already Exists')) {
    $acct_created = true;
  }

  return ($acct_created);
}

/* This function deletes an account on the InterWorx server.
 *
 * @param  $delete Success or error message (by reference).
 * @param  $args   Array of available arguments/variables.
 * @return         True, if account created; False, otherwise.
 */

function delete_acct (&$delete, &$args) {
  $protocol = $port = '';
  $delete_acct_msg = array ('access_key' => $args ['plugin_interworx_Access_Key'],
                            'domain'     => $args ['DomainName']
                           );

  set_connection_params ($protocol, $port, $args); // Set protocol and port.

  // Proceed to delete the account:

  $delete = xmlrpc_request ($args ['ServerHostName'], $protocol, $port,
                            'iworx.deleteaccount', $delete_acct_msg,
                            $args ['plugin_interworx_Verify_Certificate']);

  return ($delete == 'Account Deleted') ? true : false;
}

/* This function updates client password on the InterWorx box.  	 
 *
 * @param  $update Success or error message (by reference).
 * @param  $args   Array of available arguments/variables.
 * @return         True, if account created; False, otherwise.
 */

function update_client_info (&$update, $method_name, &$update_msg, &$args) {
  $protocol = $port = $update = '';

  /* Should probably assemble message outside of this wrapper function and 
   * then pass it in here for each of the updates (pass, e-mail, an package.
   */
  
  set_connection_params ($protocol, $port, $args); // Set protocol and port.

  // Proceed to update password:

  $update = xmlrpc_request ($args ['ServerHostName'], $protocol, $port,
                            $method_name, $update_msg,
                            $args ['plugin_interworx_Verify_Certificate']); 

  return (($update == 'Updated Password') ||
          ($update == 'Updated E-mail') ||
          ($update == 'Updated Package')) ? true : false;
}

/* This function suspends an account on the InterWorx server.
 *
 * @param  $suspend Success or error message (by reference).
 * @param  $args    Array of available arguments/variables.
 * @return          True, if account created; False, otherwise.
 */

function suspend_acct (&$suspend, &$args) {
  $protocol = $port = '';
  $suspend_acct_msg = array ('access_key' => $args ['plugin_interworx_Access_Key'],
                             'domain'     => $args ['DomainName']
                            );

  set_connection_params ($protocol, $port, $args); // Set protocol and port.

  // Proceed to suspend the account:

  $suspend = xmlrpc_request ($args ['ServerHostName'], $protocol, $port,
                             'iworx.suspendaccount', $suspend_acct_msg,
                             $args ['plugin_interworx_Verify_Certificate']);

  return ($suspend != 'Domain Not Found') ? true : false;
}

/* This function enables an account on the InterWorx server.
 *
 * @param  $enable Success or error message (by reference).
 * @param  $args   Array of available arguments/variables.
 * @return         True, if account created; False, otherwise.
 */

function enable_acct (&$enable, &$args) {
  $protocol = $port = '';
  $enable_acct_msg = array ('access_key' => $args ['plugin_interworx_Access_Key'],
                            'domain'     => $args ['DomainName']
                           );

  set_connection_params ($protocol, $port, $args); // Set protocol and port.

  // Proceed to enable the account:

  $enable = xmlrpc_request ($args ['ServerHostName'], $protocol, $port,
                            'iworx.unsuspendaccount', $enable_acct_msg,
                            $args ['plugin_interworx_Verify_Certificate']);

  return ($enable != 'Domain Not Found') ? true : false;
}
?>
