<?php

require_once 'modules/admin/views/SignupView.php';
require_once 'modules/clients/models/UserGateway.php';
require_once 'modules/clients/models/domain.php';
require_once 'newedge/classes/NE_Network.php';
require_once 'modules/billing/models/InvoiceEntry.php';
require_once 'modules/billing/models/BillingType.php';
require_once 'newedge/classes/NE_PluginCollection.php';
require_once 'modules/clients/models/Package_EventLog.php';
require_once 'modules/clients/models/Client_EventLog.php';
require_once 'modules/billing/models/Currency.php';
require_once 'modules/clients/models/ObjectCustomFields.php';

/**
* @package Admin
*/
class Signup_4_CreateAccounts extends SignupView
{
    var $permission     = '';
    var $showHeader     = false;

    var $userGateway;
    
    function preHeaders()
    {
        $this->initialize();
    }

    function dispatch()
    {
        if (!isset($_SESSION['signupValidated'])) {
            require 'modules/admin/views/Signup_2_OrderForm.php';
            $orderForm = new Signup_2_OrderForm('admin', 'Signup_2_OrderForm', $this->settings);
            $orderForm->setUser($this->user);
            $orderForm->setTpl($this->tpl);
            $orderForm->preHeaders();
            $orderForm->forceShowHeader();
            $orderForm->dispatch();
            return;
        }

        $currency = new Currency($this->user);

        $fraudmsg = "";
        if(isset($_REQUEST['fraudmsg'])) $fraudmsg = $_REQUEST['fraudmsg'];


        // repeat checks
        if (!isset($_REQUEST['package']) || $_REQUEST['package'] <= 0 || !isset($_REQUEST['clienttype']) || $_REQUEST['clienttype'] <= 0) {
            require 'modules/admin/views/Signup_0_ShowPackages.php';
            $showPackages = new Signup_0_ShowPackages('admin', 'Signup_0_ShowPackages', $this->settings);
            $showPackages->setUser($this->user);
            $showPackages->setTpl($this->tpl);
            $showPackages->preHeaders();
            $showPackages->forceShowHeader();
            
            $showPackages->dispatch();
            return;
        }
        
        $query = "SELECT type FROM promotion WHERE id = ?";
        $result = $this->db->query($query, $_REQUEST['clienttype']);
        $row = $result->fetch();
        
        if ($row['type'] == 2 && $this->domain == "") {
            require 'modules/admin/views/Signup_1_DomainNameForm.php';
            $domainNameForm = new Signup_1_DomainNameForm('admin', 'Signup_1_DomainNameForm', $this->settings);
            $domainNameForm->setUser($this->user);
            $domainNameForm->setTpl($this->tpl);
            $domainNameForm->preHeaders();
            $domainNameForm->forceShowHeader();
            $domainNameForm->dispatch();
            return;
        }

/* ADDED TO PREVENT HACK */
        $arrHack = $this->validateHack();
        if ($arrHack) {
            require 'modules/admin/views/Signup_2_OrderForm.php';
            $orderForm = new Signup_2_OrderForm('admin', 'Signup_2_OrderForm', $this->settings);
            $orderForm->setUser($this->user);
            $orderForm->setTpl($this->tpl);
            $orderForm->preHeaders();
            $orderForm->forceShowHeader();
            $orderForm->dispatch($arrHack? $arrHack : false);
            $this->logHackAttempt($arrHack);
            return;
        }
/* ADDED TO PREVENT HACK */

        $this->userGateway = new UserGateway();
        $arrError = $this->validateData();

        if ($arrError) {
            require 'modules/admin/views/Signup_2_OrderForm.php';
            $orderForm = new Signup_2_OrderForm('admin', 'Signup_2_OrderForm', $this->settings);
            $orderForm->setUser($this->user);
            $orderForm->setTpl($this->tpl);
            $orderForm->preHeaders();
            $orderForm->forceShowHeader();
            $orderForm->dispatch($arrError? $arrError : false);
            return;
        }

        // if phone verif is set and it didn't pass, user shouldn't be here
        if (@$_REQUEST['member'] != 'on') {
            $phoneVerificationPlugins = new NE_PluginCollection('phoneverification', $this->user);
            while ($phoneVerificationPlugin = $phoneVerificationPlugins->getNext(false)) {

                if ($this->settings->get("plugin_{$phoneVerificationPlugin}_Enabled") == 1
                    && !isset($_SESSION['phoneverification_passed'])
                    && $this->settings->get("plugin_{$phoneVerificationPlugin}_Minimum Bill Amount to Trigger Telephone Verification") <= $_REQUEST['totalBill']
                    && isset($_REQUEST['fraudScore']) && $this->settings->get("plugin_{$phoneVerificationPlugin}_Minimum Fraud Score to Trigger Telephone Verification") <= $_REQUEST['fraudScore'])
                {
                    require_once 'modules/admin/views/Signup_3b_PhoneVerification.php';
                    $phoneVerification = new Signup_3b_PhoneVerification('admin', 'Signup_3b_PhoneVerification', $this->settings);
                    $orderForm->setUser($this->user);
                    $orderForm->setTpl($this->tpl);
                    $orderForm->preHeaders();
                    $orderForm->forceShowHeader();
                    $orderForm->dispatch();
                    return;
                }

            }
        }

        $bolEchoOff = true; //variable for autobilling to not display to screen

        if (@$_REQUEST['member']=="on") $bMember=true;
        else $bMember=false;

        //Get ClientType For Package
        $tclienttype = $this->GetClientType($_REQUEST['package']);

        //Create Account
        $tempDateActivated = date("Y-m-d");
		$activeDate = date("Y-m-d H:i:s"); // This is a new date format used only by the dateActivated field of domains
		
        //remove the _ from the payment type
        //_ was used to determine credit card info
        //for the payment types
        $pos = strpos($_REQUEST['paymenttype'],"_");
        if ($pos>0) $_REQUEST['paymenttype'] = mb_substr($_REQUEST['paymenttype'],$pos+1);
        //end payment type formatting

        $tNextBillDate = $tempDateActivated;
        $_REQUEST['dateActivated'] = $tempDateActivated;
        $customTagsArray = unserialize(base64_decode($_REQUEST['customTagsArray']));

        //make recurring for domain = no if no payment cycle was passed.  (Means it should be a one time charge )
        if (isset($_REQUEST['paymentterm']) && $_REQUEST['paymentterm'] != 0) {
            $_REQUEST['recurring']=1;
            $tPaymentTerm = $_REQUEST['paymentterm'];
        } else {
            $_REQUEST['recurring']=0;
            $tPaymentTerm = 0;
        }
        unset($_REQUEST['paymentterm']);
        //Enter some initial commments for customer        
        
        $ip = NE_Network::getRemoteAddr();
        $host = @gethostbyaddr($ip);
        $agent = $_SERVER['HTTP_USER_AGENT'];
        
        $strInitialComments = "IP: $ip<br>\n";
        $eventLogClient = array();
        $eventLogClient['Signed up from IP'] = $ip;
        $strInitialComments .= "HOSTNAME: $host<br>\n";
        $eventLogClient['Signed up from hostname'] = $host;
        $strInitialComments .= "USER AGENT: $agent<br>\n\n\n";
        $eventLogClient['Signed up using user agent'] = $agent;
        
        $strInitialCommentsAdminSection = "IP: $ip\n";
        $strInitialCommentsAdminSection .= "HOSTNAME: $host\n";
        $strInitialCommentsAdminSection .= "USER AGENT: $agent\n\n\n";
        $strInitialCommentsUserInfo = "===== ".$this->lang("ORIGINAL CUSTOMER DATA")." ===== \n";
        $query = "SELECT * FROM customuserfields WHERE insignup=1";
        $result = $this->db->query($query);
        while ($row = $result->fetch()) {
            if (isset($_REQUEST['CT_'.$row['id']]) && $_REQUEST['CT_'.$row['id']] != '') {
                $strInitialCommentsUserInfo .= $this->varLang($row['name']).": ".strip_tags($_REQUEST['CT_'.$row['id']]);
                if($row['name'] == 'Organization'){
                    if(isset($_REQUEST['isOrganization'])){
                        $strInitialCommentsUserInfo .= " (".$this->lang("business account").")";
                    }else{
                        $strInitialCommentsUserInfo .= " (".$this->lang("individual account").")";
                    }
                }
                $strInitialCommentsUserInfo .= "\n";
            }
        }

        $strInitialCommentsUserInfo .= ((isset($_REQUEST['paymenttype']) && $_REQUEST['paymenttype'] != '')? $this->lang("Payment Type").": ".$_REQUEST['paymenttype']."\n": "");
        if (isset($_REQUEST['coupon_code']) && $_REQUEST['coupon_code'] != '') {
            $strInitialCommentsUserInfo .= $this->lang("Coupon Code").": ".strip_tags($_REQUEST['coupon_code'])."\n";
            $eventLogClient['Coupon code'] = strip_tags($_REQUEST['coupon_code']);
        }
        if (isset($_REQUEST['taxrate']) && $_REQUEST['taxrate'] != '') {
            $strInitialCommentsUserInfo .= $this->lang("Taxes").": ".$_REQUEST['taxrate']."% \n";
            $eventLogClient['Tax rate'] = $_REQUEST['taxrate'].'%';
        }
        if (isset($_REQUEST['discount']) && $_REQUEST['discount'] != '') {
            $strInitialCommentsUserInfo .= $this->lang("Discount").": ".$currency->format($_REQUEST['currency'], $_REQUEST['discount']) ."\n";
            $eventLogClient['Discount'] = $_REQUEST['discount'];
        }
        if (isset($_REQUEST['totalBill']) && $_REQUEST['totalBill'] != '') {
            $strInitialCommentsUserInfo .= $this->lang("Total").": ".$currency->format($_REQUEST['currency'], $_REQUEST['totalBill'])."\n";
            $eventLogClient['Total bill'] = $currency->format($_REQUEST['currency'], $_REQUEST['totalBill']);
        }
        if (isset($_REQUEST['currency']) && $_REQUEST['currency'] != '') {
            $strInitialCommentsUserInfo .= $this->lang("Currency").": ".$_REQUEST['currency']."\n";
            $eventLogClient['Currency'] = $currency->format($_REQUEST['currency'], $_REQUEST['totalBill']);
        }
        if (isset($_REQUEST['domain']) && $_REQUEST['domain'] != '') {
            $strInitialCommentsUserInfo .= $this->lang("Domain").": ".$_REQUEST['domain']."\n";
            $eventLogClient['Domain name'] = $_REQUEST['domain'];
        }
        if (isset($_REQUEST['new_domain_username']) && $_REQUEST['new_domain_username'] != '') {
            $strInitialCommentsUserInfo .= $this->lang("Domain Username").": ".$_REQUEST['new_domain_username']."\n";
            $eventLogClient['Domain username'] = $_REQUEST['new_domain_username'];
        }
        $strInitialCommentsUserInfo .= ((isset($_REQUEST['dateActivated']) && $_REQUEST['dateActivated'] != '')? $this->lang("Date").": ".$_REQUEST['dateActivated']."\n": "");
        $strInitialCommentsUserInfo .= "===== ".$this->lang("ORIGINAL CUSTOMER DATA")." ===== \n\n";
        
        //add fraud message to admin comments
        if ($fraudmsg!=""){
            $strInitialCommentsAdminSection .= strip_tags($fraudmsg);
            $eventLogClient['Fraud detection message'] = $fraudmsg;
        }

        //Setup welcome email
        $strMessageOutput = "<br><b>------------------------------";
        $strMessageOutputTemp = '';
        if (!$bMember) {
            $strMessageOutput .= "<br>\n".$this->lang("Customer Details").":";
        } else {
            $_REQUEST['new_password'] = $_REQUEST['member_password'];
            //get userid of existing member
            $tUserID = $_REQUEST['memberuserid'];
            $memberUser = new User($tUserID);
            $tFirstName = $memberUser->getFirstName();
            $tLastName = $memberUser->getLastName();
            $tOrganization = $memberUser->getOrganization();
            if ($tOrganization) $tLastName .= " - $tOrganization";

            $strMessageOutput .= "<br>\n<font color='red'>".$this->lang("Existing Member").": </font>$tFirstName $tLastName";

            // reset this field because the form's default payment method might not have the same autopayment status
            // as the existing user's.
            $_POST['autopayment'] = $_REQUEST['autopayment'] = ($memberUser->isAutopayment()? 1 : 0);
        }
        $strMessageOutput .= "<br>\n------------------------------</b><br>\n";
        if ($this->domain!="") {
            $strMessageOutput .= $this->lang("Domain Name").": $this->domain";
            $strMessageOutputTemp = $strMessageOutput;
            $strMessageOutput = '';
        }

        if(!$bMember) {
            $p = 0;
            $varnames="";
            $values = "";

            $tMyUser = new User();
            $tMyUser->setCurrent(false);
            if(isset($_REQUEST['isOrganization'])){
                $tMyUser->setIsOrganization(true);
                $eventLogClient['Organization'] = 'Yes';
            }else{
                $tMyUser->setIsOrganization(false);
                $eventLogClient['Organization'] = 'No';
            }
            $tMyUser->setGroupId(1);
            if(isset($_REQUEST['selectedcurrency'])){
                $tMyUser->setCurrency($_REQUEST['selectedcurrency']);
            }else{
                $tMyUser->setCurrency($_REQUEST['currency']);
            }
            $eventLogClient['Currency'] = $_REQUEST['currency'];
            
            $tMyUser->setPaymentType($_REQUEST['paymenttype']);
            $eventLogClient['Payment type'] = $_REQUEST['paymenttype'];
            
            if(isset($_REQUEST['ccmonth'])){
                $tMyUser->setCCMonth($_REQUEST['ccmonth']);
                $eventLogClient[/*T*/'CC expiration month'/*/T*/] = $_REQUEST['ccmonth'];
                
            }
            if(isset($_REQUEST['ccyear'])){
                $tMyUser->setCCYear($_REQUEST['ccyear']);
                $eventLogClient[/*T*/'CC expiration year'/*/T*/] = $_REQUEST['ccyear'];
            }
            $tMyUser->setAutopayment(isset($_REQUEST['autopayment']) && $_REQUEST['autopayment'] == 1);
            $tMyUser->setDateCreated($_REQUEST['dateActivated']);
            $tMyUser->setStatus(0);
            $tMyUser->setRecurring($_REQUEST['recurring']);
            $tMyUser->setEmail(htmlspecialchars(strip_tags($_REQUEST['CT_4'], ENT_QUOTES)));
            if (!$tMyUser->add()) {
                require 'modules/admin/views/Signup_2_OrderForm.php';
                $orderForm = new Signup_2_OrderForm('admin', 'Signup_2_OrderForm', $this->settings);
                $orderForm->setUser($this->user);
                $orderForm->setTpl($this->tpl);
                $orderForm->preHeaders();
                $orderForm->forceShowHeader();
                $orderForm->dispatch(array($this->lang('This installation has reached its number of users limit')));
                return;
            }

            $this->_importGuestTickets($tMyUser);

            $tUserID = $tMyUser->getId();

            if (!is_null($this->settings->get('plugin_paypal_Paypal Subscriptions Option In Signup'))
                && $this->settings->get('plugin_paypal_Paypal Subscriptions Option In Signup') == 1)
            {
                $_REQUEST['use_paypal_subscriptions'] = 1;
            }
            // set paypal subscriptions preference
            if (isset($_REQUEST['use_paypal_subscriptions'])) {
                $query = "SELECT id FROM customuserfields WHERE name='Use Paypal Subscriptions';";
                $result = $this->db->query($query);
                list($customId) = $result->fetch();
                $tMyUser->UpdateCustomTag($customId, 1);
                $eventLogClient['Custom field Use Paypal Subscriptions'] = $this->lang('Yes');
            }

            //Get Custom Tags for profile
            foreach ($customTagsArray as $customTag) {
                $value = '';
                if (isset($_REQUEST[$customTag])) {
                    $value = htmlspecialchars(strip_tags($_REQUEST[$customTag]),ENT_QUOTES);
                }
                //Get Custom Field Name to Use in new account email
                if (mb_substr($customTag,0,2)=="CT") {
                    //This is a profile custom tag
                    if ($customTag=="CT_1"){$tFirstName=$value;}
                    if ($customTag=="CT_2"){$tLastName=$value;}
                    $customTag = str_replace("CT_", "", $customTag);
                    if (trim($value) != '') {
                         $getCustomNameQuery = "SELECT name, type FROM customuserfields WHERE id=?";
                         $getCustomNameResult = $this->db->query($getCustomNameQuery, $customTag);
                         list($tCustomName, $tType) = $getCustomNameResult->fetch();
                         if ($tType == TYPEDATE) {
                             if($value != ''){
                                 $value = NE_Lib::form_to_db($value, $this->settings->get('Date Format'), "/");
                             }
                         }
                         $strMessageOutput .= "<br>\n$tCustomName: $value";
                         if($tCustomName == 'Organization'){
                             if(isset($_REQUEST['isOrganization'])){
                                 $strMessageOutput .= " (".$this->lang("business account").")";
                             }else{
                                 $strMessageOutput .= " (".$this->lang("individual account").")";
                             }
                         }
                    }
                    if ($value != '') {
                        $tMyUser->UpdateCustomTag($customTag,$value);
                        $eventLogClient[$tMyUser->getCustomFieldName($customTag)] = $value;
                    }
                }
            }

            //Set default HTML Email format to yes
            $getHTMLEmailQuery = "SELECT id FROM customuserfields WHERE name='HTML Email Format';";
            $getHTMLEmailResult = $this->db->query($getHTMLEmailQuery);
            list($tCustomTag) = $getHTMLEmailResult->fetch();
            $tMyUser->UpdateCustomTag($tCustomTag,"1");
            $eventLogClient['HTML Email Format'] = $this->lang('Yes');
            //End Set HTML Email

            //set clientinformation needed
            //for password to get set
            $_SESSION['customerId'] = $tUserID;
            $_SESSION['sessionPassword'] = $_REQUEST['new_password'];
            $tMyUser->setPassword($_REQUEST['new_password']);

            // update user's tax flag
            if ($tMyUser->getTaxRate()) {
                $tMyUser->setTaxable(1);
                $eventLogClient['Taxable'] = 'Yes';
            }else{
                $eventLogClient['Taxable'] = 'No';
            }
            
            $tMyUser->save();
        }

        //Determine what they wanted with the domain name if anything (REGISTRAR)
        if($_REQUEST['domain'] != '') {
            switch ($_REQUEST['transfer']) {
                case 0:
                    $strMessageOutput .= "<br>\n".$this->lang("Registrar Service Requested: Customer wants host to register domain");
                    break;
                case 1:
                    $strMessageOutput .= "<br>\n".$this->lang("Registrar Service Requested: Customer wants host to transfer domain");
                    break;
                case 2:
                    $strMessageOutput .= "<br>\n".$this->lang("Registrar Service Requested: Customer will manage their own domain");
                    break;
            }
        }
        else {
            $_REQUEST['transfer'] = 2;
        }

        //Enter Account Information
        $query="SELECT planid,planname FROM package WHERE id=?";
        $result = $this->db->query($query, $_REQUEST['package']);
        list($promotionid,$planname) = $result->fetch();

        require_once 'modules/admin/models/PackageType.php';
        $packageType = new PackageType($promotionid);
        $strMessageOutput .= "<br>\n".$this->lang("Package Type").": ".$packageType->getName();
        $strMessageOutput .= "<br>\n".$this->lang("Domain Package").": ".$planname;

        if (!$bMember) {
            //Extra Signup Email Info
            $strMessageOutput .= "<br>\nRequested Password: ".$_REQUEST['new_password'];
            $strMessageOutput .= "<br>\nPayment Type: ".$_REQUEST['paymenttype'];
            if ($_REQUEST['paymenttype'] == 'paypal' && isset($_REQUEST['use_paypal_subscriptions']))
                $strMessageOutput .= ' - '.$this->lang("Subscriptions enabled");
        }

        // Use server that hasn't been used for the longest time and that hasn't filled up his domains quota
        list($tServerID, $tServerIP) = Signup_4_CreateAccounts::getServerIdAndIP();
        
        if($tServerID != 0){
            $query = "UPDATE server SET last_utilization=? WHERE id=?";
            $this->db->query($query, date('Y-m-d H:i:s'), $tServerID);
        }

        //Create domain
        if (!isset($_REQUEST['new_domain_username'])) {
            $_REQUEST['new_domain_username'] = '';
        }

        //change next invoice date if prorate price was > 0
        if ($_REQUEST['prorating'] == 1) {
            $nextInvoiceDate =  date("Y-m-d",$_REQUEST['proTmpNextBill']);
        } else {
            $nextInvoiceDate =  $tNextBillDate;
        }

        if ($this->domain != '') {
            $strMessageOutputTemp .= "<br>\n".$this->lang("Domain Username").': ' . $_REQUEST['new_domain_username'];
            $strMessageOutputTemp .= "<br>\n".$this->lang("Domain Password").': ' . $_REQUEST['new_domain_password'];
        }
        $strMessageOutput = $strMessageOutputTemp.$strMessageOutput;
        
        $tDomain = new Domain(array(
            'm_DomainName'  => $this->domain,
            'm_CustomerID'  => $tUserID,
            'm_UserName'    => $_REQUEST['new_domain_username'],
            'm_Password'    => $this->domain != ''? $_REQUEST['new_domain_password'] : $_REQUEST['member_password'],
            'm_Recurring'   => $_REQUEST['recurring'],
            'm_dateActivated'=> $activeDate,
            'm_PlanID'      => $_REQUEST['package'],
            'm_ServerID'    => $tServerID,
            'm_nextBillDate'=> $nextInvoiceDate,
            'm_paymentterm' => $tPaymentTerm,
            'm_PromotionID' => $tclienttype,
            'm_Current'     => 0,
            'm_Register'    => $_REQUEST['transfer'],
            'm_Signup'      => 1,
        ), $this->user);
        
        if (isset($_REQUEST['addonChargesStr'])) {
            $tDomain->setAddons($this->_getPriceIds($_REQUEST['addonChargesStr']));
        }
        $tDomain->updateRecord();
        $tDomainID = $tDomain->getID();

        $eventLogPackage = array();
        
        $query_package_type_name = "SELECT name FROM promotion WHERE id = ?";
        $result_package_type_name = $this->db->query($query_package_type_name, $tclienttype);
        list($package_type_name) = $result_package_type_name->fetch();
        $eventLogPackage [/*T*/'Package Type'/*/T*/] = $package_type_name;

        $query_package_name = "SELECT planname FROM package WHERE planid = ? AND id = ?";
        $result_package_name = $this->db->query($query_package_name, $tclienttype, $_REQUEST['package']);
        list($package_name) = $result_package_name->fetch();
        $eventLogPackage [/*T*/'Package'/*/T*/] = $package_name;

        $eventLogPackage [/*T*/'Domain Name'/*/T*/] = $this->domain;

        $eventLogPackage [/*T*/'Domain Username'/*/T*/] = $_REQUEST['new_domain_username'];
        $eventLogPackage [/*T*/'Use Shared IP'/*/T*/] = $this->lang('Yes');


        if($tServerID != 0){
            $query_server_name = "SELECT name FROM server WHERE id = ?";
            $result_server_name = $this->db->query($query_server_name, $tServerID);
            list($server_name) = $result_server_name->fetch();
            $eventLogPackage [/*T*/'Server'/*/T*/] = $server_name;
        }
        
        $eventLogPackage [/*T*/'Date Created'/*/T*/] = $_REQUEST['dateActivated'];

        $eventLogPackage [/*T*/'Recurring'/*/T*/] = ($_REQUEST['recurring'] == 1)? $this->lang('Yes') : $this->lang('No');
        $eventLogPackage [/*T*/'Next Due Date'/*/T*/] = $nextInvoiceDate;
        
        switch ($tPaymentTerm){
            case  1:
                $eventLogPackage[/*T*/'Billing Cycle'/*/T*/] = $this->lang("Monthly");
                break;
            case  3:
                $eventLogPackage[/*T*/'Billing Cycle'/*/T*/] = $this->lang("Quarterly");
                break;
            case  6:
                $eventLogPackage[/*T*/'Billing Cycle'/*/T*/] = $this->lang("Semi-Annual");
                break;
            case 12:
                $eventLogPackage[/*T*/'Billing Cycle'/*/T*/] = $this->lang("Annually");
                break;
            case 24:
                $eventLogPackage[/*T*/'Billing Cycle'/*/T*/] = $this->lang("Every 2 Years");
                break;
        }
        
        
        $strMessageOutput .= "<br><br>\n\n<b>------------------------------<br>
                                 ".$this->lang("Package Variables")."
                                 <br>------------------------------</b><br>\n";
        //Set Custom Tags for package (domain)
        reset($customTagsArray);
        foreach ($customTagsArray as $customTag) {
            $value = '';
            if (isset($_REQUEST[$customTag])) {
                $value = htmlspecialchars(strip_tags($_REQUEST[$customTag]),ENT_QUOTES);
            }
            //Get Custom Field Name to Use in new account email
            if (mb_substr($customTag,0,3) == 'PCT') {
                //This is a package custom tag
                $customTag = str_replace("PCT_", "", $customTag);
                if (trim($value) != '') {
                     /* *** NEW CODE *** */
                     $getCustomNameQuery = "SELECT name, "
                                          ."fieldType "
                                          ."FROM customField "
                                          ."WHERE id = ? ";
                     /* *** NEW CODE *** */
                     
                     
                     /* *** OLD CODE *** */
                     /*
                     $getCustomNameQuery = "SELECT name, "
                                          ."type "
                                          ."FROM customdomainfields "
                                          ."WHERE id = ? ";
                     */
                     /* *** OLD CODE *** */
                     
                     $getCustomNameResult = $this->db->query($getCustomNameQuery, $customTag);
                     list($tCustomName, $tType) = $getCustomNameResult->fetch();
                     if ($tType == TYPEDATE) {
                         if($value != ''){
                             $value = NE_Lib::form_to_db($value,$this->settings->get('Date Format'), "/");
                         }
                     }
                     $strMessageOutput .= "<br>\n$tCustomName: $value";
                }
                if ($value != '') {
                    $tDomain->UpdateCustomTag($customTag,$value);
                    
                    /* *** NEW CODE *** */
                    $query_custom_domain_field = "SELECT name "
                                                ."FROM customField "
                                                ."WHERE id = ? ";
                    /* *** NEW CODE *** */
                    
                    
                    /* *** OLD CODE *** */
                    /*
                    $query_custom_domain_field = "SELECT name "
                                                ."FROM customdomainfields "
                                                ."WHERE id = ? ";
                    */
                    /* *** OLD CODE *** */
                    $result_custom_domain_field = $this->db->query($query_custom_domain_field, $customTag);
                    list($custom_domain_field_name) = $result_custom_domain_field->fetch();
                    $eventLogPackage [$custom_domain_field_name] = $value;
                }
            }
        }
        
        /* *** NEW CODE *** */
        $query = "INSERT INTO object_customField "
                ."(objectid, customFieldId, value) "
                ."VALUES(?, 1, ?) ";
        /* *** NEW CODE *** */
        
        
        /* *** OLD CODE *** */
        /*
        $query = "INSERT INTO domain_customdomainfields "
                ."(userid, customid, value) "
                ."VALUES(?, 1, ?) ";
        */
        /* *** OLD CODE *** */
        
        $data_insert = $this->db->query($query, $tDomainID, @$tServerIP);

        // serialize extra domain attributes
        $extAttr = array();
        foreach ($_REQUEST as $attrName => $attrValue) {
            if (strpos($attrName, 'ext_attr_') === 0) {
                $extAttr[mb_substr($attrName, 9)] = strip_tags($attrValue);
                $eventLogPackage[/*T*/'Extra attribute #'/*/T*/.mb_substr($attrName, 9)] = strip_tags($attrValue);
            }
        }
        if ($extAttr) {
            $tDomain->setExtAttr($extAttr);
        }

        //check to see if recurring is true ( for recurringfee table synch )
        if ($_REQUEST['recurring'] == 1) {
            //determine if customer has selected to
            //offload recurring process to 3rd party processor
            $tDomain->SetRecurring(1);
        }

        $tMyUser = new User($tUserID);
        //check to see if new cc info
        if (!$bMember && $_REQUEST['ccnumber'] != '') {
            $tMyUser->StoreCreditCardInfo($_REQUEST['ccnumber'], $this->settings);
            $eventLogClient[/*T*/'CC number (last 4)'/*/T*/] = mb_substr($_REQUEST['ccnumber'], -4);
            $tMyUser->save();
        }

        //if domain was passed determine how much to charge and create charge
        //If customer is going to transfer then this charge does not get added
        if($this->domain != '' && (($_REQUEST['transfer']==0)||($_REQUEST['transfer']==1))) {
             $aTLDInfo = explode("|", $_REQUEST['domainperiod']);
             $t_PaymentTerm = $aTLDInfo[0] * 12;
             $tRegAction = "";

             //check to see if it is one time payment
             if ($aTLDInfo[0] == 0) {
                $eventLogPackage[/*T*/'Registration Length'/*/T*/] = $this->lang('One Time');
                
                if ($_REQUEST['transfer'] == 1) {
                    $tRegAction = $this->lang("Domain Transfer");
                    $tempDomainDetails = $tRegAction." ".$this->lang('for Domain').": $this->domain (one time payment)";
                } else {
                    $tRegAction = $this->lang("Domain Registration");
                    $tempDomainDetails = $tRegAction." ".$this->lang('for Domain').": $this->domain (one time payment)";
                }
                //Create One time payment for single domain registration
                $tParams = array(
                    'm_CustomerID'        => $tUserID,
                    'm_Description'       => "$tRegAction - ".$this->domain,
                    'm_Detail'            => $tempDomainDetails,
                    'm_invoiceid'         => 0,
                    'm_Date'              => $_REQUEST['dateActivated'],
                    'm_BillingTypeID'     => BILLINGTYPE_DOMAIN_NAME,
                    'm_IsProrating'       => 0,
                    'm_Price'             => $aTLDInfo[1],
                    'm_Recurring'         => 0,
                    'm_IncludeNextPayment'=> 1,
                    'm_AppliesToID'       => $tDomainID,
                    'm_Setup'             => 0,
                    'm_Taxable'           => $this->settings->get('Domains Taxable')? 1 : 0,
                );
                $domainRegInvEntry = new InvoiceEntry($tParams);
                $domainRegInvEntry->updateRecord();
            } else {
                if($aTLDInfo[0] == 1){
                    $eventLogPackage[/*T*/'Registration Length'/*/T*/] = $aTLDInfo[0].' '.$this->lang('Year');
                }else{
                    $eventLogPackage[/*T*/'Registration Length'/*/T*/] = $aTLDInfo[0].' '.$this->lang('Years');
                }
                
                $regAppliesTo = $tDomainID;
                // If it's a transfer insert an invoice entry for the transfer and setup a recurring domain registration for future renewals
                if ($_REQUEST['transfer'] == 1) {
                    $tRegAction = $this->lang("Domain Transfer");
                    $tempDomainDetails = $tRegAction." ".$this->lang('for Domain')." : ".$this->domain." x ".$aTLDInfo[0]." ".$this->lang('Years');
                    //Create One time payment for single domain transfer
                    $tParams = array(
                    'm_CustomerID'        => $tUserID,
                    'm_Description'       => "$tRegAction - ".$this->domain,
                    'm_Detail'            => $tempDomainDetails,
                    'm_invoiceid'         =>  0,
                    'm_Date'              => $_REQUEST['dateActivated'],
                    'm_BillingTypeID'     => BILLINGTYPE_DOMAIN_NAME,
                    'm_IsProrating'       => 0,
                    'm_Price'             => $aTLDInfo[1],
                    'm_Recurring'         => 0,
                    'm_IncludeNextPayment'=> 1,
                    'm_AppliesToID'       => $tDomainID,
                    'm_Setup'             => 0,
                    'm_Taxable'           => $this->settings->get('Domains Taxable')? 1 : 0,
                    );
                    $domainRegInvEntry = new InvoiceEntry($tParams);
                    $domainRegInvEntry->updateRecord();

                    // Update the values for the recurring domain registration
                    $_REQUEST['dateActivated'] = date("Y") + $aTLDInfo[0]."-".date("m-d");
                    $domainExt = mb_substr($this->domain,strpos($this->domain,".") + 1);
                    $sql = "SELECT pricing FROM tld WHERE name = ?";

                    $result = $this->db->query($sql, $domainExt);
                    list($pricingInfo) = $result->fetch();
                    $pricingInfo = unserialize($pricingInfo);
                    foreach($pricingInfo AS $key) {
                        if($key['period'] == $aTLDInfo[0]) {
                            $aTLDInfo[1] = $key['transfer'];
                        }
                    }
                    
                    // Need to set this or the registration fee gets included in the first invoice as well as the transfer fee.
                    $regAppliesTo = 0;
                }

                $tRegAction = $this->lang("Domain Registration");
                $tempDomainDetails = $tRegAction." ".$this->lang('for Domain')." : ".$this->domain." x ".$aTLDInfo[0]." ".$this->lang("Years");

                if ($tMyUser->getUsePaypalSubscriptions()) {
                    // For domains registrations with package fees, disablegenerate=-1, so that the subscription for the domain registration is generated when
                    // the user manually pays the second domain registration charge (usually the following year), EXCEPT if the registration cycle equals the packages's, EXCEPT if the registration cycle equals the packages's.
                    // If it's only a domain charge disablegenerate=1 because the subscription can be generated immediately (there's no conflict with a package
                    // billing cycle).
                    if ((@$_REQUEST['packageProratedFee'] > 0 || $tDomain->GetPrice() > 0) && $t_PaymentTerm != $tDomain->getPaymentTermEnum()) {
                        $disableGenerate = -1;
                    } else {
                        $disableGenerate = 1;
                    }
                } else {
                    $disableGenerate = 0;
                }
                $tParams = array(
                    'customerid'      => $tUserID,
                    'paymentterm'     => $t_PaymentTerm,
                    'description'     => "$tRegAction - ".$this->domain,
                    'detail'          => $tempDomainDetails,
                    'billingtypeid'   => BILLINGTYPE_DOMAIN_NAME,
                    'nextbilldate'    => $_REQUEST['dateActivated'],
                    'appliestoid'     => $regAppliesTo,
                    'amount'          => $aTLDInfo[1],
                    'disablegenerate' => $disableGenerate,
                    'taxable'         => $this->settings->get('Domains Taxable')? 1 : 0,
                );
                require_once 'modules/billing/models/RecurringWork.php';
                $domainRegRecurringEntry = new RecurringWork($tParams);
                $domainRegRecurringEntry->update();
                $tDomain->setRegistrationYears($aTLDInfo[0]);
             }
             if (isset($this->configuration['modules']['domains']['installedVersion'])) {
                 require_once 'modules/domains/models/DomainName.php';
                 $domArr = DomainName::splitDomain($this->domain);
                 $query = "SELECT plugin, autorenew FROM tld WHERE name=?";
                 $result = $this->db->query($query, $domArr[1]);
                 list($registrar, $autoRenew) = $result->fetch();
                 $properties = array(
                    'm_userId'              => $tUserID,
                    'm_domain'              => $this->domain,
                    'm_period'              => $aTLDInfo[0],
                 	'm_autoRenew'			=> $autoRenew,
                    'm_nextBillDate'        => date("Y") + $aTLDInfo[0]."-".date("m-d"),
                    'm_domain_extra_attr'   => (is_array($extAttr) && sizeof($extAttr) > 0)? serialize($extAttr) : '',
                    'm_registration_option' => $_POST['transfer'],
                    'm_registrar'           => $registrar,
                    'm_registrarOrderID'    => '',
                    'm_status'              => 0,
                );
                $domainName = new DomainName($properties, $this->user);
                $domainName->save();
             }
        }
        
        $query="SELECT taxable FROM package WHERE id=?";
        $result = $this->db->query($query, $this->package);
        list($pkgTaxable) = $result->fetch();

        //Generate Invoice
        if ($_REQUEST['setup'] > 0) {
             //Create InvoiceEntry For Setup
             $tParams = array(
                'm_CustomerID'        => $tUserID,
                'm_Description'       => 'Account Setup',
                'm_Detail'            => 'Initial setup charges',
                'm_invoiceid'         =>  0,
                'm_Date'              => $_REQUEST['dateActivated'],
                'm_BillingTypeID'     => BILLINGTYPE_PACKAGE,
                'm_IsProrating'       => 0,
                'm_Price'             => $_REQUEST['setup'],
                'm_Recurring'         => 0,
                'm_IncludeNextPayment'=> 1,
                'm_AppliesToID'       => $tDomainID,
                'm_Setup'             => 1,
                'm_Taxable'           => $pkgTaxable,
             );
             $setupInvEntry = new InvoiceEntry($tParams);
             $setupInvEntry->updateRecord();
        }

        // Make the prorated charge if needed
        if ($_REQUEST['prorating'] == 1) {
             // Grab the name of the package they just signed up for
             $this->package = NE_Lib::prepareForDB($_REQUEST['package']);
             $query="SELECT planname FROM package WHERE id=?";
             $result = $this->db->query($query, $this->package);
             list($pkgName) = $result->fetch();

             // Pgkname: # mm/dd/yyyy thru mm/dd/yyyy
             if($this->domain != '') {
                $description = "$pkgName: ".$this->domain.", " . date($this->settings->get('Date Format')). ' '.$this->lang('thru').' ' . date($this->settings->get('Date Format'), $_REQUEST['proTmpNextBill']);
             } else {
                $description = "$pkgName ($tDomainID), " . date($this->settings->get('Date Format')). ' '.$this->lang('thru').' ' . date($this->settings->get('Date Format'), $_REQUEST['proTmpNextBill']);
             }
             $description = NE_Lib::prepareForDB($description);
             $tParams = array(
                'm_CustomerID'        => $tUserID,
                'm_Description'       => $description,
                'm_Detail'            => 'Prorated signup charge',
                'm_invoiceid'         =>  0,
                'm_Date'              => $_REQUEST['dateActivated'],
                'm_BillingTypeID'     => BILLINGTYPE_PACKAGE,
                'm_IsProrating'       => 1,
                'm_Price'             => $currency->format($_REQUEST['currency'], $_REQUEST['packageProratedFee'] + 0.00001),
                'm_Recurring'         => 0,
                'm_IncludeNextPayment'=> 1,
                'm_AppliesToID'       => $tDomainID,
                'm_Taxable'           => $pkgTaxable,
             );
             $proratedInvEntry = new InvoiceEntry($tParams);
             $proratedInvEntry->updateRecord();
        }

        // Revalidate coupon and create discount negative charge
        if ($_REQUEST['discount']) {
             require_once 'modules/billing/models/Coupon.php';
             if ($coupon = Coupon::validate($_REQUEST['coupon_code'], $_REQUEST['clienttype'], $_REQUEST['package'], $tPaymentTerm)) {
                 $strMessageOutput .= "<br><br>\n\n<b>------------------------------<br>\n"
                                 .$this->lang("Discount Coupon")
                                 ."<br>\n------------------------------</b><br>\n"
                                 .$this->lang("Code").": ".$_REQUEST['coupon_code']."<br>\n"
                                 .$this->lang("Amount").": ".$currency->format($_REQUEST['currency'], -$_REQUEST['discount'], true, false)."<br><br>\n\n";

                 $m_Description = $this->lang('Discount coupon')." ($planname";
                 if(isset($this->domain) && $this->domain != ''){
                     $m_Description .= ": $this->domain";
                 }
                 $m_Description .= ')';
                 $m_Detail = $m_Description."<br>Code: ".$_REQUEST['coupon_code'];

                 if ($coupon['recurring']) {
                     // create recurring entry
                     require_once 'modules/billing/models/RecurringWork.php';
                     
                     $recurringEntry = new RecurringWork(array(
                        'description'       => $m_Description,
                        'detail'            => $m_Detail,
                        'billingtypeid'     => BILLINGTYPE_COUPON_DISCOUNT,
                        'amount'            => $_REQUEST['discount'],
                        'amountPercent'     => $coupon['type']? $coupon['discount'] : 0,
                        'disablegenerate'   => $tMyUser->getUsePaypalSubscriptions()? 1 : 0,
                        'customerid'        => $tUserID,
                        'paymentterm'       => $tDomain->m_paymentterm,
                        'nextbilldate'      => $tDomain->m_nextBillDate,
                        'appliestoid'       => $tDomain->getID(),
                        'couponApplicableTo'=> $coupon['applicableTo'],
                        'taxable'           => $coupon['taxable'],
                        'monthlyusage'      => '0|'.$coupon['recurringmonths']));
                     $recurringEntry->update();
                     
                     $idrecurring = $recurringEntry->GetID();
                     
                     $query = "SELECT id "
                             ."FROM recurringfee "
                             ."WHERE  description = ? "
                             ."AND appliestoid = ? "
                             ."AND status = 1 ";
                     $result = $this->db->query($query, $m_Description, $tDomain->getID());
                     $idValueRecurring = $result->fetch();

                     $query = "INSERT INTO coupons_usage (invoiceentryid,couponid,isrecurring) VALUES(?,?,?)";
                     $data_insert = $this->db->query($query, $idValueRecurring[0], $coupon['id'], 1);

                 } else {
                     $discountInvEntry = new InvoiceEntry(array(
                        'm_CustomerID'        => $tUserID,
                        'm_Description'       => $m_Description,
                        'm_Detail'            => $m_Detail,
                        'm_invoiceid'         =>  0,
                        'm_Date'              => $_REQUEST['dateActivated'],
                        'm_BillingTypeID'     => BILLINGTYPE_COUPON_DISCOUNT,
                        'm_IsProrating'       => 0,
                        'm_Price'             => $_REQUEST['discount'],
                        'm_PricePercent'      => $coupon['type']? $coupon['discount'] : 0,
                        'm_Recurring'         => 0,
                        'm_IncludeNextPayment'=> 1,
                        'm_AppliesToID'       => $tDomainID,
                        'm_CouponApplicableTo'=> $coupon['applicableTo'],
                        'm_Taxable'           => $coupon['taxable'],
                     ));
                     $discountInvEntry->updateRecord();
                     
                     $invoiceentryid = $discountInvEntry->getId();
                     
                     $query = "INSERT INTO coupons_usage (invoiceentryid,couponid,isrecurring) VALUES(?,?,?)";
                     $data_insert = $this->db->query($query, $invoiceentryid, $coupon['id'],0);
                 }

                  Coupon::updateQuantity($_REQUEST['coupon_code']);
             }
        }

        // Process Package Add-ons
        if ($_REQUEST['addonChargesStr'] != '') {
            $strMessageOutput .= "<br><br>\n\n<b>------------------------------<br>\n
                                 ".$this->lang("Package Add-ons")."
                                 <br>\n------------------------------</b><br>\n";
            require_once 'modules/admin/models/PackageAddon.php';
            
            $cycleLang = array(
                 0  => $this->lang('billed only once'),
                 1  => $this->lang('billed monthly'),
                 3  => $this->lang('billed quarterly'),
                 6  => $this->lang('billed semiannually'),
                12  => $this->lang('billed annually'),
                24  => $this->lang('billed every 2 years'),
            );
            
            foreach ($this->_getPriceIds($_REQUEST['addonChargesStr']) as $selectedPriceId => $selectedPriceAttribs) {
                $addon = new PackageAddon($selectedPriceAttribs['addonId']);
                $tPrices = $addon->getPrices();

                $query_package_addon = "SELECT pa.name, pap.detail FROM packageaddon pa, packageaddon_prices pap WHERE pa.id = ? AND pa.id = pap.packageaddon_id AND pap.id = ?";
                $result_package_addon = $this->db->query($query_package_addon, $selectedPriceAttribs['addonId'], $selectedPriceId);
                list($package_addon_name, $package_addon_detail) = $result_package_addon->fetch();
                $eventLogPackage [$package_addon_name] = $package_addon_detail.' ('.$cycleLang[$selectedPriceAttribs['cycle']].')';

                $strMessageOutput .= "<br>\n".$addon->getName().": "
                    .$tPrices[$selectedPriceId]['detail']. " ("
                    .$currency->format($_REQUEST['currency'], $tPrices[$selectedPriceId]['price'.$selectedPriceAttribs['cycle']], true, false);

                if ($selectedPriceAttribs['cycle'] != 0
                    && $tPrices[$selectedPriceId]['price'.$selectedPriceAttribs['cycle']] != 0)
                {
                    $strMessageOutput .= ' ' . $this->lang("every %s month(s)", $selectedPriceAttribs['cycle']);
                }
                $strMessageOutput .= ")";

                if ($tPrices[$selectedPriceId]['price'.$selectedPriceAttribs['cycle']] < 0
                    || ($selectedPriceAttribs['cycle'] != 0 && $selectedPriceAttribs['cycle'] != $tDomain->m_paymentterm && !$tPrices[$selectedPriceId]['price'.$selectedPriceAttribs['cycle'].'Force']))
                {
                    continue;
                }

                // recurring fee portion
                // (note: when $selectedPriceAttribs['cycle'] is 0 this means it's an addon for a setup-price-only package
                if ($selectedPriceAttribs['cycle'] > 0 && $tPrices[$selectedPriceId]['price'.$selectedPriceAttribs['cycle']] >0) {
                    require_once 'modules/billing/models/RecurringWork.php';
                    if ($tMyUser->getUsePaypalSubscriptions() && $selectedPriceAttribs['cycle'] != $tDomain->m_paymentterm) {
                        $disableGenerate = -1;
                    } elseif ($tMyUser->getUsePaypalSubscriptions()) {
                        $disableGenerate = 1;
                    } else {
                        $disableGenerate = 0;
                    }
                    $recurringEntry = new RecurringWork(array(
                       'description'           => $addon->getName() . ': ' . $tPrices[$selectedPriceId]['detail'],
                       'detail'                => '',
                       'billingtypeid'         => BILLINGTYPE_PACKAGE_ADDON,
                       'packageAddonPricesId'  => $selectedPriceId,
                       'amount'                => $tPrices[$selectedPriceId]['price'.$selectedPriceAttribs['cycle']],
                       'disablegenerate'       => $disableGenerate,
                       'customerid'            => $tUserID,
                       'paymentterm'           => $selectedPriceAttribs['cycle'],
                       'nextbilldate'          => $tDomain->m_nextBillDate,
                       'appliestoid'           => $tDomain->getID(),
                       'taxable'               => $addon->getTaxable()));
                    $recurringEntry->update();

                    // prorated portion
                    if ($_REQUEST['prorating'] == 1) {
                        list($tAddonPrice, $addonProratedPrice, $addonProratedDays, $addonProIncFollowing, $addonTmpNextBill, $addonProNextBill)
                        = $this->processProrating($this->settings->get('Prorate To Day'), $this->settings->get('Include Following Payment'), $selectedPriceAttribs['cycle'], $tPrices[$selectedPriceId]['price'.$selectedPriceAttribs['cycle']]);

                        $proratedAddonInvEntry = new InvoiceEntry(array(
                            'm_CustomerID'        => $tUserID,
                            'm_Description'       => $addon->getName() . ': ' . $tPrices[$selectedPriceId]['detail']
                                                     . ', ' . date($this->settings->get('Date Format')). ' thru ' . date($this->settings->get('Date Format'), $_REQUEST['proTmpNextBill']),
                            'm_Detail'            => 'Prorated signup charge',
                            'm_invoiceid'         =>  0,
                            'm_Date'              => $_REQUEST['dateActivated'],
                            'm_BillingTypeID'     => BILLINGTYPE_PACKAGE_ADDON,
                            'm_IsProrating'       => 1,
                            'm_Price'             => $addonProratedPrice,
                            'm_Recurring'         => 0,
                            'm_IncludeNextPayment'=> 1,
                            'm_AppliesToID'       => $tDomainID,
                            'm_Taxable'           => $addon->getTaxable(),
                        ));
                        $proratedAddonInvEntry->updateRecord();
                    }
                }

                // setup portion
                if ($tPrices[$selectedPriceId]['price0'] > 0) {
                    $m_Description = $addon->getName() . ': ' . $tPrices[$selectedPriceId]['detail'] . " ($planname";
                    if(isset($this->domain)){
                        $m_Description .=  " : $this->domain";
                    }
                    $m_Description .= '), (Setup)';
                    $addonInvEntry = new InvoiceEntry(array(
                        'm_CustomerID'        => $tUserID,
                        'm_Description'       => $m_Description,
                        'm_Detail'            => '',
                        'm_invoiceid'         =>  0,
                        'm_Date'              => $_REQUEST['dateActivated'],
                        'm_BillingTypeID'     => BILLINGTYPE_PACKAGE_ADDON,
                        'm_IsProrating'       => 0,
                        'm_Price'             => $tPrices[$selectedPriceId]['price0'],
                        'm_Recurring'         => 0,
                        'm_IncludeNextPayment'=> 1,
                        'm_AppliesToID'       => $tDomainID,
                        'm_Setup'             => 0,
                        'm_AddonSetup'        => 1,
                        'm_Taxable'           => $addon->getTaxable(),
                        'm_Setup'             => 1,
                    ));
                    $addonInvEntry->updateRecord();
                }
            }
        }
        $clientLog = Client_EventLog::newInstance($tUserID, $tUserID, CLIENT_EVENTLOG_CREATED, $tUserID, serialize($eventLogClient));
        $this->logger->addEventLog($clientLog);
        $packageLog = Package_EventLog::newInstance($tUserID, $tDomainID, PACKAGE_EVENTLOG_CREATED, $tUserID, serialize($eventLogPackage));
        $this->logger->addEventLog($packageLog);
        
        $strMessageOutput .= "<br><br>\n\n<b>------------------------------<br>\n
                                 ".$this->lang("Signup Environment")."
                                 <br>\n------------------------------</b><br>\n";
        $strMessageOutput .= $strInitialComments.$fraudmsg;

        $strMessageOutput .= "<br><br>\n\n".$this->lang("Thank you for using ClientExec!")."<br>\n";
        $strMessageOutput .= "<b>".$this->lang("The ClientExec Team")."</b><br>\n";
        $strMessageOutput .= "http://www.clientexec.com";
        
        require 'modules/admin/views/Signup_5_ProcessBilling.php';

        $processBilling = new Signup_5_ProcessBilling('admin', 'Signup_5_ProcessBilling');
        $processBilling->setUser($this->user);
        $processBilling->setTpl($this->tpl);
        $processBilling->preHeaders();
        $processBilling->dispatch($tUserID,$this->domain,$tDomainID,$strMessageOutput,$_REQUEST['autopayment'], $tFirstName,$tLastName,$bMember);
        
        //Reassign Renewal Price for recurrinFee after generate invoice
        if(isset($domainRegRecurringEntry) && $_REQUEST['transfer'] == 0 && $aTLDInfo[2] != $aTLDInfo[1]) {
            $domainRegRecurringEntry->SetAmount($aTLDInfo[2]);
            $domainRegRecurringEntry->update();
        }
        exit;
    }


/* ADDED TO PREVENT HACK */
    function validateHack()
    {
        if (isset($_REQUEST['paymentterm']) && $_REQUEST['paymentterm'] != 0) {
            $tPaymentTerm = $_REQUEST['paymentterm'];
        } else {
            $tPaymentTerm = 0;
        }

        $arrHack = array();

        // Validate Registration Length and Domain
        if($this->domain != '' && (($_REQUEST['transfer']==0)||($_REQUEST['transfer']==1))){
            $aTLDInfo = explode("|", $_REQUEST['domainperiod']);
            
            // Validate if Registration Length has the right structure
            if(count($aTLDInfo) != 3){
                $arrHack[] = $this->lang("Registration Length has been altered with an invalid structure");
            }else{
                $tld = mb_substr(strstr($this->domain, '.'),1);
    /*
                $sqlValidTLDPrices = '';
                if($_REQUEST['transfer'] == 1){
                    $sqlValidTLDPrices = "SELECT COUNT(*) FROM tld "
                                        ."WHERE period <= ? AND period >= ? "
                                        ."AND transferprice <= ? AND transferprice >= ? "
                                        ."AND renewal <= ? AND renewal >= ? "
                                        ."AND name = ?";
                }else{
                    $sqlValidTLDPrices = "SELECT COUNT(*) FROM tld "
                                        ."WHERE period <= ? AND period >= ? "
                                        ."AND price <= ? AND price >= ? "
                                        ."AND renewal <= ? AND renewal >= ? "
                                        ."AND name = ?";
                }
    
                $tldResult = $this->db->query($sqlValidTLDPrices,
                                              $aTLDInfo[0] + 0.0001,
                                              $aTLDInfo[0] - 0.0001,
                                              $aTLDInfo[1] + 0.0001,
                                              $aTLDInfo[1] - 0.0001,
                                              $aTLDInfo[2] + 0.0001,
                                              $aTLDInfo[2] - 0.0001,
                                              $tld);
                list($countTLD) = $tldResult->fetch();
    
                // Validate if Registration Length exist
                if($countTLD != 1){
		    // Added by Dixon to test the Free Domain Option
		    $freeDomainTestQuery = "SELECT count(DISTINCT t.id) FROM tld t, package_tld pt WHERE t.id = pt.tld_id AND pt.period = ? AND t.name = ?";
		    $freeDomainTestResult = $this->db->query($freeDomainTestQuery, $aTLDInfo[0], $tld);
		    list($countFreeTLD) = $freeDomainTestResult->fetch();
		    if($countFreeTLD != 1) {
			$arrHack[] = $this->lang("Registration Length has been altered with an invalid value");
		    }
                    //$arrHack[] = $this->lang("Registration Length has been altered with an invalid value");
                }*/
            }
            
            // Validate Domain
            $checkDomainResult = $this->checkDomain();

            switch($checkDomainResult[0]){
                case '-1':
                    $arrHack[] = $this->lang('Warning') . ': ' . $this->lang('Domain Name') . ' ' . $checkDomainResult[1] . ' ' . $this->lang('already has an account with us. If you are a current customer please submit a support ticket for assistance.');
                    break;
                case '0':
                    break;
                case '1':
                    if($_REQUEST['transfer'] == 0){
                        $arrHack[] = $this->lang('Domain Is Already Registered') . '. ' . $this->lang('According to registrar records, the domain') . ' '. $checkDomainResult[1] . ' '. $this->lang('is already registered.');
                    }
                    break;
                case '2':
                    $arrHack[] = $this->lang('Registrar Error') . '. ' . $this->lang('Domain extension not recognized or supported');
                    break;
                case '3':
                    $arrHack[] = $this->lang('Domain Name') . ' ' . $checkDomainResult[1] . ' ' . $this->lang('is not valid. Please try again');
                    break;
                case '5':
                    $tmessage = $this->lang('Could not contact registry to lookup domain');
                    if(isset($strReturnValue[2])){
                        $tmessage .= '. ' . $this->lang('Registrar returned') . ': ' . $strReturnValue[2];
                    }
                    $arrHack[] = $tmessage;
                    break;
                default :
                    $arrHack[] = $this->lang('There was a problem trying to register this domain');
                    break;
            }
        }

        // Validate Discount Amount
        if($_REQUEST['discount']){
            require_once 'modules/billing/models/Coupon.php';
            if ($coupon = Coupon::validate($_REQUEST['coupon_code'], $_REQUEST['clienttype'], $_REQUEST['package'], $tPaymentTerm)){
              
                // If Coupon is of Amount Type, validate that its Amount value is right
                if(!$coupon['type']){
                    if($_REQUEST['discount'] !=  - $coupon['discount']){
                        $arrHack[] = $this->lang("Discount Amount has been altered");
                    }
                }
            }
        }

        // Validate Billing Cycle
        if(isset($_REQUEST['paymentterm'])){
            // Validate if Billing Cycle has a valid value
            if(!in_array($_REQUEST['paymentterm'], array(0,1,3,6,12,24))){
                $arrHack[] = $this->lang("Billing Cycle has been altered with an invalid value");
            }else{
                $query = "SELECT price1included, price3included, price6included, "
                               ."price12included, price24included FROM package WHERE id = ?";
                $result = $this->db->query($query, $_REQUEST['package']);

                $tPriceincluded = array();
                list($tPriceincluded[1],$tPriceincluded[3],$tPriceincluded[6],$tPriceincluded[12],$tPriceincluded[24]) = $result->fetch();

                if($_REQUEST['paymentterm'] != 0){
                    // Validate if Billing Cycle is allowed
                    if($tPriceincluded[$_REQUEST['paymentterm']] != 1){
                        $arrHack[] = $this->lang("Billing Cycle has been altered with an invalid value");
                    }
                }else{
                    // Validate if Billing Cycle should be a one time charge
                    if(in_array(1, $tPriceincluded)){
                        $arrHack[] = $this->lang("Billing Cycle has been altered with an invalid value");
                    }
                }
            }
        }
        
        return $arrHack;
    }

