<?php

require_once 'modules/admin/models/SSLPlugin.php';

class PluginServertastic extends SSLPlugin
{
    public $mappedTypeIds = array (
        SSL_CERT_RAPIDSSL                               => 'RapidSSL-12',
        SSL_CERT_GEOTRUST_QUICKSSL_PREMIUM              => 'QuickSSLPremium-12',
        SSL_CERT_GEOTRUST_TRUE_BUSINESSID               => 'TrueBizID-12',
        SSL_CERT_GEOTRUST_TRUE_BUSINESSID_EV            => 'TrueBizIDEV-12',
        SSL_CERT_GEOTRUST_TRUE_BUSINESSID_WILDCARD      => 'TrueBizIDWildcard-12',
        SSL_CERT_VERISIGN_SECURE_SITE                   => 'SecureSite-12',
        SSL_CERT_VERISIGN_SECURE_SITE_PRO               => 'SecureSitePro-12',
        SSL_CERT_VERISIGN_SECURE_SITE_EV                => 'SecureSiteEV-12',
        SSL_CERT_VERISIGN_SECURE_SITE_PRO_EV            => 'SecureSiteProEV-12',
    );
    
    public $usingInviteURL = true;
    
    function getVariables()
    {
        $variables = array(
            /*T*/'Plugin Name'/*/T*/ => array (
                                'type'          =>'hidden', 
                                'description'   =>/*T*/'How CE sees this plugin (not to be confused with the Signup Name)'/*/T*/,
                                'value'         =>/*T*/'ServerTastic'/*/T*/
                               ),
            /*T*/'Use testing server'/*/T*/ => array(
                                'type'          =>'yesno',
                                'description'   =>/*T*/'Select Yes if you wish to use ServerTastic\'s testing environment, so that transactions are not actually made. For this to work, you must first register you server\'s ip in ServerTastic\'s testing environment, and your server\'s name servers must be registered there as well.'/*/T*/,
                                'value'         =>0
                               ),
            /*T*/'API Key'/*/T*/ => array(
                                'type'          =>'text',
                                'description'   =>/*T*/'Enter your API Key here.'/*/T*/,
                                'value'         =>''
                               ),
             /*T*/'Actions'/*/T*/ => array (
                                'type'          => 'hidden',
                                'description'   => /*T*/'Current actions that are active for this plugin (when a domain isn\'t registered)'/*/T*/,
                                'value'         => 'Purchase,CancelConfiguration (Cancel Configuration),ResendInviteEmail (Resend Invite Email),ResendFulfillmentEmail (Resend Fulfillment Email)'
                                )
        );
    
        return $variables;
    }
    
    function doPurchase($params)
    {
        $userPackage = new UserPackage($params['userPackageId']);
        $params = $this->buildParams($userPackage);
        
        $certId = $userPackage->getCustomField('Certificate Id');
        // no cert stored, so purchase the cert.
        if ( $certId == '' ) {
            // Step 1: Purchase Cert
            $certId = $this->purchaseCert($params);        
            $userPackage->setCustomField('Certificate Id', $certId);
            $params['certId'] = $certId;
        }
    }
    
    private function purchaseCert($params)
    {
        $arguments = array(
            'st_product_code'               => $this->getServiceNameById($params['typeId']),
            'api_key'                       => $params['API Key'],
            'end_customer_email'            => $params['EmailAddress'],
            'reseller_unique_reference'     => md5(time()),
            'server_count'                  => 1,
            'integration_source_id'         => 4 // CE integration source, to tell them it's from a CE instance
        );
        
        $response = $this->_makeRequest('/order/place', $arguments);
        throw new Exception('ServerTastic Plugin Error: Failed to communicate with ServerTastic', EXCEPTION_CODE_CONNECTION_ISSUE);
        
        if ( isset($response->success) ) {
            return $response->reseller_order_id;
        }
    }
    
