<?php
global $CONFIG, $_LANG, $smarty, $whmcs;
require_once dirname(__FILE__).'/includes/api.php';

/**
 * 
 * Initialisate language always while loading this file.
 * 
 */
$langFile = dirname(__FILE__) . '/lang/' . ((isset($_SESSION['language'])) ? $_SESSION['language'] : '') . '.php';

if (!file_exists($langFile)) {
    $langFile = dirname(__FILE__) . '/lang/' . $whmcs->get_config('Language') . '.php';

    if (!file_exists($langFile)) {
        $langFile = dirname(__FILE__) . '/lang/english.php';
    }
}

require_once($langFile);

if (isset($smarty)) {
    $smarty->assign('LANG', $_LANG);
}

/**
 * 
 * getAllProducts() function will return an array of all products available at GoGetSSL.
 * 
 */
function gogetssl_getAllProducts() {
    $productRequest = curlCall('https://my.gogetssl.com/api/certificates.json');
    
    $certList = json_decode($productRequest, true);
    
    if (is_array($certList)) {
        return $certList;
    }

    return array();
}

/**
 * 
 * ConfigOptions() function will return an array for the configuration page within the WHMCS adminarea.
 * 
 */
function gogetssl_ConfigOptions() {
    global $packageconfigoption;

    $products = gogetssl_getAllProducts();
    
    $emailQuery = select_query('tblemailtemplates', '*', array('name' => 'SSL Certificate Configuration Required'));
    
    if (mysql_num_rows($emailQuery) < 1) {
        full_query('INSERT INTO tblemailtemplates (type, name, subject, message, fromname, fromemail, disabled, custom, language, copyto, plaintext) VALUES ("product", "SSL Certificate Configuration Required", "SSL Certificate Configuration Required", "<p>Dear {$client_name},</p><p>Thank you for your order for an SSL Certificate. Before you can use your certificate, it requires configuration which can be done at the URL below.</p><p>{$ssl_configuration_link}</p><p>Instructions are provided throughout the process but if you experience any problems or have any questions, please open a ticket for assistance.</p><p>{$signature}</p>", "", "", "", "", "", "", "0")');
    }

    $certTypeList = '';
    
    if (is_array($products)) {
        foreach ($products['products'] as $cert => $details) {
            if ($details['id']) {
                $certTypeList .= $details['name'] . ' (ID: ' . $details['id'] . ')' . ',';
            }
        }
    }

    if (isset($packageconfigoption[1]) && isset($packageconfigoption[2])) {
        if (!empty($packageconfigoption[1]) && !empty($packageconfigoption[2])) {
            try {
                gogetssl_call(array('command' => null, 'uid' => $packageconfigoption[1], 'pw' => $packageconfigoption[2]), $packageconfigoption[5]);
            } catch (GoGetSSLAuthException $e) {
                echo '<div class="errorbox"><strong><span class="title">API credentials invalid</span></strong><br>Recheck your API credentials (Username and API password), we counldn\'t authenticate to the GoGetSSL API. This could case a bugs within the GoGetSSL server module.</div>';
            }
        }
    }

    $additionalNotes = '<script type="text/javascript">
        $(document).ready(function() {

            $("#techemail").parent().parent("tr").prev().after("<tr><td colspan=4><div id=\"newtechnote\"></td></tr>");
            $("#newtechnote").html($("#tech_note").html());
            $("#tech_note").html("");
        });
        </script>

        <div id="tech_note">
        <b>Attention:</b> The fields below should be filled <b>ONLY</b> in case you wish to use a custom <b>Technical Contact Email</b> for your SSL Certificates. Default Technical Email is the client\'s organization email. Using a custom Technical Email is useful for <b>resellers</b>, who wish to appear as the technical contact of there customer\'s SSL certificates.<br />
        &nbsp;&nbsp;* In order to use <b>Default Technical Email</b> leave ALL of the fields below empty.<br />
        &nbsp;&nbsp;* If you wish to use <b>Custom Technical Email</b> - fill in ALL of the fields below.<br />
        </div>
        ';

    return array(
        'Username' => array(
            'Type' => 'text', 
            'Size' => '25', 
            'Description' => 'Enter your (sandbox-)API username here.'
        ), 
        'API Password' => array(
            'Type' => 'password', 
            'Size' => '25', 
            'Description' => 'Enter your (sandbox-)API password here.'
        ), 
        'Certificate Type' => array(
            'Type' => 'dropdown', 
            'Options' => $certTypeList
        ),
        'Months' => array(
            'Type' => 'dropdown',
            'Options' => '1,3,12,24,36'
		),
		'Test Mode' => array(
            'Type' => 'yesno', 
            'Description' => 'Tick this to enable sandbox, you\'ll need a sandbox account!'
        ),
        '    ' => array('Description' => $additionalNotes),
        'Tech Email' => array(
            'Type' => 'text',
            'Size' => 20,
            'Description' => '<div id="techemail"></div>'
        ),
        'Tech Firstname' => array(
            'Type' => 'text',
            'Size' => 20,
            'Description' => ''
        ),
        'Tech Lastname' => array(
            'Type' => 'text',
            'Size' => 20,
            'Description' => ''
        ),
        'Tech Address1' => array(
            'Type' => 'text',
            'Size' => 20,
            'Description' => ''
        ),
        'Tech City' => array(
            'Type' => 'text',
            'Size' => 20,
            'Description' => ''
        ),
        'Tech State/Province' => array(
            'Type' => 'text',
            'Size' => 20,
            'Description' => ''
        ),
        'Tech Country' => array(
            'Type' => 'text',
            'Size' => 20,
            'Description' => '2 digit country code (uppercase)'
        ),
        'Tech Postal Code' => array(
            'Type' => 'text',
            'Size' => 20,
            'Description' => ''
        ),
        'Tech Phone' => array(
            'Type' => 'text',
            'Size' => 20,
            'Description' => 'NNNNNNNNNNNN (only numbers!)'
        ),
        'Tech Organization Name' => array(
            'Type' => 'text',
            'Size' => 20,
            'Description' => ''
        ),
    );
}

/**
 * 
 * CreateAccount() function is called when an new order is being processed.
 * 
 */
function gogetssl_CreateAccount($params) {
    global $CONFIG;
    
    $orderQuery = select_query('tblsslorders', '*', array('serviceid' => $params['serviceid']));
    
    if (mysql_num_rows($orderQuery) >= 1) {
        return 'An SSL Order already exists for this order';
    }
    
    $orderFetch = mysql_fetch_assoc($orderQuery);
    
    if (isset($params['configoptions']['Certificate Type'])) {
        $certType = $params['configoptions']['Certificate Type'];
    } else {
        $certTypeSplit = explode('(ID: ', $params['configoption3']);
        $certType = substr($certTypeSplit[1], 0, -1);
    }
    
    $queryData = array(
        'userid' => $params['clientsdetails']['userid'], 
        'serviceid' => $params['serviceid'], 
        'remoteid' => '', 
        'module' => 'gogetssl', 
        'certtype' => $certType, 
        'status' => 'Incomplete'
    );
    
    if (version_compare('4.5.2', $CONFIG['Version'], '<=')) {
        $queryData['status'] = 'Awaiting Configuration';
    }

    $sslOrderID = insert_query('tblsslorders', $queryData);
    
    $sendWelcome = false;
    if (!empty($_POST) && !empty($_POST['vars']['products'][$params['serviceid']]) && !empty($_POST['vars']['products'][$params['serviceid']]['sendwelcome'])) {
        $sendWelcome = true;
    }
    
    if (empty($_POST['vars']['products'][$params['serviceid']])) {
        $productQuery = mysql_query('SELECT autosetup FROM tblproducts WHERE id = ' . $params['packageid'] . ' LIMIT 1');
        $productFetch = mysql_fetch_assoc($productQuery);
        
        $sendWelcome = ($productFetch['autosetup'] == 'payment' || $productFetch['autosetup'] == 'order');
    }

    if ($sendWelcome) {
        $sslConfigurationLink = (($CONFIG['SystemSSLURL'] == '') ? $CONFIG['SystemURL'] : $CONFIG['SystemSSLURL']) . '/configuressl.php?cert=' . md5($sslOrderID);
        $sslConfigurationLink = '<a href="' . $sslConfigurationLink . '">' . $sslConfigurationLink . '</a>';
        sendMessage('SSL Certificate Configuration Required', $params['serviceid'], array('ssl_configuration_link' => $sslConfigurationLink));
    }

    return 'success';
}

