<?php

require_once 'modules/admin/views/SignupView.php';
require_once 'modules/clients/models/UserGateway.php';
require_once 'newedge/classes/NE_Network.php';
require_once 'newedge/classes/NE_MailGateway.php';
require_once 'newedge/classes/NE_PluginCollection.php';

/**
* After user info has bee submited:
* - Check if customer's e-mail already exists
* - Check with fraud plugins if enabled
* - Show terms and conditions if enabled
* - Continue with step four
*
* @package Admin
*/
class Signup_3_Validation extends SignupView
{
    var $permission     = '';
    var $showHeader     = false;
    
    function preHeaders()
    {
        $this->initialize();
    }

    function dispatch()
    {
        $fraudmsg = '';

        $arrError = Array();

        // ****** CHECK ACCESS CODE ******
        if (    $this->settings->get('Request Access Code') == 1
                && !@$_REQUEST['member']=='on'
                && (!isset($_SESSION['sessAccessCode']) || $_SESSION['sessAccessCode'] != addslashes(strtoupper($_POST['accesscode']))))
        {
                    $arrError[] = $this->lang("The access code does not match with the one in the image.");
        }

        // ****** CHECK PASSWORD STRENGTH ******
        if ($this->settings->get('Enforce Password Strength in Signup') || $this->settings->get('Enforce Password Strength For Domains')) {
            include_once 'modules/admin/models/PasswordStrength.php';
            $passwordStrength = new PasswordStrength($this->settings);

            // no need to check existing users passwords
            if ($this->settings->get('Enforce Password Strength in Signup') && (!isset($_REQUEST['member']) || $_REQUEST['member'] != 'on')) {
                $passwordStrength->setPassword($_REQUEST['new_password']);   // use the unfiltered value
                if (!$passwordStrength->validate()) {
                    foreach ($passwordStrength->getMessages() as $message) {
                        $arrError[] = $this->varLang($message);
                    }
                }
            }
        }

        // ****** VALIDATE DOMAIN USERNAME AND PASSWORD******
        if ($this->domain != '') {
            include_once 'modules/admin/views/Signup_4_CreateAccounts.php';
            include_once 'modules/admin/models/server.php';

            if (!isset($_REQUEST['new_domain_username'])) {
                // cpanel usernames can't be longer than 8 characters
                $_REQUEST['new_domain_username'] = mb_substr(str_replace(array('.', '-'), '', $this->domain), 0, 8);
            }
            $_POST['new_domain_username'] = $_REQUEST['new_domain_username'];
            if (!isset($_REQUEST['new_domain_password'])) {
                $checkPasswordStrength = false;
                if (!@$_REQUEST['member']=='on') {
                    $_REQUEST['new_domain_password'] = $_REQUEST['new_password'];
                    $_POST['new_domain_password'] = $_REQUEST['new_password'];
                } else {
		    $pwd = "123".$this->domain;
                    $_REQUEST['new_domain_password'] = mb_substr(str_replace('.', '', $pwd), 0, 8);
                    $_POST['new_domain_password'] = mb_substr(str_replace('.', '', $pwd), 0, 8);
                }
            } else {
                $checkPasswordStrength = true;
            }

            if ($this->domain && $this->settings->get('Enforce Password Strength For Domains') && $checkPasswordStrength) {
                $passwordStrength->setPassword($_REQUEST['new_domain_password']);   // use the unfiltered value
                if (!$passwordStrength->validate()) {
                    foreach ($passwordStrength->getMessages() as $message) {
                        $arrError[] = $this->varLang($message);
                    }
                }
            }

            list($tServerID, $tServerIP) = Signup_4_CreateAccounts::getServerIdAndIP();
            
            if($tServerID != 0){
                $server = New Server($tServerID);
                $pluginName = $server->GetPluginName();
                if ($pluginName != '') {
                    $server_plugins = new NE_PluginCollection("server", $this->user);
                    $params = array_merge(  $server->GetAllServerPluginVariables($this->user, $pluginName),
                                            array(
                                                'DomainUsername'        => $_REQUEST['new_domain_username'],
                                                'DomainPassword'        => $_REQUEST['new_domain_password'],
                                                'DomainName'            => $this->domain,
                                            ),
                                            $server->GetParams("Create",$pluginName)
                                        );

		try
		{
			$result = $server_plugins->callFunction($pluginName, 'validateCredentials', $params);

			if (is_a($result, 'NE_Error')) {
				foreach ($result->getMessagesArr() as $error) {
					$arrError[] = $this->varLang($error);
				}
			} else {
				$_REQUEST['new_domain_username'] = $result;
				$_POST['new_domain_username'] = $result;
			}
		}
		catch ( Exception $ex )
		{
			$arrError[] = $ex->getMessage();
		}
                }
            }
        }

        $arrError = array_unique($arrError);

        // ****** CHECK E-MAIL DUPLICATE ******
        if (!isset($_REQUEST['member']) || $_REQUEST['member'] != 'on') {
            $userGateway = new UserGateway();
            if ($userGateway->checkEmailDuplicate(htmlspecialchars($_REQUEST['CT_4'], ENT_QUOTES), true)) {
                $arrError[] = $this->lang("This E-mail address is already in use");
            }
        }

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

        // ****** CHECK WITH FRAUD PLUGINS ******
        if (!$arrError && @!$_REQUEST['member'] == 'on') {
            $fraudPlugins = new NE_PluginCollection("fraud", $this->user);
            while ($fraudPlugin = $fraudPlugins->getNext()) {
                if (!$this->settings->get('plugin_'.$fraudPlugin->getInternalName()."_Enabled")) {
                    continue;
                }

    	        $fraudmsg .= "<br>\n------------------------------<b><br>\n";
    	        $fraudmsg .= $this->lang("Fraud Details for %s Fraud Plugin", $this->settings->get("plugin_".$fraudPlugin->getInternalName()."_Plugin Name"))."<br>\n";
    	        $fraudmsg .= "</b>------------------------------<br>\n";              

                $fraudPlugin->grabDataFromRequest($_REQUEST);
                $fraudCheckResult = $fraudPlugin->execute();

                $outputkeys = array_keys($fraudCheckResult);
                $numoutputkeys = count($fraudCheckResult);
                for ($i = 0; $i < $numoutputkeys; $i++) {
                     $key = $outputkeys[$i];
                     $value = $fraudCheckResult[$key];
                     $fraudmsg .= $key . " = " . $value . "<br>\n";
                }

                // post the fraud score for use in the phone verification step
                $_POST['fraudScore'] = $fraudPlugin->getScore();

                $fraudPlugin->extraSteps();

                if (!$fraudPlugin->isOrderAccepted()) {
                    $arrError = array_merge($arrError, $fraudPlugin->getFailureMessages());
                }
            }
        } 

        $phonenum = '';
        $phoneKey = '';
        $countryCode = '';
        foreach ($_POST as $key => $val) {
            if ($key == 'phoneField') {
                $phonenum = $_REQUEST[$val];
                $phoneKey = $val;
            }
            if ($key == 'country') {
                $countryCode = $_REQUEST[$val];
            }

        }
        $this->logger->log(3,"phonenum=".$phonenum." countryCode = ".$countryCode);
        $_REQUEST[$phoneKey] = $this->_validatePhone($phonenum,$countryCode);
        $this->logger->log(3," phone = ".$_REQUEST[$phoneKey]);
        
        // ******** IF ANY CHECK FAILED, SEND NOTIFICATIONS AND REDIRECT TO STEP 2 *********

        if (!@$_REQUEST['member'] == 'on' && $arrError) {
            $strMessageOutput = "------------------------------<b><br>\n";
        	$strMessageOutput .= $this->lang("Reason For Rejection")."<br>\n";
        	$strMessageOutput .= "</b>------------------------------<br>\n";
        	foreach($arrError as $reason) {
        		$strMessageOutput .= $reason."<br>\n";
        	}
        	
        	$strMessageOutput .= "<br>\n------------------------------<b><br>\n";
            $strMessageOutput .= $this->lang("Customer Details").":<br>\n";
    		$strMessageOutput .= "</b>------------------------------<br>\n";
    		
    		if ($_REQUEST['domain'] != "") {
            	$strMessageOutput .= $this->lang("Domain Name").": ".strip_tags($_REQUEST['domain']);
            	$strMessageOutput .= $this->lang("Domain Username").": ".strip_tags($_REQUEST['new_domain_username']);
            	$strMessageOutput .= $this->lang("Domain Password").": ".strip_tags($_REQUEST['new_domain_password']);
            	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 transfer their own domain");
    	                break;
    	        }
    		}
    		
    		$customTagsArray = unserialize(base64_decode($_REQUEST['customTagsArray']));
    		//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) {
                             $value = NE_Lib::form_to_db($value, "/");
                         }
                         $strMessageOutput .= "<br>\n$tCustomName: $value";
                    }
                }
            }
            
            //Enter Account Information
    	    $query="SELECT planid,planname FROM package WHERE id=?";
    	    $result = $this->db->query($query, $_POST['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 (!@$_REQUEST['member'] == 'on') {
    	        //Extra Signup Email Info
    	        $strMessageOutput .= "<br>\nRequested Password: ".$_REQUEST['new_password'];
    	        $strMessageOutput .= "<br>\nPayment Type: ".mb_substr($_POST['paymenttype'], 2);
    	        if ($_POST['paymenttype'] == 'paypal' && isset($_POST['use_paypal_subscriptions']))
    	            $strMessageOutput .= ' - '.$this->lang("Subscriptions enabled");
    	    }
            
            $strMessageOutput .= "<br><br>\n\n<b>------------------------------<br>\n
                                 ".$this->lang("Package Variables")."
                                 <br>\n------------------------------</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) {
                             $value = NE_Lib::form_to_db($value, "/");
                         }
                         $strMessageOutput .= "<br>\n$tCustomName: $value";
                    }
                }
            }
            
            $strMessageOutput .= "<br><br>\n\n------------------------------<b><br>\n";
            $strMessageOutput .= $this->lang("Signup Environment").":\n";
            $strMessageOutput .= "<br></b>------------------------------<br>\n";
            //Enter some initial commments for customer
            $ip = NE_Network::getRemoteAddr();
            $host = @gethostbyaddr($ip);
            $agent = $_SERVER['HTTP_USER_AGENT'];
            
            $strMessageOutput .= "IP: $ip<br>\n";
            $strMessageOutput .= "HOSTNAME: $host<br>\n";
            $strMessageOutput .= "USER AGENT: $agent<br>\n";
    		
    	    //add fraud message to admin comments
    	    if ($fraudmsg!=""){
    	        $strMessageOutput .= $fraudmsg;
    	    }
    	    
    	    $strMessageOutput .= "<br><br>\n\n".$this->lang("Thank you for using ClientExec!")."<br>\n";
    	    $strMessageOutput .= "<b>".$this->lang("The ClientExec Team")."</b>\n";
    	    $strMessageOutput .= "<br>http://www.clientexec.com";
    	    
    	    $this->SendOutNotifications($tFirstName, $tLastName, $_REQUEST['domain'], $strMessageOutput, false, false);

            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);
            exit;
        }

        $_SESSION['signupValidated'] = true;

        $_REQUEST['fraudmsg'] = $fraudmsg;
        $_POST['fraudmsg'] = $fraudmsg;

        if ($this->settings->get('Show Terms and Conditions') == 0) {
            if (!@$_REQUEST['member']=='on') {
                $phoneVerificationPlugins = new NE_PluginCollection('phoneverification', $this->user);
                
                while ($phoneVerificationPlugin = $phoneVerificationPlugins->getNext(false)) {
                    if ($this->settings->get("plugin_{$phoneVerificationPlugin}_Enabled") == 1
                        && $this->settings->get("plugin_{$phoneVerificationPlugin}_Minimum Bill Amount to Trigger Telephone Verification") <= $_POST['totalBill'])
                    {
                        require 'modules/admin/views/Signup_3b_PhoneVerification.php';
                        $phoneVerif = new Signup_3b_PhoneVerification('admin', 'Signup_3b_PhoneVerification', $this->settings);
                        $phoneVerif->setUser($this->user);
                        $phoneVerif->setTpl($this->tpl);
                        $phoneVerif->preHeaders();
                        $phoneVerif->dispatch();
                        return;
                    }
                }
            }

            require_once 'modules/admin/views/Signup_4_CreateAccounts.php';
            $createAccounts = new Signup_4_CreateAccounts('admin', 'Signup_4_CreateAccounts', $this->settings);
            $createAccounts->setUser($this->user);
            $createAccounts->setCustomer($this->customer);
            $createAccounts->setTpl($this->tpl);
            $createAccounts->preHeaders();
            $createAccounts->dispatch();
            return;
        }

        $this->templateInit();
        $this->forceShowHeader();
        
        $this->tpl->assign("SUBMITFUNCTION","SubmitStepThree");
        $this->tpl->assign("BACKFUNCTION","BackStepThree");
        $this->tpl->assign("BACKINPUTNAME","back");
        $this->tpl->assign("BACKINPUTVALUE","1");
        $this->tpl->assign("INPUTNAME","next");
        $this->tpl->assign("INPUTVALUE","1");
        $this->tpl->assign("SIGNUPBLOCKDESCRIPTION",$this->lang("Terms and Conditions"));

        //populate all the fields passed from previous step
        $_POST['step'] = 4;
        if (!isset($_REQUEST['member'])) {
            $phoneVerificationPlugins = new NE_PluginCollection('phoneverification', $this->user);
            while ($phoneVerificationPlugin = $phoneVerificationPlugins->getNext(false)) {
                if ($this->settings->get("plugin_{$phoneVerificationPlugin}_Enabled") == 1) {
                    $_POST['step'] = 7;
                    break;
                }
            }
        }

        foreach ($_POST as $key=>$val) {
            $this->tpl->assign("INPUTNAME",$key);
            $this->tpl->assign("INPUTVALUE",$val);
            $this->tpl->parse("ALLTHEFIELDS", ".form_hidden_inputs");
        }
        $termsAndConditions = $this->settings->get('Terms and Conditions');
        $termsAndConditions['plainText'] = str_replace('&quot;','"',$termsAndConditions['plainText']);
        $termsAndConditions['HTML'] = str_replace('&quot;','"',$termsAndConditions['HTML']);
        $termsAndConditions['plainText'] = str_replace('&#039;','\'',$termsAndConditions['plainText']);
        $termsAndConditions['HTML'] = str_replace('&#039;','\'',$termsAndConditions['HTML']);
        if (trim($termsAndConditions['plainText']) != '') {
            $termsAndConditions = htmlspecialchars($termsAndConditions['plainText']);
            $termsAndConditions = nl2br($termsAndConditions);
            $this->tpl->assign('termsFontWeight', 'bold');
        } else {
            $termsAndConditions = $termsAndConditions['HTML'];
            $this->tpl->assign('termsFontWeight', 'normal');
        }
        $this->tpl->assign("TERMSANDCONDITIONS", $termsAndConditions);
        $this->tpl->assign("FRAUDMSG", $fraudmsg);
        $this->tpl->parse("SIGNUP_3_TOS","signup_3_termsofservice");
        $this->tpl->FastPrint("SIGNUP_3_TOS");

        $this->tpl->FastPrint("FOOTER");  //Display Footer
        $this->showFooter();
    }

    function _validatePhone($phone, $country)
    {
        // strip all non numerical values
        $phone = preg_replace('/[^\d]/', '', $phone);

        if($phone == ''){
            return $phone;
        }

        $query = "SELECT phone_code FROM country WHERE iso=? AND phone_code != ''";
        $result = $this->db->query($query, $country);
        if (!$row = $result->fetch()) {
            return $phone;
        }

        // check if code is already there
        $code = $row['phone_code'];
        $phone = preg_replace("/^($code)(\\d+)/", '+\1.\2', $phone);
        if ($phone[0] == '+') {
            return $phone;
        }

        // if not, prepend it
        return "+$code.$phone";
    }
}

?>