    /**
    * @return int possible return values:
    *       -1:    Domain name already has an account in this system
    *       0:     Domain available
    *       1:     Domain already registered
    *       2:     Registrar Error, domain extension not recognized or supported
    *       3:     Domain invalid
    *       5:     Could not contact registry to look up domain
    */
    function checkDomain()
    {
        $firstPoint = strpos($this->domain, '.');
        $domain    = mb_substr($this->domain, 0, $firstPoint);
        $extension = mb_substr($this->domain, $firstPoint + 1);
        
        $this->logger->log(4, "CheckDomainReturn('".$domain."', '".$extension."')");
        $message = false;
        $i = 0; //domain available
        if ($this->settings->get('Check Domain Availability') == 1) {
            $query = "SELECT plugin FROM tld WHERE name = ?";
            $result = $this->db->query($query, $extension);
            list ($pluginName) = $result->fetch();
            if ($pluginName == "") {
                // use whois
                //Flag to cWhois not to do second
                //full whois for .com etc as not
                //required here
                $this->logger->log(4, "Checking domain using cWhois");
                include 'newedge/classes/cWhois/cwhois.php';
                $GLOBALS['dtd'] = $dtd; // cwhois searches this in the global scope...
                $Reg="*";
                $i=cWhois($domain,'.' . $extension,$Reg);
            } else {
                // using registrar service
                $this->logger->log(4, "Checking domain using ".$pluginName);
                include_once 'newedge/classes/NE_PluginCollection.php';
                $registrar_plugins = new NE_PluginCollection('registrars', $this->user);
                $registrarVariables = $registrar_plugins->callFunction($pluginName, 'getVariables');
                $params = array();
                foreach ($registrarVariables as $key => $var) {
                    $settingname = "plugin_".$pluginName."_".$key;
                    $params = array_merge($params,array( $key => $this->settings->get($settingname) ));
                }
                $params = array_merge($params, array(
                    'tld'   => $extension,
                    'sld'   => $domain,
                ));
                $response = $registrar_plugins->callFunction($pluginName, 'checkDomain', $params);
                $this->logger->log(4, "CheckDomain::callfunction result: " . print_r($response, true));
                $i = $response[0];
                if (@isset($response[1])) $message = $response[1];
            }
        }

        if ((($i==1)||($i==0)) && $this->settings->get('Domain name duplicates handling') >= 2){
            $query = "SELECT id, status "
                    ."FROM domains "
                    ."WHERE DomainName = ? ";
            $result = $this->db->query($query, $domain.'.'.$extension);
            $row = $result->fetch();
            if($this->settings->get('Domain name duplicates handling') == 2){
                if($result->getNumRows() > 0 && $row['status'] != 3) $i = -1;   
            } elseif ($this->settings->get('Domain name duplicates handling') == 3){
                if($result->getNumRows() > 0) $i = -1; 
            }
        }
            
        $strReturnValue[] = $i;
        $strReturnValue[] = $domain . '.' . $extension;
        if ($message){
             $strReturnValue[] = strip_tags($message);
        }
        $this->logger->log(4, "CheckDomainReturn: " . print_r($strReturnValue, true));
        return $strReturnValue;
    }