/**
 * 
 * AdminServicesTabFields() function will return an array with information about the order for the WHMCS adminarea.
 * 
 */
function gogetssl_AdminServicesTabFields($params) {
    $orderQuery = select_query('tblsslorders', '*', array('serviceid' => $params['serviceid'], 'status' => 'Completed'));
    
    if (mysql_num_rows($orderQuery) < 1) {
        return 'No Completed SSL Order exists for this order';
    }
    
    $orderFetch = mysql_fetch_assoc($orderQuery);

    $postFields = array();
    $postFields['uid'] = $params['configoption1'];
    $postFields['pw'] = $params['configoption2'];
    $postFields['order_id'] = $orderFetch['remoteid'];
    $postFields['command'] = 'getOrderStatus';
    $statusResult = gogetssl_call($postFields, $params['configoption5']);

    if (isset($statusResult['error'])) {
        return $statusResult['description'];
    }
    
    if (isset($statusResult['success'])) {
        
        $fieldsArray = array(
            'Status' => $statusResult['status'], 
            'Domain' => $statusResult['domain'], 
            'Total Domains' => $statusResult['total_domains']
        );
        
        if (isset($statusResult['order_id']) && $statusResult['order_id'] != '') {
            $fieldsArray['Order id'] = $statusResult['order_id']; 
        }
        
        if (isset($statusResult['partner_order_id']) && $statusResult['partner_order_id'] != '') {
            $fieldsArray['Partner order id'] = $statusResult['partner_order_id']; 
        }
        
        if (isset($statusResult['status_description']) && $statusResult['status_description'] != '') {
            $fieldsArray['Status Description'] = $statusResult['status_description']; 
        }
        
        if ($statusResult['status'] == 'active') {
            $fieldsArray['Valid From'] = $statusResult['valid_from']; 
            $fieldsArray['Valid Till'] = $statusResult['valid_till'];
            
            $fieldsArray['CSR code'] = '<textarea name="csr_code" rows="10" cols="80">' . $statusResult['csr_code'] . '</textarea>';
            $fieldsArray['CRT code'] = '<textarea name="crt_code" rows="10" cols="80">' . $statusResult['crt_code'] . '</textarea>';
            $fieldsArray['CA code'] = '<textarea name="ca_code" rows="10" cols="80">' . $statusResult['ca_code'] . '</textarea>';
        }

        return $fieldsArray;
    }

    return null;
}

/**
 * 
 * ClientArea() function will return an array with the requested information for WHMCS, this will be used to display the right content within the clientarea product/order page.
 * 
 */
function gogetssl_ClientArea($params) {
    global $_LANG, $CONFIG;

    $orderQuery = full_query('SELECT * FROM tblsslorders WHERE serviceid = '.$params['serviceid'].' AND (status = "Incomplete" OR status = "Awaiting Configuration" OR status = "Completed")');

    if (mysql_num_rows($orderQuery) < 1) {
        return $_LANG['gogetssl_page_not_found_desc'];
    }

    $orderFetch = mysql_fetch_assoc($orderQuery);
    
    if ($orderFetch['status'] != 'Completed') {
        return array(
            'templatefile' => 'templates/clientarea', 
            'vars' => array(
                'goget_status' => $_LANG['gogetssl_status_awaiting_configuration'],
                'goget_raw_status' => 'awaiting_configuration',
                'configuration_url' => (($CONFIG['SystemSSLURL'] == '') ? $CONFIG['SystemURL'] : $CONFIG['SystemSSLURL']) . '/configuressl.php?cert=' . md5($orderFetch['id'])
            )
        );
    }
    
    $certQuery = full_query('SELECT * FROM tblhosting WHERE id = ' . $params['serviceid'] . ' AND billingcycle IN ("Annually", "Biennially", "Triennially") LIMIT 1');
    $certFetch = mysql_fetch_assoc($certQuery);

    $postFields = array();
    $postFields['uid'] = $params['configoption1'];
    $postFields['pw'] = $params['configoption2'];
    $postFields['order_id'] = $orderFetch['remoteid'];
    $postFields['command'] = 'getOrderStatus';
    $statusResult = gogetssl_call($postFields, $params['configoption5']);

    if (isset($statusResult['error'])) {
        return $_LANG['gogetssl_error_occured'] . $statusResult['description'];
    }

    $status = '';
    
    if (isset($statusResult['success'])) {
            
        if ($statusResult['status'] == 'active' && $certFetch) {
            $expiresDate = $statusResult['valid_till'];
            
            full_query('UPDATE tblhosting SET nextduedate = "' . $expiresDate . '", nextinvoicedate = "' . $expiresDate . '" WHERE id = ' . $params['serviceid']);
        }

        $status = $statusResult['status'];
        
        if (isset($_LANG['gogetssl_status_'.$status])) {
            $status = $_LANG['gogetssl_status_'.$status];
        }
    }
    
    if (isset($_GET['custom_page'])) {
        
        if (function_exists('gogetssl_page_' . $_GET['custom_page'])) {
            return call_user_func_array('gogetssl_page_' . $_GET['custom_page'], array($params, $statusResult, $orderFetch));
        } else {
            return array(
                'templatefile' => 'templates/notification', 
                'vars' => array(
                    'status' => 'error',
                    'title' => $_LANG['gogetssl_page_not_found_title'],
                    'description' => $_LANG['gogetssl_page_not_found_desc']
                )
            );
        }
        
    } else {
        return array(
            'templatefile' => 'templates/clientarea', 
            'vars' => array(
                'goget_status' => $status,
                'goget_order' => $statusResult
            )
        );
    }
}

/**
 * 
 * page_manage_validation() function will being called when the "manage_validation" page has to being loaded. 
 * 
 */
