<?php

require_once 'classes/RegistrarPlugin.php';
require_once dirname(__FILE__).'/class.opensrs.php';

/**
* @package Plugins
*/
class PluginOpensrs 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*/'OpenSRS'/*/T*/
                               ),
            /*T*/'Use Opensrs to check and register domains'/*/T*/ => array(
                                'type'          =>'yesno',
                                'description'   =>/*T*/"If you don't use any registrar, the domain check is done with whois."/*/T*/,
                                'value'         => 0
                               ),
            /*T*/'Use testing server'/*/T*/ => array(
                                'type'          =>'yesno',
                                'description'   =>/*T*/'Select Yes if you wish to use OpenSRS\'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 OpenSRS reseller account.'/*/T*/,
                                'value'         => '',
                            ),
            /*T*/'Private Key'/*/T*/  => array(
                                'type'          => 'password',
                                'description'   => /*T*/'Enter your OpenSRS reseller private key.'/*/T*/,
                                'value'         => '',
                            )
        );

        return $variables;
    }

    function checkDomain($params)
    {
         $host = 'rr-n1-tor.opensrs.net';
        if ($params['Use testing server']) $host = 'horizon.opensrs.net';
        
        $opensrs = new OpenSRS($host, 
                               $params['Username'],
                               $params['Private Key'],
                               $this->logger);
                               
        $return = $opensrs->lookup_domain(strtolower($params['sld'].".".$params['tld']));
        
        if ($return == null) {
            $this->logger->log(5, "OpenSRS Error: Ensure port 55443 is open and PHP is compiled with OpenSSL.");
            return array(5);
        }
        
        // Check for errors
        foreach ($return as $key=>$val)
        {
            if ($val['@']['key'] == 'response_code') $status_key = $key;
            if ($val['@']['key'] == 'is_success') $success_key = $key;
            if ($val['@']['key'] == 'response_text') $status_text = $key;
        }
        if ($return[$success_key]['#'] != 1) {
            $this->logger->log(5, "OpenSRS Lookup Failed: ".$return[$status_text]['#']);
            return array(5);
        }
        
        $available = $return[$status_key]['#'];
        if ($available == 200 || $available == 210) return array(0);
        if ($available == 211 || $available == 212) return array (1);
        return array(5);
    }

    function registerDomain($params)
    {
        if ($params['Use testing server']) {
            $host = 'horizon.opensrs.net';
            $params['NS1']['hostname'] = "default.opensrs.org";
            $params['NS2']['hostname'] = "default1.opensrs.org";
            $params['Custom NS'] = 1;
            for ($i = 3; $i <= 12; $i++) {
                unset($params['NS'.$i]);
            }
        } else {
            $host = 'rr-n1-tor.opensrs.net';
            if (isset($params['NS1'])) {
               $params['Custom NS'] = 1;
            } else {
                $params['Custom NS'] = 0;
            }
        }
        
        $opensrs = new OpenSRS($host, 
                               $params['Username'],
                               $params['Private Key'],
                               $this->logger);
                               
                               
        $params['domain'] = strtolower($params['sld'].".".$params['tld']);
        $params['RegistrantPhone'] = $this->_plugin_opensrs_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';
        
        
        $return = $opensrs->register_domain($params);
        
        if ($return == null) {
            $this->logger->log(5, "OpenSRS Error: Ensure port 55443 is open and PHP is compiled with OpenSSL.");
            return array(-1, array("OpenSRS Error: Ensure port 55443 is open and PHP is compiled with OpenSSL."));
        }
        foreach ($return as $key=>$val)
        {
            if ($val['@']['key'] == 'response_code') $status_key = $key;
            if ($val['@']['key'] == 'is_success') $success_key = $key;
            if ($val['@']['key'] == 'response_text') $status_text = $key;
            if ($val['@']['key'] == 'attributes') $attributes_key = $key;
        }
    
        $this->logger->log(5, "OpenSRS Registration Response: ".$return[$status_text]['#']);
        
        if (isset($attributes_key)) {
            $attributes = $return[$attributes_key]['#']['dt_assoc'][0]['#']['item'];
            if ($return[$success_key]['#'] == 1) {
                foreach ($attributes as $key=>$val) {
                    if ($val['@']['key'] == 'id') $regId = $val['#'];
                }
            }
        }
        $code = $return[$status_key]['#'];
        if ($code == 210 || $code == 200 || $code == 250) return array($regId);
        if ($code == 485) return array(0);
        return array(-1, array("Domain registration failed: ".$return[$status_text]['#']));
    }

    // @access private
    function _plugin_opensrs_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)
    {
    }
}

?>