    function doParseCSR($params) 
    {
        $userPackage = new UserPackage($params['userPackageId']);
        $params = $this->buildParams($userPackage);
        
        $arguments = array(
            'api_key'           => $params['API Key'],
            'reseller_order_id' => $params['certId']
        );

        $response = $this->_makeRequest('/order/review', $arguments);
        if (!is_object($response)) throw new Exception('ServerTastic Plugin Error: Failed to communicate with ServerTastic', EXCEPTION_CODE_CONNECTION_ISSUE);
        
        $return = array();
        if ( isset($response->success) ) {
            $return['non_csr'] = true;
            $return['domain'] = $response->domain_name;
            $return['info']['Order Status'] = $response->order_status;
            $return['info']['Invite URL'] = $response->invite_url;
            $return['info']['Domain Name'] = $response->domain_name;
            $return['info']['Customer EMail'] = $response->end_customer_email;
            $return['info']['Organization Name'] = $response->organisation_info->name;
            $return['info']['Organization Division'] = $response->organisation_info->division;
            $return['info']['Organization City'] = $response->organisation_info->address->city;
            $return['info']['Organization Region'] = $response->organisation_info->address->region;
            $return['info']['Organization Country'] = $response->organisation_info->address->country;
            $return['info']['Approver EMail'] = $response->approver_email_address;
        }
        return $return;
    }
    
    function doGetCertStatus($params)
    {
        $userPackage = new UserPackage($params['userPackageId']);
        $params = $this->buildParams($userPackage);
        
        $arguments = array(
            'api_key'               => $params['API Key'],
            'reseller_order_id'     => $params['certId']
        ); 
        $response = $this->_makeRequest('/order/review', $arguments);
        
        if (!is_object($response)) throw new Exception('ServerTastic Plugin Error: Failed to communicate with ServerTastic', EXCEPTION_CODE_CONNECTION_ISSUE);
        
        if ( isset($response->success) ) {
            $status = strval($response->order_status);
            
            if ( $status == 'Completed' ) {
                // cert is issued, so mark our internal status as issued so we don't poll anymore.
                $userPackage->setCustomField('Certificate Status', SSL_CERT_ISSUED_STATUS);
            }
            return $status;
        }
    }
    
    function doResendInviteEmail($params)
    {
        $userPackage = new UserPackage($params['userPackageId']);
        $params = $this->buildParams($userPackage);
        
        $arguments = array(            
            'api_key'               => $params['API Key'],
            'email_type'            => 'Invite',
            'reseller_order_id'     => $params['certId']
        ); 
        $response = $this->_makeRequest('/order/resendemail', $arguments);
        
        if (!is_object($response)) throw new Exception('ServerTastic Plugin Error: Failed to communicate with ServerTastic', EXCEPTION_CODE_CONNECTION_ISSUE);

        if ( isset($response->success) ) {
            return 'Successfully resent invite e-mail.';
        }        
    }
    
    function doResendApproverEmail($params)
    {
        $userPackage = new UserPackage($params['userPackageId']);
        $params = $this->buildParams($userPackage);
        
        $arguments = array(            
            'api_key'               => $params['API Key'],
            'email_type'            => 'Approver’',
            'reseller_order_id'     => $params['certId']
        ); 
        $response = $this->_makeRequest('/order/resendemail', $arguments);
        
        if (!is_object($response)) throw new Exception('ServerTastic Plugin Error: Failed to communicate with ServerTastic', EXCEPTION_CODE_CONNECTION_ISSUE);

        if ( isset($response->success) ) {
            return 'Successfully resent approver e-mail.';
        }        
    }
    
    function doResendFulfillmentEmail($params)
    {
        $userPackage = new UserPackage($params['userPackageId']);
        $params = $this->buildParams($userPackage);
        
        $arguments = array(            
            'api_key'               => $params['API Key'],
            'email_type'            => 'Fulfillment’]’',
            'reseller_order_id'     => $params['certId']
        ); 
        $response = $this->_makeRequest('/order/resendemail', $arguments);
        
        if (!is_object($response)) throw new Exception('ServerTastic Plugin Error: Failed to communicate with ServerTastic', EXCEPTION_CODE_CONNECTION_ISSUE);

        if ( isset($response->success) ) {
            return 'Successfully resent fulfillment e-mail.';
        }        
    }
    
    function doCancelConfiguration($params)
    {
        $userPackage = new UserPackage($params['userPackageId']);
        $params = $this->buildParams($userPackage);
        
        $arguments = array(
            'api_key'               => $params['API Key'],
            'reseller_order_id'     => $params['certId']
        ); 
        $response = $this->_makeRequest('/order/cancel', $arguments);
        
        if (!is_object($response)) throw new Exception('ServerTastic Plugin Error: Failed to communicate with ServerTastic', EXCEPTION_CODE_CONNECTION_ISSUE);
        
        if ( isset($response->success) ) {
            $userPackage->setCustomField("Certificate Id", '');
            return 'Successfully cancelled configuration of certificate.';       
        }        
    }