function gogetssl_page_manage_validation($params, $statusResult, $orderFetch) {
    global $CONFIG, $_LANG;
        
    if ($statusResult['status'] == 'processing') {
        
        $postFields = array();
        $postFields['uid'] = $params['configoption1'];
        $postFields['pw'] = $params['configoption2'];
        $postFields['product_id'] = $orderFetch['certtype'];
        $postFields['command'] = 'getProductDetails';
        $productDetails = gogetssl_call($postFields, $params['configoption5']);

        if (isset($productDetails['error'])) {
            return array(
                'templatefile' => 'templates/notification', 
                'vars' => array(
                    'status' => 'error',
                    'title' => $_LANG['gogetssl_error_occured'],
                    'description' => $productDetails['description']
                )
            );
        }
        
        if (isset($_POST['submit'])) {
            
            $validationMethods = array('dns', 'http', 'https');
            $postFields = array();
            
            if (isset($_POST['validation_method']) && in_array($_POST['validation_method'], $validationMethods) && $productDetails['product_brand'] == 'comodo') {
                
                switch ($_POST['validation_method']) {
                    
                    case 'dns':
                        $postFields['approver_email'] = 'dns';
                        break;

                    case 'https':
                        $postFields['approver_email'] = 'https';
                        break;

                    case 'http':
                    default:
                        $postFields['approver_email'] = 'http';
                        break;
                        
                }
                
            } else {
                //$postFields['dcv_method'] = 'email';
                $postFields['approver_email'] = $_POST['approver_email'];
            }
            
            $postFields['uid'] = $params['configoption1'];
            $postFields['pw'] = $params['configoption2'];
            $postFields['order_id'] = $orderFetch['remoteid'];
            $postFields['command'] = 'changeValidationEmail';
            $changeValidationResult = gogetssl_call($postFields, $params['configoption5']);
            
            if (isset($changeValidationResult['error'])) {
                return array(
                    'templatefile' => 'templates/notification', 
                    'vars' => array(
                        'status' => 'error',
                        'title' => $_LANG['gogetssl_error_occured'],
                        'description' => $changeValidationResult['description']
                    )
                );
            }
            
            // Again, this because of the wrong validation method, refresh cache.
            $postFields = array();
            $postFields['uid'] = $params['configoption1'];
            $postFields['pw'] = $params['configoption2'];
            $postFields['order_id'] = $orderFetch['remoteid'];
            $postFields['command'] = 'getOrderStatus';
            $statusResult = gogetssl_call($postFields, $params['configoption5']);

            if (isset($statusResult['error'])) {
                return $_LANG['gogetssl_error_occured'] . $statusResult['description'];
            }
                        
        }
        
        $allApproverEmails = array();
        
        if ($productDetails['product_brand'] == 'comodo') {
            $postFields = array();
            $postFields['uid'] = $params['configoption1'];
            $postFields['pw'] = $params['configoption2'];
            $postFields['domain'] = $statusResult['domain'];
            $postFields['command'] = 'getDomainEmails';
            $domainEmailsResult = gogetssl_call($postFields, $params['configoption5']);

            if (isset($domainEmailsResult['error'])) {
                return array(
                    'templatefile' => 'templates/notification',
                    'vars' => array(
                        'status' => 'error',
                        'title' => $_LANG['gogetssl_error_occured'],
                        'description' => $domainEmailsResult['description']
                    )
                );
            }

            $allApproverEmails = $domainEmailsResult['ComodoApprovalEmails'];
        } else {
            $postFields = array();
            $postFields['uid'] = $params['configoption1'];
            $postFields['pw'] = $params['configoption2'];
            $postFields['domain'] = $statusResult['domain'];
            $postFields['command'] = 'getDomainEmailsForGeotrust';
            $domainEmailsResult = gogetssl_call($postFields, $params['configoption5']);

            if (isset($domainEmailsResult['error'])) {
                return array(
                    'templatefile' => 'templates/notification',
                    'vars' => array(
                        'status' => 'error',
                        'title' => $_LANG['gogetssl_error_occured'],
                        'description' => $domainEmailsResult['description']
                    )
                );
            }

            $allApproverEmails = $domainEmailsResult['GeotrustApprovalEmails'];
        }
        
        return array(
            'templatefile' => 'templates/manage_validation', 
            'vars' => array(
                'goget_order' => $statusResult,
                'goget_product' => $productDetails,
                'goget_approver_emails' => $allApproverEmails,
            )
        );
    }else{
        
        header('location: '.(($CONFIG['SystemSSLURL'] == '') ? $CONFIG['SystemURL'] : $CONFIG['SystemSSLURL']).'/clientarea.php?action=productdetails&id='.$params['serviceid']);
        exit();
        
    }
}

/**
 * 
 * manage_validation() function will being called when the "manage_validation" button has been pressed, this will redirect the user to the same page with the "manage_validation" GET param.
 * 
 */
function gogetssl_manage_validation($params) {
    global $CONFIG;
    header('location: '.(($CONFIG['SystemSSLURL'] == '') ? $CONFIG['SystemURL'] : $CONFIG['SystemSSLURL']).'/clientarea.php?action=productdetails&id='.$params['serviceid'].'&custom_page=manage_validation');
    exit();
}

/**
 * 
 * page_reissue() function will being called when the "reissue" page has to being loaded. 
 * 
 */