    function logHackAttempt($arrHack)
    {
        $logHack = "A hack attempt has been detected:\r\n\r\n"
                  .implode("\r\n", $arrHack)
                  ."\r\n\r\n";

        $ip = NE_Network::getRemoteAddr();
        $host = @gethostbyaddr($ip);
        $agent = $_SERVER['HTTP_USER_AGENT'];
        
        $logHack .= "===== ".$this->lang("ATTACKER INFO")." =====\r\n";
        
        $logHack .= "IP: $ip\r\n";
        $logHack .= "HOSTNAME: $host\r\n";
        $logHack .= "USER AGENT: $agent\r\n";
        $query = "SELECT * FROM customuserfields WHERE insignup=1";
        $result = $this->db->query($query);
        while ($row = $result->fetch()) {
            if (isset($_REQUEST['CT_'.$row['id']]) && $_REQUEST['CT_'.$row['id']] != '') {
                $logHack .= $this->varLang($row['name']).": ".strip_tags($_REQUEST['CT_'.$row['id']]);
                if($row['name'] == 'Organization'){
                    if(isset($_REQUEST['isOrganization'])){
                        $logHack .= " (".$this->lang("business account").")";
                    }else{
                        $logHack .= " (".$this->lang("individual account").")";
                    }
                }
                $logHack .= "\r\n";
            }
        }

        if (@$_REQUEST['member']=="on"){
            $tUserID = $_REQUEST['memberuserid'];
            include_once 'modules/clients/models/user.php';
            $memberUser = new user($tUserID);
            $tFirstName = $memberUser->getFirstName();
            $tLastName = $memberUser->getLastName();
            $tOrganization = $memberUser->getOrganization();
            if ($tOrganization) $tLastName .= " - $tOrganization";
            
            $logHack .= $this->lang("Existing Member").": $tFirstName $tLastName\r\n";
            
            $tEmail = $memberUser->getEmail();
            $logHack .= $this->lang("Email").": $tEmail\r\n";
        }
        if ($this->domain!="") {
            $logHack .= $this->lang("Domain Name").": $this->domain\r\n";
        }
        
        $this->logger->log(1, "CLIENTEXEC HACK ATTEMPT DETECTED: \r\n" . $logHack);
    }

/* ADDED TO PREVENT HACK */