    function _makeRequest($url, $arguments)
    {
        require_once 'newedge/classes/NE_Network.php';
    
        $request = 'https://';
    
        if (@$this->settings->get('plugin_ServerTastic_Use testing server')) $request .= 'test-api.servertastic.com';
        else $request .= 'api.servertastic.com';
    
        $request .= '/ssl' . $url;
        
        $i = 0; 
        foreach ($arguments as $name => $value) {
            $value = urlencode($value);
            if (!$i) $request .= "?$name=$value";
            else $request .= "&$name=$value";
            $i++;
        }
    
        $this->logger->log(4, 'ServerTastic Params: '. print_r($arguments, true));
        $response = NE_Network::curlRequest($this->settings, $request, false, false, true);
    
        if (is_a($response, 'NE_Error')) throw new Exception ($response);
        if (!$response) return false;   // don't want xmlize an empty array
    
        $response = simplexml_load_string($response);
    
        if ( isset($response->error) ) {
            throw new Exception ('ServerTastic Plugin Error: ' . $response->error->message);
        }
        
        return $response;
    }
    
    function getAvailableActions($userPackage)
    {
        $actions = array();
        $params['userPackageId'] = $userPackage->id;
        try {
            $status = $this->doGetCertStatus($params);
            
            if ( $status == 'Cancelled' || $status == 'Roll Back' ) {
                $actions[] = 'Purchase';
            } else if ( $status == 'Awaiting Customer Verification' || $status == 'Awaiting Provider Approval' ) {
                $actions[] = 'CancelConfiguration (Cancel Configuration)';
                $actions[] = 'ResendApproverEmail (Resend Approver Email)';
            } else if ( $status == 'Invite Available' ) {
                $actions[] = 'CancelConfiguration (Cancel Configuration)';
                $actions[] = 'ResendInviteEmail (Resend Invite Email)';
            } else if ( $status == 'Completed' ) {
                $actions[] = 'ResendFulfillmentEmail (Resend Fulfillment Email)';
            }               
        } catch ( Exception $e ) {
            $actions[] = 'Purchase';
        }
        
        return $actions;
    }
    
    
    function getCertificateTypes() 
    {
        return array (
            'QuickSSLPremium-12' => 'GeoTrust QuickSSL Premium',
            'TrueBizID-12' => 'GeoTrust True BusinessID',
            'RapidSSL-12' => 'RapidSSL',
            'TrueBizIDEV-12' => 'GeoTrust TrueBizID with EV',
            'TrueBizIDWildcard-12' => 'GeoTrust TrueBizID Wildcard',
            'SecureSite-12' => 'Verisign Secure Site',
            'SecureSitePro-12' => 'Verisign Secure Site Pro',
            'SecureSiteEV-12' => 'Verisign Secure Site EV',
            'SecureSiteProEV-12' => 'Verisign Secure Site Pro EV',
        );
    }

    private function getServiceNameById($id)
    {
        switch ( $id ) {
            case SSL_CERT_RAPIDSSL:
                return 'RapidSSL-12';
            case SSL_CERT_GEOTRUST_QUICKSSL_PREMIUM:
                return 'QuickSSLPremium-12';
            case SSL_CERT_GEOTRUST_TRUE_BUSINESSID:
                return 'TrueBizID-12';
            case SSL_CERT_GEOTRUST_TRUE_BUSINESSID_EV:
                return 'TrueBizIDEV-12';
            case SSL_CERT_GEOTRUST_TRUE_BUSINESSID_WILDCARD:
                return 'TrueBizIDWildcard-12';
            case SSL_CERT_VERISIGN_SECURE_SITE:
                return 'SecureSite-12';
            case SSL_CERT_VERISIGN_SECURE_SITE_PRO:
                return 'SecureSitePro-12';
            case SSL_CERT_VERISIGN_SECURE_SITE_EV:
                return 'SecureSiteEV-12';
            case SSL_CERT_VERISIGN_SECURE_SITE_PRO_EV:
                return 'SecureSiteProEV-12';
        }
    }
    
    function getWebserverTypes($type)
    {
        return array();
    }
}