function gogetssl_page_reissue($params, $statusResult, $orderFetch) {
    global $CONFIG, $_LANG;
    
    if ($statusResult['status'] == 'active') {
        
        $postFields = array();
        $postFields['uid'] = $params['configoption1'];
        $postFields['pw'] = $params['configoption2'];
        $postFields['product_id'] = $orderFetch['certtype'];
        $postFields['command'] = 'getProductDetails';
        $productDetails = gogetssl_call($postFields, $params['configoption5']);

        if (isset($productDetails['error'])) {
            return array(
                'templatefile' => 'templates/notification', 
                'vars' => array(
                    'status' => 'error',
                    'title' => $_LANG['gogetssl_error_occured'],
                    'description' => $productDetails['description']
                )
            );
        }
        
        if (isset($_POST['csr']) && isset($_POST['servertype']) && ctype_digit($_POST['servertype'])) {
            $validationMethods = array('email');

            if ($productDetails['product_brand'] == 'comodo') {
                $validationMethods = array_merge($validationMethods, array('http', 'https', 'dns'));
            }

            if (!isset($_POST['validation']) || !in_array($_POST['validation'], $validationMethods)) {
                $_POST['validation'] = 'email';
            }

            $_SESSION['gogetsslcert']['reissue'] = $_POST;
        
            $approverEmails = array();
            $reissueValues = array();
            $alternativeValues = array();
            $domains = array();
            
            $domains[] = $statusResult['domain'];
            
            if (isset($_POST['additional_domain_1'])) {
                foreach ($_POST as $k => $v) {
                    if (substr($k, 0, 18) == 'additional_domain_' && $v != '') {
                        $domains[] = $v;
                    }
                }
            }

            switch ($_POST['validation']) {
                case 'dns':
                case 'http':
                case 'https':
                    $postFields = array();
                    $postFields['uid'] = $params['configoption1'];
                    $postFields['pw'] = $params['configoption2'];
                    $postFields['csr'] = $_POST['csr'];
                    $postFields['command'] = 'getDomainAlternative';
                    $domainAlternativeResult = gogetssl_call($postFields, $params['configoption5']);

                    if (isset($domainAlternativeResult['error'])) {
                        return array(
                            'templatefile' => 'templates/notification',
                            'vars' => array(
                                'status' => 'error',
                                'title' => $_LANG['gogetssl_error_occured'],
                                'description' => $domainAlternativeResult['description']
                            )
                        );
                    }

                    $alternativeValues = $domainAlternativeResult['validation'];
                    break;

                default:
                    //We don't need to call something for all domains
                    break;
            }
            
            foreach ($domains as $domain) {
                switch ($_POST['validation']) {

                    case 'dns':
                        $reissueValues[$domain] = str_replace($statusResult['domain'], $domain, $alternativeValues['dns']['dns']['record']);
                        break;

                    case 'http':
                        $reissueValues[$domain] = array(
                            'link' => 'http://' . $domain . '/' . $alternativeValues['http']['http']['filename'],
                            'filename' => $alternativeValues['http']['http']['filename'],
                            'content' => $alternativeValues['http']['http']['content']
                        );
                        break;

                    case 'https':
                        $reissueValues[$domain] = array(
                            'link' => 'https://' . $domain . '/' . $alternativeValues['https']['https']['filename'],
                            'filename' => $alternativeValues['https']['https']['filename'],
                            'content' => $alternativeValues['https']['https']['content']
                        );;
                        break;


                    case 'email':
                    default:
                        if ($productDetails['product_brand'] == 'comodo') {
                            $postFields = array();
                            $postFields['uid'] = $params['configoption1'];
                            $postFields['pw'] = $params['configoption2'];
                            $postFields['domain'] = $domain;
                            $postFields['command'] = 'getDomainEmails';
                            $domainEmailsResult = gogetssl_call($postFields, $params['configoption5']);

                            if (isset($domainEmailsResult['error'])) {
                                return array(
                                    'templatefile' => 'templates/notification',
                                    'vars' => array(
                                        'status' => 'error',
                                        'title' => $_LANG['gogetssl_error_occured'],
                                        'description' => $domainEmailsResult['description']
                                    )
                                );
                            }

                            $approverEmails[$domain] = $domainEmailsResult['ComodoApprovalEmails'];
                        } else {
                            $postFields = array();
                            $postFields['uid'] = $params['configoption1'];
                            $postFields['pw'] = $params['configoption2'];
                            $postFields['domain'] = $domain;
                            $postFields['command'] = 'getDomainEmailsForGeotrust';
                            $domainEmailsResult = gogetssl_call($postFields, $params['configoption5']);

                            if (isset($domainEmailsResult['error'])) {
                                return array(
                                    'templatefile' => 'templates/notification',
                                    'vars' => array(
                                        'status' => 'error',
                                        'title' => $_LANG['gogetssl_error_occured'],
                                        'description' => $domainEmailsResult['description']
                                    )
                                );
                            }

                            $approverEmails[$domain] =  $domainEmailsResult['GeotrustApprovalEmails'];
                        }
                        break;
                }
            }

            if ($_POST['validation'] == 'email') {
                return array(
                    'templatefile' => 'templates/reissue_email',
                    'vars' => array(
                        'goget_order' => $statusResult,
                        'goget_product' => $productDetails,
                        'goget_approver_emails' => $approverEmails
                    )
                );
            } else {
                return array(
                    'templatefile' => 'templates/reissue_' . $_POST['validation'],
                    'vars' => array(
                        'goget_order' => $statusResult,
                        'goget_product' => $productDetails,
                        'goget_reissue_values' => $reissueValues
                    )
                );
            }
            
        } elseif ((isset($_POST['approver_email_0']) && $_POST['approver_email_0'] != '') || isset($_POST['next'])) {
            
            $_POST = array_merge($_SESSION['gogetsslcert']['reissue'], $_POST);
            
            $postFields = array();
            $postFields['uid'] = $params['configoption1'];
            $postFields['pw'] = $params['configoption2'];
            $postFields['csr'] = $_POST['csr'];
            $postFields['product_id'] = $orderFetch['certtype'];
            
            if ($productDetails['product_brand'] == 'comodo') {
                $postFields['brand'] = 1;
            } else {
                $postFields['brand'] = 2;
            }

            
            if ($productDetails['product_wildcard'] == 'yes') {
                $postFields['wildcard'] = 1;
            } else {
                $postFields['wildcard'] = 0;
            }

            $postFields['command'] = 'decodeCSR';
            $csrTest = gogetssl_call($postFields, $params['configoption5']);
            
            if ($csrTest['error']) {
                return array(
                    'templatefile' => 'templates/notification', 
                    'vars' => array(
                        'status' => 'error',
                        'title' => $_LANG['gogetssl_error_occured'],
                        'description' => $csrTest['description']
                    )
                );
            }
            
            $postFields = array();
            $postFields['uid'] = $params['configoption1'];
            $postFields['pw'] = $params['configoption2'];
            if ($_POST['validation'] == 'email') {
                $postFields['approver_email'] = $_POST['approver_email_0'];
            }
            $postFields['dcv_method'] = $_POST['validation'];
            $postFields['csr'] = $_POST['csr'];
            $postFields['webserver_type'] = 1;
            $postFields['signature_hash'] = ((isset($_SESSION['gogetsslcert']['reissue']['hashing'])) && in_array($_SESSION['gogetsslcert']['reissue']['hashing'], array('SHA1', 'SHA2')) ? $_SESSION['gogetsslcert']['reissue']['hashing'] : 'SHA2');
            
            if (isset($_POST['additional_domain_1']) && $_POST['validation'] == 'email') {
                $postFields['dns_names'] = array();
                $postFields['approver_emails'] = array();
                
                $i = 1;
                
                foreach ($_POST as $k => $v) {
                    if (substr($k, 0, 18) == 'additional_domain_' && $v != '') {                        
                        $postFields['dns_names'][] = $v;
                        $postFields['approver_emails'][] = ((isset($_POST['approver_email_'.$i])) ? $_POST['approver_email_'.$i] : '');
                        
                        $i++;
                    }
                }
                
                if (empty($postFields['dns_names'])) {
                    unset($postFields['dns_names']);
                } else {
                    $postFields['dns_names'] = implode(',', $postFields['dns_names']);
                    $postFields['approver_emails'] = implode(',', $postFields['approver_emails']);
                }
            }
            
            $postFields['order_id'] = $orderFetch['remoteid'];
            $postFields['command'] = 'reIssueOrder';
            $reissue = gogetssl_call($postFields, $params['configoption5']);
            
            if ($reissue['error']) {
                return array(
                    'templatefile' => 'templates/notification', 
                    'vars' => array(
                        'status' => 'error',
                        'title' => $_LANG['gogetssl_error_occured'],
                        'description' => $reissue['description']
                    )
                );
            }else{
                unset($_SESSION['gogetsslcert']);
                
                return array(
                    'templatefile' => 'templates/notification', 
                    'vars' => array(
                        'status' => 'success',
                        'description' => $_LANG['gogetssl_reissue_successful'],
                        'url' => (($CONFIG['SystemSSLURL'] == '') ? $CONFIG['SystemURL'] : $CONFIG['SystemSSLURL']).'/clientarea.php?action=productdetails&id='.$params['serviceid']
                    )
                );
            }
            
        }
        
        $additionalDomains = array();
        
        if (isset($statusResult['domains'])) {
            
            $dnsNames = explode(',', $statusResult['domains']);
            
            for ($i = 1; $i <= ($statusResult['total_domains'] - 1); $i++) {
                
                $additionalDomains[$i] = ((isset($dnsNames[($i - 1)])) ? $dnsNames[($i - 1)] : '');
                
            }
            
        }

        return array(
            'templatefile' => 'templates/reissue', 
            'vars' => array(
                'webservertypes' => gogetssl_getSSLWebServerTypes(), 
                'goget_order' => $statusResult,
                'goget_product' => $productDetails,
                'goget_additional_domains' => $additionalDomains,
            )
        );
    }else{
        
        header('location: '.(($CONFIG['SystemSSLURL'] == '') ? $CONFIG['SystemURL'] : $CONFIG['SystemSSLURL']).'/clientarea.php?action=productdetails&id='.$params['serviceid']);
        exit();
        
    }
}

/**
 * 
 * reissue() function will being called when the "reissue" button has been pressed, this will redirect the user to the same page with the "reissue" GET param.
 * 
 */
function gogetssl_reissue($params) {
    global $CONFIG;
    header('location: '.(($CONFIG['SystemSSLURL'] == '') ? $CONFIG['SystemURL'] : $CONFIG['SystemSSLURL']).'/clientarea.php?action=productdetails&id='.$params['serviceid'].'&custom_page=reissue');
    exit();
}

/**
 * 
 * resend_conf() function will being called when the "resend_conf" button has been pressed, this will resend the configuration email.
 * 
 */
function gogetssl_resend_conf($params) {
    global $_LANG, $CONFIG;
    
    $orderQuery = full_query('SELECT * FROM tblsslorders WHERE serviceid = '.$params['serviceid'].' AND (status = "Incomplete" OR status = "Awaiting Configuration")');
    
    if (mysql_num_rows($orderQuery) < 1) {
        return $_LANG['gogetssl_error_order_already_configured'];
    }
    
    $orderFetch = mysql_fetch_assoc($orderQuery);
    
    $sslConfigurationLink = (($CONFIG['SystemSSLURL'] == '') ? $CONFIG['SystemURL'] : $CONFIG['SystemSSLURL']) . '/configuressl.php?cert=' . md5($orderFetch['id']);
    $sslConfigurationLink = '<a href="' . $sslConfigurationLink . '">' . $sslConfigurationLink . '</a>';
    
    sendMessage('SSL Certificate Configuration Required', $params['serviceid'], array('ssl_configuration_link' => $sslConfigurationLink));
    
    return 'success';
}

/**
 * 
 * resend_val() function will being called when the "resend_val" button has been pressed, this will resend the validation email.
 * 
 */
function gogetssl_resend_val($params) {
    global $_LANG, $CONFIG;
    
    $orderQuery = select_query('tblsslorders', '*', array('serviceid' => $params['serviceid'], 'status' => 'Completed'));
    
    if (mysql_num_rows($orderQuery) < 1) {
        return $_LANG['gogetssl_no_certificate_exists'];
    }
    
    $orderFetch = mysql_fetch_assoc($orderQuery);
    
    $postFields = array();
    $postFields['uid'] = $params['configoption1'];
    $postFields['pw'] = $params['configoption2'];
    $postFields['order_id'] = $orderFetch['remoteid'];
    $postFields['command'] = 'resendEmail';
    
    $statusResult = gogetssl_call($postFields, $params['configoption5']);
        
    if (isset($statusResult['error'])) {
        return $_LANG['gogetssl_error_occured'] . $statusResult['description'];
    }    
    
    return 'success';
}

/**
 * 
 * ClientAreaCustomButtonArray() function will return an array with available actions for the clientarea.
 * 
 */