    function validateData()
    {
        $arrErrors = array();

        // Only check the profile custom fields and duplicate email if not an existing member
        if (!isset($_REQUEST['member']) || $_REQUEST['member'] != 'on') {
            $query = "SELECT * FROM customuserfields WHERE insignup=1 AND isrequired=1";
            $result = $this->db->query($query);
            while ($row = $result->fetch()) {
                if (!isset($_REQUEST['CT_'.$row['id']]) || $_REQUEST['CT_'.$row['id']] == '') {
                    $arrErrors[] = $row['name'].' '.$this->lang('cannot be blank');
                }
            }
            
            if ($this->userGateway->checkEmailDuplicate(htmlspecialchars($_REQUEST['CT_4'], ENT_QUOTES), true)) {
                $arrErrors[] = $this->lang('This E-mail address is already in use');
            }
        }
        
        /* *** NEW CODE *** */
        $query = "SELECT id, "
                ."name "
                ."FROM customField "
                ."WHERE groupId = ".CUSTOM_FIELDS_FOR_PACKAGE." "
                ."AND InSignup = 1 "
                ."AND isRequired = 1 ";
        /* *** NEW CODE *** */
        
        
        /* *** OLD CODE *** */
        /*
        $query = "SELECT * "
                ."FROM customdomainfields "
                ."WHERE insignup = 1 "
                ."AND isrequired = 1 ";
        */
        /* *** OLD CODE *** */
        
        $result = $this->db->query($query);
        
        while ($row = $result->fetch()) {
            $innerQuery = "SELECT * "
                         ."FROM promotion_customdomainfields "
                         ."WHERE promotionid = ? "
                         ."AND customid = ? ";
            $innerResult = $this->db->query($innerQuery, $this->clienttype, $row['id']);
            
            if ($innerResult->fetch()) {
                continue;
            }
            
            if (!isset($_REQUEST['PCT_'.$row['id']])
              || $_REQUEST['PCT_'.$row['id']] == '') {
                $arrErrors[] = $row['name'].' '.$this->lang('cannot be blank');
            }
        }
        
/* IS THIS CODE DOING SOMETHING? */
//        if (isset($domain) && $domain != '' && !preg_match(REGEXDOMAIN, $domain)) {
//            $arrErrors[] = $this->lang('invalid domain name');
//        }
/* IS THIS CODE DOING SOMETHING? */

/* SHOULDN'T IT BE LIKE THIS? */
        if (isset($this->domain) && $this->domain != '' && !preg_match(REGEXDOMAIN, $this->domain)) {
            $arrErrors[] = $this->lang('invalid domain name');
        }
/* SHOULDN'T IT BE LIKE THIS? */

        return $arrErrors;
    }

