<?php
require_once 'modules/admin/models/RegistrarPlugin.php';
require_once dirname(__FILE__).'/class.onlinenic.php';

/**
* @package Plugins
*/
class PluginOnlinenic extends RegistrarPlugin
{
    function getVariables()
    {
        $variables = array(
            /*T*/'Plugin Name'/*/T*/ => array (
                                'type'          =>'hidden',
                                'description'   =>/*T*/'How CE sees this plugin (not to be confused with the Signup Name)'/*/T*/,
                                'value'         =>/*T*/'OnlineNIC'/*/T*/
                               ),
            /*T*/'Use testing server'/*/T*/ => array(
                                'type'          =>'yesno',
                                'description'   =>/*T*/'Select Yes if you wish to use OnlineNIC\'s testing environment, so that transactions are not actually made.'/*/T*/,
                                'value'         => 0
                               ),
            /*T*/'Username'/*/T*/ => array(
                                'type'          => 'text',
                                'description'   => /*T*/'Enter your username for your OnlineNIC reseller account.'/*/T*/,
                                'value'         => '',
                            ),
            /*T*/'Private Key'/*/T*/  => array(
                                'type'          => 'password',
                                'description'   => /*T*/'Enter your OnlineNIC reseller password.'/*/T*/,
                                'value'         => '',
                            )
        );

        return $variables;
    }

    function getError($return, $request)
    {
        $errorMessage = '';
        if($return == null) {
            $errorMessage = "OnlineNIC Error: Ensure port 20001 is open and PHP is compiled with OpenSSL.";
            $this->logger->log(4, $errorMessage);
            return true;
        }
        if($return['result'][0]['@']['code'] != 1000){
            if($return['result'][0]['@']['code'] == 1700 && $request == 'Register Domain'){
                $errorMessage = "OnlineNIC ".$request." Successfully, but fail to keep it in OnlineNIC's database. Please contact OnlineNIC: ".$return['result'][0]['#']['msg'][0]['#'];
            }else{
                $errorMessage = "OnlineNIC ".$request." Failed: ".$return['result'][0]['#']['msg'][0]['#'];
                if(isset($return['result'][0]['#']['value'][0]['#']) && $return['result'][0]['#']['value'][0]['#'] != 'no value') $errorMessage .= " (".$return['result'][0]['#']['value'][0]['#'].")";
            }
        }
        if($errorMessage != ''){
            $this->logger->log(4, $errorMessage);
        }
        return $errorMessage;
    }

    function checkDomain($params)
    {
        $host = 'onlinenic.com';
        if ($params['Use testing server']) $host = '218.5.81.149';
        
        $onlinenic = new OnlineNIC($host, 
                                   $params['Username'],
                                   $params['Private Key'],
                                   $this->logger);
                               
        $loginReturn = $onlinenic->login();
        
        // Check for login errors
        if($this->getError($loginReturn, 'Login') != '') return array(5);
        
        $return = $onlinenic->lookup_domain(strtolower($params['sld']), strtolower($params['tld']));

        // Check for lookup errors
        if($this->getError($return, 'Lookup') != '') return array(5);
        
        $available = $return['resData'][0]['#']['domain:chkData'][0]['#']['domain:cd'][0]['@']['x'];

        $logoutReturn = $onlinenic->logout();
        
        // Check for logout errors
        $this->getError($logoutReturn, 'Logout');

        if ($available == '-') return array(0);
        if ($available == '+') return array (1);
        return array(5);
    }

    function registerDomain($params)
    {
        if ($params['Use testing server']) {
            $host = '218.5.81.149';
            $params['NS1']['hostname'] = "ns2.onlinenic.com";
            $params['NS2']['hostname'] = "ns3.onlinenic.com";
            $params['Custom NS'] = 1;
            for ($i = 3; $i <= 12; $i++) {
                unset($params['NS'.$i]);
            }
        } else {
            $host = 'onlinenic.com';
            if (isset($params['NS1'])) {
               $params['Custom NS'] = 1;
            } else {
                $params['Custom NS'] = 0;
            }
        }
        
        $onlinenic = new OnlineNIC($host,
                                   $params['Username'],
                                   $params['Private Key'],
                                   $this->logger);

        $params['domain'] = strtolower($params['sld'].".".$params['tld']);
        $params['RegistrantPhone'] = $this->_plugin_onlinenic_validatePhone($params['RegistrantPhone'],$params['RegistrantCountry']);
        if ($params['RegistrantOrganizationName'] == "") $params['RegistrantOrganizationName'] = $params['RegistrantFirstName']." ".$params['RegistrantLastName'];
        
        /* Grab some information that isn't passed by default */
        $query = "SELECT username "
                ."FROM domains "
                ."WHERE DomainName = ? ";
        $result = $this->db->query($query, $params['sld'].".".$params['tld']);
        list ($params['DomainUsername']) = $result->fetch();
        
        $query = "SELECT id from customuserfields where type='8'";
        $result = $this->db->query($query);
        list($fieldid) = $result->fetch();
        
        $query = "SELECT id FROM users WHERE email=?";
        $result = $this->db->query($query, $params['RegistrantEmailAddress']);
        list($userid) = $result->fetch();
        
        $query = "SELECT value FROM user_customuserfields WHERE customid=? AND userid=?";
        $result = $this->db->query($query, $fieldid, $userid);
        list($lang) = $result->fetch();
        if (strtolower($lang) == 'french') $params['RegistrantLanguage'] = 'FR';
        else $params['RegistrantLanguage'] = 'EN';

        $loginReturn = $onlinenic->login();
        
        // Check for login errors
        $errorMessage = $this->getError($loginReturn, 'Login');
        if($errorMessage != '') return array(-1, array($errorMessage));      

        
//      Review in DataBase if this user has a contact id for OnlineNIC, if not, then create it
//      some SQL query
        
//      if(this user has a contact id for OnlineNIC){
//          $params['ContactID'] = DATABASE_VALUE;
//      }else{

            $createContactReturn = $onlinenic->create_contact($params);
        
            // Check for create contact errors
            $errorMessage = $this->getError($loginReturn, 'Create Contact');
            if($errorMessage != '') return array(-1, array($errorMessage));
            
//          Store in the DataBase the contact id for OnlineNIC
//          some SQL query

            $params['ContactID'] = $createContactReturn['resData'][0]['#']['contact:creData'][0]['#']['contact:id'][0]['#'];
//      }

        $return = $onlinenic->register_domain($params);
        
        // Check for register domain errors
        $errorMessage = $this->getError($loginReturn, 'Register Domain');
        if($errorMessage != '') return array(-1, array($errorMessage));

        $this->logger->log(4, "OnlineNIC Registration Response: ".$return['result'][0]['#']['msg'][0]['#']);
        $regId = $return['trID'][0]['#']['svTRID'][0]['#'];

        $logoutReturn = $onlinenic->logout();
        
        // Check for logout errors
        $this->getError($logoutReturn, 'Logout');
        
        return array($regId);
    }

    // @access private
    function _plugin_onlinenic_validatePhone($phone, $country)
    {
        // strip all non numerical values
        $phone = preg_replace('/[^\d]/', '', $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";
    }
    
    function disableRenewal($params)
    {
    }
}

?>