function gogetssl_ClientAreaCustomButtonArray($params) {
    global $_LANG, $CONFIG;
    
    $buttonArray = array();
    
    $orderQuery = select_query('tblsslorders', '*', array('serviceid' => $params['serviceid'], 'status' => 'Completed'));
    
    if (mysql_num_rows($orderQuery) < 1) {
        $buttonArray[$_LANG['gogetssl_resend_conf']] = 'resend_conf';
        
        return $buttonArray;
    }
    
    $orderFetch = mysql_fetch_assoc($orderQuery);

    $postFields = array();
    $postFields['uid'] = $params['configoption1'];
    $postFields['pw'] = $params['configoption2'];
    $postFields['order_id'] = $orderFetch['remoteid'];
    $postFields['command'] = 'getOrderStatus';
    $statusResult = gogetssl_call($postFields, $params['configoption5']);

    if (isset($statusResult['error'])) {
        return $buttonArray;
    }
    
    if ($statusResult['status'] == 'active') {
        $buttonArray[$_LANG['gogetssl_reissue']] = 'reissue';
    } elseif ($statusResult['status'] == 'processing') {
        if ($statusResult['dcv_method'] == 'email')
            $buttonArray[$_LANG['gogetssl_resend_val']] = 'resend_val';
        
        $buttonArray[$_LANG['gogetssl_manage_validation_method']] = 'manage_validation';
    }
    
    return $buttonArray;
}

/**
 * 
 * AdminCustomButtonArray() function will return an array of possible actions within the WHMCS adminarea.
 * 
 */
function gogetssl_AdminCustomButtonArray() {
    return array(
        'Activate Order' => 'activate',
        'Cancel' => 'cancel', 
        'Manage SSL certificate' => 'manage_ssl', 
    );
}


/**
 * 
 * manage_ssl() function will pass the admin to the clientarea, because this is more stable.
 * 
 */
function gogetssl_manage_ssl($params) {
    global $CONFIG;
    echo '<center>Redirecting.. Please wait.</center><script> window.location = "'.(($CONFIG['SystemSSLURL'] == '') ? $CONFIG['SystemURL'] : $CONFIG['SystemSSLURL']).'/dologin.php?username='.get_query_val('tblclients', 'email', array('id' => $params['userid'])).'&goto='.urlencode('clientarea.php?action=productdetails&id='.$params['serviceid']).'"; </script>';
    exit();
}

/**
 * 
 * cancel() function will cancel an incomplete SSL order within WHMCS from the adminarea.
 * 
 */
function gogetssl_cancel($params) {
    $orderQuery = full_query('SELECT * FROM tblsslorders WHERE serviceid = '.$params['serviceid'].' AND (status = "Incomplete" OR status = "Awaiting Configuration")');
    
    if (mysql_num_rows($orderQuery) < 1) {
        return 'No Incomplete SSL Order exists for this order';
    }

    update_query('tblsslorders', array('status' => 'Cancelled'), array('serviceid' => $params['serviceid']));
    
    return 'success';
}

/**
 * 
 * SSLStepOne() function will prepare step one for the SSL configuration page.
 * 
 */
function gogetssl_SSLStepOne($params) {
    global $_LANG;
    
    $orderID = $params['remoteid'];
    $returnValues = array();
    
    if (isset($_SESSION['gogetsslcert'][$orderID]['status'])) {
        
        $postFields = array();
        $postFields['uid'] = $params['configoption1'];
        $postFields['pw'] = $params['configoption2'];
        $postFields['order_id'] = $orderID;
        $postFields['command'] = 'getOrderStatus';
        $statusResult = gogetssl_call($postFields, $params['configoption5']);
        
        if (isset($statusResult['error'])) {
            $returnValues['error'] = $_LANG['gogetssl_error_occured'] . $statusResult['description'];
            return $returnValues;
        }
        
        if (isset($statusResult['success'])) {
            
            if ($statusResult['status'] == 'cancelled') {
                update_query('tblsslorders', array('completiondate' => '', 'status' => 'Cancelled'), array('serviceid' => $params['serviceid']));
            }

            
            if ($statusResult['status'] == 'active') {
                update_query('tblsslorders', array('completiondate' => 'now()', 'status' => 'Completed'), array('serviceid' => $params['serviceid'], 'status' => array('sqltype' => 'NEQ', 'value' => 'Completed')));
            }

        }

        $values['displaydata']['Domain'] = $statusResult['domain'];
        $values['displaydata']['Validity Period'] = sprintf($_LANG['gogetssl_validity_period'], $statusResult['validity_period']);
        $values['displaydata']['Expiration Date'] = $statusResult['valid_till'];
        
        $_SESSION['gogetsslcert'][$orderID]['status'] = true;
    }

    $postFields = array();
    $postFields['uid'] = $params['configoption1'];
    $postFields['pw'] = $params['configoption2'];
    $postFields['product_id'] = $params['certtype'];
    $postFields['command'] = 'getProductDetails';
    $productResult = gogetssl_call($postFields, $params['configoption5']);
    
    if (isset($productResult['error'])) {
        $returnValues['error'] = $_LANG['gogetssl_error_occured'] . $productResult['description'];
        return $returnValues;
    }

    
    if (isset($productResult['success'])) {
        $_SESSION['gogetsslcert'][$orderID]['product_details'] = $productResult;
    }

    if ($_SESSION['gogetsslcert'][$orderID]['product_details']['product_is_multidomain'] == 'yes') {
        $sanOption = 'SAN';

        foreach($params['configoptions'] as $k => $v) {
            if (stripos($k, 'SAN') !== false) {
                $sanOption = $k;
            }
        }

        if (isset($params['configoptions'][$sanOption])) {
            $sanMax = $_SESSION['gogetsslcert'][$orderID]['product_details']['product_multidomains_included'] + $params['configoptions'][$sanOption];
        } else {
            $sanMax = $_SESSION['gogetsslcert'][$orderID]['product_details']['product_multidomains_included'];
        }

        $sanConfiguration = array();

        //One less because of the domain within the CSR.
        for($i = 1; $i <= ($sanMax - 1); $i++){
            
            $sanConfiguration['san_' . $i] = array(
                'FriendlyName' => sprintf($_LANG['gogetssl_san_domain_name'], $i), 
                'Type' => 'text', 
                'Size' => '30', 
                'Description' => '', 
                'Required' => false
            );
            
        }

        $_SESSION['gogetsslcert'][$orderID]['san_total'] = $sanMax;
        $returnValues['additionalfields'][$_LANG['gogetssl_san_configuration']] = $sanConfiguration;
    }
    
    if ($_SESSION['gogetsslcert'][$orderID]['product_details']['product_organization'] == 'yes') {
        
        $returnValues['additionalfields'][$_LANG['gogetssl_organization_data']] = array(
            'org_name' => array(
                'FriendlyName' => $_LANG['gogetssl_organization_company_name'],
                'Type' => 'text',
                'Size' => '30',
                'Description' => '',
                'Required' => true
            ) ,
            'org_division' => array(
                'FriendlyName' => $_LANG['gogetssl_organization_division'],
                'Type' => 'text',
                'Size' => '30',
                'Description' => $_LANG['gogetssl_organization_division_or_department_desc'],
                'Required' => true
            ) ,
            'org_duns' => array(
                'FriendlyName' => $_LANG['gogetssl_organization_duns'],
                'Type' => 'text',
                'Size' => '30',
                'Description' => $_LANG['gogetssl_data_universal_numbering_system_desc']
            ) ,
            'org_addressline1' => array(
                'FriendlyName' => $_LANG['gogetssl_organization_address'],
                'Type' => 'text',
                'Size' => '30',
                'Description' => '',
                'Required' => true
            ) ,
            'org_city' => array(
                'FriendlyName' => $_LANG['gogetssl_organization_city'],
                'Type' => 'text',
                'Size' => '30',
                'Description' => '',
                'Required' => true
            ) ,
            'org_region' => array(
                'FriendlyName' => $_LANG['gogetssl_organization_state_province'],
                'Type' => 'text',
                'Size' => '30',
                'Description' => '',
                'Required' => true
            ) ,
            'org_postalcode' => array(
                'FriendlyName' => $_LANG['gogetssl_organization_postal_code'],
                'Type' => 'text',
                'Size' => '30',
                'Description' => '',
                'Required' => true
            ) ,
            'org_country' => array(
                'FriendlyName' => $_LANG['gogetssl_organization_country'],
                'Type' => 'country',
                'Description' => '',
                'Required' => true
            ) ,
            'org_phone' => array(
                'FriendlyName' => $_LANG['gogetssl_organization_phone_number'],
                'Type' => 'text',
                'Size' => '30',
                'Description' => '',
                'Required' => true
            ) ,
            'org_fax' => array(
                'FriendlyName' => $_LANG['gogetssl_organization_fax_number'],
                'Type' => 'text',
                'Size' => '30',
                'Description' => ''
            )
        );
        
    }

    return $returnValues;
}