    /**
    * @static
    */
    function getServerIdAndIP()
    {
        // Use server that hasn't been used for the longest time and that hasn't filled up his domains quota
        $query = "SELECT s.id, s.sharedip, s.domains_quota FROM server s LEFT JOIN package_server ps ON s.id=ps.server_id "
                ."WHERE ps.package_id=? ORDER BY s.last_utilization ASC, ps.id ASC";
        $result = $this->db->query($query, $_REQUEST['package']);
        $tServerID = 0;
        $tServerIP = '';
        while ($row = $result->fetch()) {
            $query2 = "SELECT COUNT(id) AS num_domains "
                     ."FROM domains "
                     ."WHERE serverid = ? ";
            $result2 = $this->db->query($query2, $row['id']);
            $row2 = $result2->fetch();
            if ($row2['num_domains'] >= $row['domains_quota'] && $row['domains_quota'] != 0) {
                continue;
            }
            $tServerID = $row['id'];
            $tServerIP = $row['sharedip'];
            break;
        }

        return array($tServerID, $tServerIP);
    }

    /**
    * If the new customer previously had a guest account, move the tickets from the guest account
    * and delete the guest account.
    *
    * @access private
    */
    function _importGuestTickets(&$user)
    {
        if (!isset($this->configuration['modules']['support']['installedVersion'])) {
            return;
        }


        if (!$guestUserIt = $this->userGateway->getGuestUserIteratorWithEmail($user->getEmail())) {
            return;
        }

        if (!$guestUser = $guestUserIt->fetch()) {
            return;
        }

        require_once 'modules/support/actions/SetOwner.php';
        $setOwner = new SetOwner('support', 'SetOwner');
        $setOwner->setUser($this->user);
        $setOwner->setCustomer($this->customer);
        $setOwner->moveTicketsFromGuestUser($guestUser, $user);
    }
}

?>