/**
 * 
 * SSLStepTwo() function will check everything from step one and prepare step two for the SSL configuration page.
 * 
 */
function gogetssl_SSLStepTwo($params) {
    global $_LANG, $smarty;

    $orderID = $params['remoteid'];
    $returnValues = array();
    
    if (empty($params['firstname'])) {
        $returnValues['error'] .= '- ' . $_LANG['gogetssl_error_firstname_missing'] . '<br/>';
    }
    
    if (empty($params['lastname'])) {
        $returnValues['error'] .= '- ' . $_LANG['gogetssl_error_lastname_missing'] . '<br/>';
    }
    
    if (empty($params['email'])) {
        $returnValues['error'] .= '- ' . $_LANG['gogetssl_error_e-mail_missing'] . '<br/>';
    }
    
    if (empty($params['address1'])) {
        $returnValues['error'] .= '- ' . $_LANG['gogetssl_error_address_missing'] . '<br/>';
    }
    
    if (empty($params['city'])) {
        $returnValues['error'] .= '- ' . $_LANG['gogetssl_error_city_missing'] . '<br/>';
    }
    
    if (empty($params['state'])) {
        $returnValues['error'] .= '- ' . $_LANG['gogetssl_error_state_missing'] . '<br/>';
    }
    
    if (empty($params['country'])) {
        $returnValues['error'] .= '- ' . $_LANG['gogetssl_error_country_missing'] . '<br/>';
    }

    if (empty($params['phonenumber'])) {
        $returnValues['error'] .= '- ' . $_LANG['gogetssl_error_phone_missing'] . '<br/>';
    }
    
    if ($_SESSION['gogetsslcert'][$orderID]['product_details']['product_organization'] == 'yes') {
        
        if (empty($params['orgname'])) {
            $returnValues['error'] .= '- ' . $_LANG['gogetssl_error_organization_missing'] . '<br/>';
        }

        
        if (empty($params['jobtitle'])) {
            $returnValues['error'] .= '- ' . $_LANG['gogetssl_error_job_Title_missing'] . '<br/>';
        }

    } else {
        
        if (empty($params['jobtitle'])) {
            $params['jobtitle'] = 'n/a';
        }

    }
    
    if (isset($returnValues['error'])) {
        return $returnValues;
    }

    $postFields = array();
    $postFields['uid'] = $params['configoption1'];
    $postFields['pw'] = $params['configoption2'];
    $postFields['csr'] = $params['csr'];
    $postFields['product_id'] = $params['certtype'];
    
    if ($_SESSION['gogetsslcert'][$orderID]['product_details']['product_brand'] == 'comodo') {
        $postFields['brand'] = 1;
    } else {
        $postFields['brand'] = 2;
    }

    
    if ($_SESSION['gogetsslcert'][$orderID]['product_details']['product_wildcard'] == 'yes') {
        $postFields['wildcard'] = 1;
    } else {
        $postFields['wildcard'] = 0;
    }

    $postFields['command'] = 'decodeCSR';
    $decodeResult = gogetssl_call($postFields, $params['configoption5']);
    
    if (isset($decodeResult['error'])) {
        $returnValues['error'] = $_LANG['gogetssl_error_occured'] . $decodeResult['description'];
        return $returnValues;
    }

    if (isset($decodeResult['success'])) {
        $csrData = $decodeResult['csrResult'];
        $_SESSION['gogetsslcert'][$orderID]['csr_result'] = $csrData;
    }
    
    if ($_SESSION['gogetsslcert'][$orderID]['product_details']['product_is_multidomain'] == 'yes') {
        $csrSans = array();
        $formSans = array();
        
        if (isset($csrData['dnsName(s)'])) {
            $csrSans = explode(',', $csrData['dnsName(s)']);
        }

        foreach ($params['fields'] as $k => $v) {
            if(substr($k, 0, 3) == 'san' && !empty($v))
                $formSans[] = $v;
        }

        $csrSans[] = $csrData['CN'];
        $totalSans = array_merge($csrSans, $formSans);
        $totalSans = array_filter($totalSans);
        $totalSans = array_unique($totalSans);
        
        $sanMax = $_SESSION['gogetsslcert'][$orderID]['san_total'];
        
        if ($sanMax < count($totalSans)) {
            return array('error' => sprintf($_LANG['gogetssl_san_max_count_error'], $sanMax));
        }
    }

    $approverEmails = array();

    if ($_SESSION['gogetsslcert'][$orderID]['product_details']['product_brand'] == 'comodo') {
        $postFields = array();
        $postFields['uid'] = $params['configoption1'];
        $postFields['pw'] = $params['configoption2'];
        $postFields['domain'] = $csrData['CN'];
        $postFields['command'] = 'getDomainEmails';
        $domainEmailsResult = gogetssl_call($postFields, $params['configoption5']);

        if (isset($domainEmailsResult['error'])) {
            $returnValues['error'] = $_LANG['gogetssl_error_occured'] . $domainEmailsResult['description'];
            return $returnValues;
        }

        if (isset($domainEmailsResult['ComodoApprovalEmails'])) {
            foreach ($domainEmailsResult['ComodoApprovalEmails'] as $k => $v) {
                if (!empty($v)) {
                    $approverEmails[] = $v;
                }
            }
        }

    } else {
        $postFields = array();
        $postFields['uid'] = $params['configoption1'];
        $postFields['pw'] = $params['configoption2'];
        $postFields['domain'] = $csrData['CN'];
        $postFields['command'] = 'getDomainEmailsForGeotrust';
        $domainEmailsResult = gogetssl_call($postFields, $params['configoption5']);

        if (isset($domainEmailsResult['error'])) {
            $returnValues['error'] = $_LANG['gogetssl_error_occured'] . $domainEmailsResult['description'];
            return $returnValues;
        }

        if (isset($domainEmailsResult['GeotrustApprovalEmails'])) {
            foreach ($domainEmailsResult['GeotrustApprovalEmails'] as $k => $v) {
                if (!empty($v)) {
                    $approverEmails[] = $v;
                }
            }
        }
    }

    $returnValues['approveremails'] = $approverEmails;
    $returnValues['displaydata']['Domain'] = $csrData['CN'];
    $returnValues['displaydata']['Organization'] = $csrData['O'];
    $returnValues['displaydata']['Organization Unit'] = $csrData['OU'];
    $returnValues['displaydata']['Email'] = $csrData['Email'];
    $returnValues['displaydata']['Locality'] = $csrData['L'];
    $returnValues['displaydata']['State'] = $csrData['S'];
    $returnValues['displaydata']['Country'] = $csrData['C'];
    
    $sans = '';
    $emails = '';
    $sanDomains = array();
    
    if ($_SESSION['gogetsslcert'][$orderID]['product_details']['product_is_multidomain'] == 'yes') {
        $i = 0;
        
        foreach ($totalSans as $san) {
            
            if ($san != $csrData['CN']) {
                
                $sanDomains[$i]['domain'] = $san;

                $sanApproverEmails = array();


                if ($_SESSION['gogetsslcert'][$orderID]['product_details']['product_brand'] == 'comodo') {
                    $postFields = array();
                    $postFields['uid'] = $params['configoption1'];
                    $postFields['pw'] = $params['configoption2'];
                    $postFields['domain'] = $san;
                    $postFields['command'] = 'getDomainEmails';
                    $domainEmailsResult = gogetssl_call($postFields, $params['configoption5']);

                    if (isset($domainEmailsResult['error'])) {
                        $returnValues['error'] = $_LANG['gogetssl_error_occured'] . $domainEmailsResult['description'];
                        return $returnValues;
                    }

                    if (isset($domainEmailsResult['ComodoApprovalEmails'])) {
                        foreach ($domainEmailsResult['ComodoApprovalEmails'] as $k => $v) {
                            if (!empty($v)) {
                                $sanApproverEmails[] = $v;
                            }
                        }
                    }
                } else {
                    $postFields = array();
                    $postFields['uid'] = $params['configoption1'];
                    $postFields['pw'] = $params['configoption2'];
                    $postFields['domain'] = $san;
                    $postFields['command'] = 'getDomainEmailsForGeotrust';
                    $domainEmailsResult = gogetssl_call($postFields, $params['configoption5']);

                    if (isset($domainEmailsResult['error'])) {
                        $returnValues['error'] = $_LANG['gogetssl_error_occured'] . $domainEmailsResult['description'];
                        return $returnValues;
                    }

                    if (isset($domainEmailsResult['GeotrustApprovalEmails'])) {
                        foreach ($domainEmailsResult['GeotrustApprovalEmails'] as $k => $v) {
                            if (!empty($v)) {
                                $sanApproverEmails[] = $v;
                            }
                        }
                    }
                }

                $sanDomains[$i]['emails'] = $sanApproverEmails;
                $sans .= $san . ',';
                
                $i++;
                
            }
        }

        $sans = substr($sans, 0, -1);
        $values['displaydata']['SANs'] = $sans;
        $values['san_domains'] = $sanDomains;
        
        if (!empty($sanDomains)) {
            $smarty->assign('san_enabled', 1);
            $smarty->assign('san_domains', $sanDomains);
        }
    }
    
    update_query('tblhosting', array('domain' => $returnValues['displaydata']['Domain']), array('id' => $params['serviceid']));

    $_SESSION['gogetsslcert'][$orderID]['csr'] = $params['csr'];
    $_SESSION['gogetsslcert'][$orderID]['address1'] = $params['address1'];
    $_SESSION['gogetsslcert'][$orderID]['postcode'] = $params['postcode'];
    $_SESSION['gogetsslcert'][$orderID]['hashing'] = ((isset($params['hashing']) && in_array($params['hashing'], array('SHA1', 'SHA2'))) ? $params['hashing'] :  'SHA2');
    
    $postFields = array();
    $postFields['uid'] = $params['configoption1'];
    $postFields['pw'] = $params['configoption2'];
    $postFields['product_id'] = $params['certtype'];
    

    $cycles = array('Annually' => 1, 'Biennially' => 2, 'Triennially' => 3);
    $serviceId = (int)$params['serviceid'];
    $service = mysql_fetch_assoc(mysql_query('select * from tblhosting where id = "' . $serviceId . '"'));
    $certyears_recurring = $cycles[$service['billingcycle']];

    if ($certyears_recurring) {
        $certyears = $certyears_recurring * 12;
    } else {
        $certyears = $params['configoption4'];
    }

    $postFields['period'] = $certyears;
    $postFields['webserver_type'] = $params['servertype'];
    $postFields['csr'] = $params['csr'];
    $postFields['server_count'] = '1';
    
    if ($_SESSION['gogetsslcert'][$orderID]['product_details']['product_is_multidomain'] == 'yes') {
        $postFields['dns_names'] = $sans;
    }

    if (isset($params['configoption7']) && !empty($params['configoption7'])) {
        $contactTypes = array('admin_');

        $postFields['tech_firstname'] = $params['configoption8'];
        $postFields['tech_lastname'] = $params['configoption9'];
        $postFields['tech_organization'] = $params['configoption16'];
        $postFields['tech_title'] = 'Technical';
        $postFields['tech_address1'] = $params['configoptio10'];
        $postFields['tech_address2'] = '';
        $postFields['tech_city'] = $params['configoption11'];
        $postFields['tech_region'] = $params['configoption12'];
        $postFields['tech_postalcode'] = $params['configoption14'];
        $postFields['tech_country'] = $params['configoption13'];
        $postFields['tech_phone'] = $params['configoption15'];
        $postFields['tech_fax'] = $params['configoption15'];
        $postFields['tech_email'] =  $params['configoption7'];
    } else {
        $contactTypes = array('admin_', 'tech_');
    }

    foreach ($contactTypes as $contactType) {
        $postFields[$contactType . 'firstname'] = $params['firstname'];
        $postFields[$contactType . 'lastname'] = $params['lastname'];
        $postFields[$contactType . 'organization'] = $params['orgname'];
        $postFields[$contactType . 'title'] = $params['jobtitle'];
        $postFields[$contactType . 'address1'] = $params['address1'];
        $postFields[$contactType . 'address2'] = $params['address2'];
        $postFields[$contactType . 'city'] = $params['city'];
        $postFields[$contactType . 'region'] = $params['state'];
        $postFields[$contactType . 'postalcode'] = $params['postcode'];
        $postFields[$contactType . 'country'] = $params['country'];
        $postFields[$contactType . 'phone'] = $params['phonenumber'];
        $postFields[$contactType . 'fax'] = (($params['faxnumber'] != '') ? $params['faxnumber'] : $params['phonenumber']);
        $postFields[$contactType . 'email'] =  $params['email'];
    }

    
    if (!empty($params['fields'])) {
        foreach ($params['fields'] as $k => $v) {
            $postFields[$k] = $v;
        }
    }

    $_SESSION['gogetsslcert'][$orderID]['order_details'] = $postFields;

    return $returnValues;
}

/**
 * 
 * SSLStepThree() function will check everything from step two and activates SSL certificate.
 * 
 */
function gogetssl_SSLStepThree($params) {
    global $CONFIG, $_LANG;
    
    $orderID = $params['remoteid'];
    $returnValues = array();
    
    if (empty($params['approveremail'])) {
        $returnValues['error'] = 'You need to choose approver email for SSL validation';
        return $returnValues;
    }
    
    $orderQuery = select_query('tblsslorders', '*', array('serviceid' => $params['serviceid'], 'status' => 'Completed'));
    
    if (mysql_num_rows($orderQuery) >= 1) {
        unset($_SESSION['gogetsslcert']);
        return $_LANG['gogetssl_error_occured'] . $_LANG['gogetssl_error_order_already_configured'];
    }
    
    $orderFetch = mysql_fetch_assoc($orderQuery);
    
    $postFields = array();
    
    foreach ($_SESSION['gogetsslcert'][$orderID]['order_details'] as $k => $v)
        $postFields[$k] = $v;
    
    $sansEmails = '';

    if ($_SESSION['gogetsslcert'][$orderID]['product_details']['product_is_multidomain'] == 'yes') {
        $sansDomains = explode(',', $postFields['dns_names']);

        if (!empty($sansDomains)) {
            foreach ($sansDomains as $san) {
                $san = trim($san);
                
                if ($_POST['san_approveremail'][$san] == 'The Domain Name is an Intranet Server Name or Intranet IP Address!') {
                    $sansEmails .= 'none,';
                    continue;
                }

                $sansEmails .= $_POST['san_approveremail'][$san] . ',';
            }
        }

        
        if (!empty($sansEmails)) {
            $postFields['approver_emails'] = substr($sansEmails, 0, -1);
        }
    }

    $postFields['csr'] = $_SESSION['gogetsslcert'][$orderID]['csr'];
    $postFields['signature_hash'] = $_SESSION['gogetsslcert'][$orderID]['hashing'];
    $postFields['webserver_type'] = 1;
    $postFields['dcv_method'] = 'email';
    $postFields['approver_email'] = (($params['approveremail'] == 'The Domain Name is an Intranet Server Name or Intranet IP Address!') ? 'none' : $params['approveremail']);
    $postFields['only_validate'] = 1;
    $postFields['command'] = 'addSSLOrder';
    
    $testOrderResult = gogetssl_call($postFields, $params['configoption5']);

    if (isset($testOrderResult['error'])) {
        $returnValues['error'] = $_LANG['gogetssl_error_occured'] . $testOrderResult['description'];
        return $returnValues;
    }

    if ($testOrderResult['message'] == 'valid') {
        $_SESSION['gogetsslcert'][$orderID]['order_details'] = $postFields;
    }
    
    unset($postFields['only_validate']);
    
    $addOrderResult = gogetssl_call($postFields, $params['configoption5']);

    if (isset($addOrderResult['error'])) {
        $returnValues['error'] = $_LANG['gogetssl_error_occured'] . $addOrderResult['description'];
        return $returnValues;
    }
    
    if (isset($addOrderResult['success'])) {
        update_query('tblsslorders', array('remoteid' => $addOrderResult['order_id'], 'completiondate' => 'now()', 'status' => 'Completed'), array('serviceid' => $params['serviceid']));
    }

    unset($_SESSION['gogetsslcert']);
    return $returnValues;
}

/**
 * 
 * Renew() function will being called when the renew invoice has been paid.
 * 
 */
function gogetssl_renew($params) {
    global $CONFIG, $_LANG;
    
    $orderQuery = select_query('tblsslorders', '*', array('serviceid' => $params['serviceid'], 'status' => 'Completed'));
    
    if (mysql_num_rows($orderQuery) < 1) {
        logActivity('GoGetSSL Renew error: Could not find completed order; serviceid: ' . $params['serviceid']);
        return;
    }
    
    $orderFetch = mysql_fetch_assoc($orderQuery);
    
    $postFields = array();
    $postFields['uid'] = $params['configoption1'];
    $postFields['pw'] = $params['configoption2'];
    $postFields['order_id'] = $orderFetch['remoteid'];
    $postFields['command'] = 'getOrderStatus';
    $statusResult = gogetssl_call($postFields, $params['configoption5']);
    
    if (isset($statusResult['error'])) {
        logActivity('GoGetSSL Renew error: Received error on getting order status; description: ' . $statusResult['description']);
        return;
    }
    
    $postFields = array();
    $postFields['uid'] = $params['configoption1'];
    $postFields['pw'] = $params['configoption2'];
    $postFields['product_id'] = $orderFetch['certtype'];
    $postFields['csr'] = $statusResult['csr_code'];
    $postFields['server_count'] = $statusResult['server_count'];
    $postFields['period'] = $statusResult['ssl_period'];
    $postFields['dcv_method'] = $statusResult['dcv_method'];
    $postFields['approver_emails'] = $statusResult['approver_emails'];
    $postFields['webserver_type'] = $statusResult['webserver_type'];
    
    if (isset($statusResult['dns_names'])) 
        $postFields['dns_names'] = $statusResult['dns_names'];
        
    $postFields['command'] = 'addSSLRenewOrder';
    
    $prefix = array('tech', 'org', 'admin');
    
    foreach ($statusResult as $k => $v) {
        
        $keySplit = explode('_', $k);
        
        if (count($keySplit) <= 1)
            continue;
        
        if (in_array($keySplit[0], $prefix)) {
            $postFields[$k] = $v;
        }
    }
    
    $renewResult = gogetssl_call($postFields, $params['configoption5']);
    
    if (isset($renewResult['error'])) {
        logActivity('GoGetSSL Renew error: Received error on renewing SSL; description: ' . $renewResult['description']);
        return;
    }
    
    update_query('tblsslorders', array('remoteid' => $renewResult['order_id'], 'completiondate' => 'now()', 'status' => 'Completed'), array('serviceid' => $params['serviceid']));
    
    logActivity('GoGetSSL Renew sucessful: Created renew requests successfully; serviceid: ' . $params['serviceid']);
}

/**
 * 
 * call() function handles every request to GoGetSSL and will return an array with results.
 * 
 */
function gogetssl_call($fields, $testMode = '') {
    global $CONFIG, $whmcs;

    $apiKey = $whmcs->get_config('GoGetSSL_APIKey');
    $apiKeyExpiry = $whmcs->get_config('GoGetSSL_APIKeyExpire');

    if (!empty($apiKeyExpiry) && $apiKeyExpiry <= time()) {
        $apiKey = '';
    }

    if (!empty($apiKey)) {
        $api = new GoGetSSLApi($apiKey);
    } else {
        $api = new GoGetSSLApi();
    }

    if ($testMode) {
        $api->setUrl('https://sandbox.gogetssl.com/api');
    } else {
        $api->setUrl('https://my.gogetssl.com/api');
    }

    if (empty($apiKey)) {
        $authResult = $api->auth(trim($fields['uid']), trim($fields['pw']));

        if (!isset($authResult['key'])) {
            return array('error' => true, 'description' => 'API password not valid');
        }

        $whmcs->set_config('GoGetSSL_APIKey', $authResult['key']);
        $whmcs->set_config('GoGetSSL_APIKeyExpire', strtotime('+10 months'));
    }

    switch ($fields['command']) {
        case 'getAllProducts':
            $callResult = $api->getAllProducts();
            break;

        case 'resendEmail':
            $callResult = $api->resendEmail($fields['order_id']);
            break;
            
        case 'decodeCSR':
            $callResult = $api->decodeCSR($fields['csr'], $fields['brand'], $fields['wildcard']);
            break;

        case 'getDomainEmailsForGeotrust':
            $callResult = $api->getDomainEmailsForGeotrust($fields['domain']);
            break;
            
        case 'getDomainEmails':
            $callResult = $api->getDomainEmails($fields['domain']);
            break;

        case 'addSSLOrder':
            $callResult = $api->addSSLOrder($fields);
            break;

        case 'addSSLRenewOrder':
            $callResult = $api->addSSLRenewOrder($fields);
            break;

        case 'getOrderStatus':
            $callResult = $api->getOrderStatus($fields['order_id']);
            break;
                
        case 'getProductDetails':
            $callResult = $api->getProductDetails($fields['product_id']);
            break;

        case 'reIssueOrder':
            $callResult = $api->reIssueOrder($fields['order_id'], $fields);
            break;
            
        case 'changeValidationEmail':
            $callResult = $api->changeValidationEmail($fields['order_id'], $fields);
            break;

        case 'getDomainAlternative':
            $callResult = $api->getDomainAlternative($fields['csr']);
            break;

    }

    return $callResult;
}

/**
 * 
 * getSSLWebServerTypes() function will return an array of available webservers, copied from the WHMCS source. Only used for reissue.
 * 
 */
function gogetssl_getSSLWebServerTypes() {
    $t = array();
    $t['1001'] = "AOL";
    $t['1002'] = "Apache +ModSSL";
    $t['1003'] = "Apache-SSL (Ben-SSL, not Stronghold)";
    $t['1004'] = "C2Net Stronghold";
    $t['1005'] = "Cobalt Raq";
    $t['1006'] = "Covalent Server Software";
    $t['1031'] = "cPanel / WHM";
    $t['1029'] = "Ensim";
    $t['1032'] = "H-Sphere";
    $t['1007'] = "IBM HTTP Server";
    $t['1008'] = "IBM Internet Connection Server";
    $t['1009'] = "iPlanet";
    $t['1010'] = "Java Web Server (Javasoft / Sun)";
    $t['1011'] = "Lotus Domino";
    $t['1012'] = "Lotus Domino Go!";
    $t['1013'] = "Microsoft IIS 1.x to 4.x";
    $t['1014'] = "Microsoft IIS 5.x and later";
    $t['1015'] = "Netscape Enterprise Server";
    $t['1016'] = "Netscape FastTrack";
    $t['1017'] = "Novell Web Server";
    $t['1018'] = "Oracle";
    $t['1030'] = "Plesk";
    $t['1019'] = "Quid Pro Quo";
    $t['1020'] = "R3 SSL Server";
    $t['1021'] = "Raven SSL";
    $t['1022'] = "RedHat Linux";
    $t['1023'] = "SAP Web Application Server";
    $t['1024'] = "Tomcat";
    $t['1025'] = "Website Professional";
    $t['1026'] = "WebStar 4.x and later";
    $t['1027'] = "WebTen (from Tenon)";
    $t['1028'] = "Zeus Web Server";
    $t['1000'] = "Other (not listed)";
    return $t;
}


