<?php

require_once 'classes/RegistrarPlugin.php';
require_once dirname(__FILE__).'/lib/apiutil.php';
/**
* @package Plugins
*/
class PluginDirecti 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*/'Directi'/*/T*/
                               ),
            /*T*/'Use testing server'/*/T*/ => array(
                                'type'          =>'yesno',
                                'description'   =>/*T*/'Select Yes if you wish to use Directi\'s testing environment, so that transactions are not actually made.<br><br><b>Note: </b>You will first need to register for a demo account at<br>http://cp.onlyfordemo.net/servlet/ResellerSignupServlet?&validatenow=false.'/*/T*/,
                                'value'         =>0
                               ),
            /*T*/'Login'/*/T*/ => array(
                                'type'          =>'text',
                                'description'   =>/*T*/'Enter your username for your Directi reseller account.'/*/T*/,
                                'value'         =>''
                               ),
            /*T*/'Password'/*/T*/ => array(
                                'type'          =>'password',
                                'description'   =>/*T*/'Enter the password for your Directi reseller account.'/*/T*/,
                                'value'         =>''
                               ),
            /*T*/'Role'/*/T*/ => array(
                                'type'          =>'hidden',
                                'description'   =>/*T*/'Type of account.'/*/T*/,
                                'value'         =>'reseller'
                               ),
            /*T*/'Language'/*/T*/ => array(
                                'type'          =>'hidden',
                                'description'   =>/*T*/'Language preference.'/*/T*/,
                                'value'         =>'en'
                               ),
            /*T*/'Parent ID'/*/T*/ => array(
                                'type'          =>'text',
                                'description'   =>/*T*/'This can be found in your Directi profile.'/*/T*/,
                                'value'         =>''
                               ),
            'Actions'   => array (
                                'type'          => 'hidden',
                                'description'   => 'Current actions that are active for this plugin',
                                'value'         => 'CheckDomain, DisableRenewal, EditNS, GetContact, GetInfo, GetNS, Register, RegisterNS, SetContact, SetNS, FetchDomains',
                                )
        );

        return $variables;
    }

    function checkDomain($params)
    {
        require_once dirname(__FILE__).'/lib/DomOrder.class.php';

        $params['sld'] = strtolower($params['sld']);
        $params['tld'] = strtolower($params['tld']);
        $domain = $params['sld'].".".$params['tld'];
        if ($params['Use testing server']) {
            $demo = "demo";
        } else {
            $demo = "";
        }

        $DomOrder = new DomOrder(dirname(__FILE__).'/lib/wsdl/'.$demo.'DomOrder.wsdl');

        $return = $DomOrder->checkAvailabilityMultiple(
                                 $params['Login'],
                                 $params['Password'],
                                 $params['Role'],
                                 $params['Language'],
                                 $params['Parent ID'],
                                 array($params['sld']),
                                 array($params['tld']),
                                 false
                                 );
        $this->logger->log(5, 'checkAvailabilityMultiple('.print_r($return,true).')');
        if ($return[$domain]['status'] === 'available') return array(0);
        elseif ($return[$domain]['status'] === 'regthroughus' || $return[$domain]['status'] === 'regthroughothers') return array(1);
        elseif ($return[$domain]['status'] == 'error' && $return[$domain]['error'] == 'Could not connect to registry') return array(2);
        else {
            $this->logger->log(5, 'Directi Result: [status]=>'.$return[$domain]['status'].' [error]=>'.$return[$domain]['error']);
            return array(5);
        }
    }

    function registerDomain($params)
    {
        // required classes to register a domain
        require_once dirname(__FILE__).'/lib/DomContact.class.php';
        require_once dirname(__FILE__).'/lib/DomOrder.class.php';
        require_once dirname(__FILE__).'/lib/Customer.class.php';
        require_once dirname(__FILE__).'/lib/DomContactExt.class.php';
        require_once dirname(__FILE__).'/lib/DotCoopContact.class.php';

        // variable setup and validation
        $params['sld'] = strtolower($params['sld']);
        $params['tld'] = strtolower($params['tld']);
        $domain = $params['sld'].".".$params['tld'];
        if ($params['Use testing server']) {
            $demo = "demo";
        } else {
            $demo = "";
        }
        $countrycode = $this->getCountryCode($params['RegistrantCountry']);
        $telno = $this->_validatePhone($params['RegistrantPhone'],$countrycode);
        if ($params['RegistrantOrganizationName'] == "") $params['RegistrantOrganizationName'] = "N/A";
        if ($params['Use testing server']) {
            // Required nameservers for test server
            $nameservers = array(
                                    "0" => "ns1.logicboxes.com",
                                    "1" => "ns2.logicboxes.com"
                                );
        } else {
            // maximum 12 name servers are allowed by Directi
            for ($i = 1; $i <= 12; $i++) {
                if (isset($params["NS$i"])) {
                    $nameservers["$i"] = $params["NS$i"]['hostname'];
                } else {
                    break;
                }
            }
        }
        // Create a new customer object
        $customer = new Customer(dirname(__FILE__).'/lib/wsdl/'.$demo.'Customer.wsdl');

        $return = $customer->addCustomer(
                                     $params['Login'],
                                     $params['Password'],
                                     $params['Role'],
                                     $params['Language'],
                                     $params['Parent ID'],
                                     $params['RegistrantEmailAddress'],
                                     $params['DomainPassword'],
                                     $params['RegistrantFirstName']." ".$params['RegistrantLastName'],
                                     $params['RegistrantOrganizationName'],
                                     $params['RegistrantAddress1'],
                                     null,
                                     null,
                                     $params['RegistrantCity'],
                                     $params['RegistrantStateProvince'],
                                     $params['RegistrantCountry'],
                                     $params['RegistrantPostalCode'],
                                     $countrycode,
                                     $telno,
                                     null,
                                     null,
                                     null,
                                     null,
                                     'en'
                                     );
        $this->logger->log(5, 'addCustomer('.print_r($return,true).')');
        if (isset($return['faultstring'])) {
            if (strpos($return['faultstring'],"is already a customer")) {
                $return = $customer->getCustomerId($params['Login'],$params['Password'],$params['Role'],$params['Language'],$params['Parent ID'],$params['RegistrantEmailAddress']);
                $this->logger->log(5, 'getCustomerId('.print_r($return,true).')');
            } elseif (strpos($return['faultstring'],"Zip is Invalid")) {
                return array(-1, array("Client Profile Error: Zip is Invalid"));
            } elseif (strpos($return['faultstring'],"Telephone Country Code/Telephone No. is invalid")) {
                return array(-1, array("Client Profile Error: Telephone Country Code/Telephone No. is invalid"));
            } elseif (strpos($return['faultstring'],"password")) {
                return array(-1, array("Password cannot be blank and must be at least 6 characters"));
            } else {
                return array(-1, array("Couldn't create client, please validate the client information."));
            }
        }

        $custID = print_r($return,true);

        $DomContact = new DomContact(dirname(__FILE__).'/lib/wsdl/'.$demo.'DomContact.wsdl');

        $return = $DomContact->listnames(
                                     $params['Login'],
                                     $params['Password'],
                                     $params['Role'],
                                     $params['Language'],
                                     $params['Parent ID'],
                                     $custID
                                     );
        $this->logger->log(5, '$domContact->listNames('.print_r($return,true).')');
        $contactID = null;
        for ($i = 1; $i <= $return['recsindb']; $i++) {
            if ($return[$i]['emailaddr'] == $params['RegistrantEmailAddress']) {
                $contactID = $return[$i]['contactid'];
            }
        }
        if ($contactID == null) {
            $return = $DomContact->add(
                                     $params['Login'],
                                     $params['Password'],
                                     $params['Role'],
                                     $params['Language'],
                                     $params['Parent ID'],
                                     $params['RegistrantFirstName']." ".$params['RegistrantLastName'],
                                     $params['RegistrantOrganizationName'],
                                     $params['RegistrantEmailAddress'],
                                     $params['RegistrantAddress1'],
                                     null,
                                     null,
                                     $params['RegistrantCity'],
                                     $params['RegistrantStateProvince'],
                                     $params['RegistrantCountry'],
                                     $params['RegistrantPostalCode'],
                                     $countrycode,
                                     $telno,
                                     null,
                                     null,
                                     $custID
                                     );
            $this->logger->log(5, '$domContact->add('.print_r($return,true).')');
            $return = $DomContact->addDefaultContact(
                                           $params['Login'],
                                           $params['Password'],
                                           $params['Role'],
                                           $params['Language'],
                                           $params['Parent ID'],
                                           $custID
                                           );
            $this->logger->log(5, 'addDefaultContact('.print_r($return,true).')');
            $contactID = print_r($return,true);
        }

        // Extra information required to register a .us and .coop domain through Directi
        if ($params['tld'] == 'us' || $params['tld'] == 'coop')
        {
            if ($params['tld'] == 'us') {
                $productKey = 'domus';
                $contactDetailsHash = array(
                                            'category'  => $params['ExtendedAttributes']['us_nexus'],
                                            'purpose'   => $params['ExtendedAttributes']['us_purpose']
                                            );
            } /*elseif ($params['tld'] == 'coop') {
                $productKey = 'dotcoop';
                $sponsor1 = null;
                $sponsor2 = null;
                $DotCoopContact = new DotCoopContact(dirname(__FILE__).'/lib/wsdl/'.$demo.'DotCoopContact.wsdl');
                // Get a list of current contacts and search for the submitted contacts
                $return = $DotCoopContact->getSponsorsList(
                                        $params['Login'],
                                        $params['Password'],
                                        $params['Role'],
                                        $params['Language'],
                                        $params['Parent ID'],
                                        $custID,
                                        $contactID
                                        );
                $GLOBALS['logger']->log(5, 'getSponsorList('.print_r($return,true).')');

                if (is_array($return['sponsorhash'])) {
                    foreach ($return['sponsorhash'] as $sponsor) {
                        if ($sponsor['emailaddr'] == $params['ExtendedAttributes']['sponsor1_email']) {
                            $sponsor1 = $sponsor['contactid'];
                        }
                        if ($sponsor['emailaddr'] == $params['ExtendedAttributes']['sponsor2_email']) {
                            $sponsor2 = $sponsor['contactid'];
                        }
                    }
                }

                foreach ($return['defsponsorhash'] as $sponsor) {
                    if ($sponsor['emailaddr'] == $params['ExtendedAttributes']['sponsor1_email']) {
                        $sponsor1 = $sponsor['contactid'];
                    }
                    if ($sponsor['emailaddr'] == $params['ExtendedAttributes']['sponsor2_email']) {
                        $sponsor2 = $sponsor['contactid'];
                    }
                }

                if ($sponsor1 == null) {
                    $countrycode = _plugin_Directi_getCountryCode($params['ExtendedAttributes']['sponsor1_country']);
                    $return = $DotCoopContact->addSponsor(
                                        $params['Login'],
                                        $params['Password'],
                                        $params['Role'],
                                        $params['Language'],
                                        $params['Parent ID'],
                                        $params['ExtendedAttributes']['sponsor1_name'],
                                        $params['ExtendedAttributes']['sponsor1_org'],
                                        $params['ExtendedAttributes']['sponsor1_email'],
                                        $params['ExtendedAttributes']['sponsor1_address'],
                                        null,
                                        null,
                                        $params['ExtendedAttributes']['sponsor1_city'],
                                        $params['ExtendedAttributes']['sponsor1_state'],
                                        $params['ExtendedAttributes']['sponsor1_country'],
                                        $params['ExtendedAttributes']['sponsor1_zip'],
                                        $countrycode,
                                        _plugin_Directi_validatePhone($params['ExtendedAttributes']['sponsor1_telephone'],$countrycode),
                                        null,
                                        null,
                                        $custID
                                        );
                   $GLOBALS['logger']->log(5, 'addSponsor('.print_r($return,true).')');
                   $sponsor1 = print_r($return, true);
               }
               if ($sponsor2 == null) {
                   $countrycode = _plugin_Directi_getCountryCode($params['ExtendedAttributes']['sponsor2_country']);
                   $return = $DotCoopContact->addSponsor(
                                        $params['Login'],
                                        $params['Password'],
                                        $params['Role'],
                                        $params['Language'],
                                        $params['Parent ID'],
                                        $params['ExtendedAttributes']['sponsor2_name'],
                                        $params['ExtendedAttributes']['sponsor2_org'],
                                        $params['ExtendedAttributes']['sponsor2_email'],
                                        $params['ExtendedAttributes']['sponsor2_address'],
                                        null,
                                        null,
                                        $params['ExtendedAttributes']['sponsor2_city'],
                                        $params['ExtendedAttributes']['sponsor2_state'],
                                        $params['ExtendedAttributes']['sponsor2_country'],
                                        $params['ExtendedAttributes']['sponsor2_zip'],
                                        $countrycode,
                                        _plugin_Directi_validatePhone($params['ExtendedAttributes']['sponsor2_telephone'],$countrycode),
                                        null,
                                        null,
                                        $custID
                                        );
                    $GLOBALS['logger']->log(5, 'addSponsor('.print_r($return,true).')');
                    $sponsor2 = print_r($return, true);
               }
               $contactDetailsHash = array('sponsor1' => $sponsor1, 'sponsor2' => $sponsor2);
            } */

            $DomContactExt = new DomContactExt(dirname(__FILE__).'/lib/wsdl/'.$demo.'DomContactExt.wsdl');
            $return = $DomContactExt->setContactDetails(
                                        $params['Login'],
                                        $params['Password'],
                                        $params['Role'],
                                        $params['Language'],
                                        $params['Parent ID'],
                                        $contactID,
                                        $contactDetailsHash,
                                        $productKey
                                        );
           $this->logger->log(5, 'setContactDetails('.print_r($return,true).')');
        }

        // Create a new domain order object
        $DomOrder = new DomOrder(dirname(__FILE__).'/lib/wsdl/'.$demo.'DomOrder.wsdl');
        // This function doesn't seem to work anymore :S
        /*$return = $DomOrder->validateDomainRegistrationParams(
                                        $params['Login'],
                                        $params['Password'],
                                        $params['Role'],
                                        $params['Language'],
                                        $params['Parent ID'],
                                        array($domain => $params['NumYears']),
                                        $nameservers,
                                        $contactID,
                                        $contactID,
                                        $contactID,
                                        $contactID,
                                        $custID,
                                        "NoInvoice"
                                        );
        $this->logger->log(5, 'validateDomainRegistrationParams('.print_r($return,true).')');
        if ($return[$domain]['status'] != 'Success') {
            return array(-1, array("Failed validating domain parameters: ".$return[$domain]['error']));
        }
        */
        $return = $DomOrder->addWithoutValidation(
                                        $params['Login'],
                                        $params['Password'],
                                        $params['Role'],
                                        $params['Language'],
                                        $params['Parent ID'],
                                        array($domain => $params['NumYears']),
                                        $nameservers,
                                        $contactID,
                                        $contactID,
                                        $contactID,
                                        $contactID,
                                        $custID,
                                        "NoInvoice"
                                        );
        $this->logger->log(5, 'addWithoutValidation('.print_r($return,true).')');

        // Let's do some error checking to see what happened
        if (@$return[$domain]['status'] == 'error') {
            if ( $return[$domain]['error'] == 'Domain '.$domain.' already registered') {
                return array(0);
            } else {
                return array(-1, array('Error registering domain: ' . $return[$domain]['error']));
            }
        } elseif (isset($return['faultcode'])) {
            $this->logger->log(5, 'Directi Fault Code: '.$return['faultstring']);
            if (strpos($return['faultstring'],"Password should be between 6 to 15 characters.")) return array(-1,array("Domain password should be between 6 to 15 characters."));
            elseif (strpos($return['faultstring'],"Invalid Password/Username")) return array(-1,array("Invalid Plugin Username/Password or Directi account suspended"));
            elseif (strpos($return['faultstring'],"We no longer sell/renew/transfer this TLD")) return array(-1,array("We no longer sell/renew/transfer this TLD"));
            else return array(-1,array("Fault Error: Please look over domain and plugin information"));
        } elseif (@$return[$domain]['actionstatus'] === 'Success') {
            return array(1,array($return[$domain]['entityid']));
        } else {
            $this->logger->log(5, 'Directi Result: [error]=>'.$return[$domain]['error'].' [faultstring]=>'.$return['faultstring']);
            return array(-1,array($return[$domain]['error']));
        }
    }

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

    function _validatePhone($phone, $code)
    {
        // strip all non numerical values
        $phone = preg_replace('/[^\d]/', '', $phone);
        // check if code is already there and delete it
        return preg_replace("/^($code)(\\d+)/", '\2', $phone);
    }
    
    function disableRenewal($params)
    {
    }
    
    
    function getContactInformation($params)
    {
        require_once dirname(__FILE__).'/lib/DomOrder.class.php';
        
        $params['sld'] = strtolower($params['sld']);
        $params['tld'] = strtolower($params['tld']);
        $domain = $params['sld'].".".$params['tld'];
        if ($params['Use testing server']) {
            $demo = "demo";
        } else {
            $demo = "";
        }

        $DomOrder = new DomOrder(dirname(__FILE__).'/lib/wsdl/'.$demo.'DomOrder.wsdl');
        
        $ret = $DomOrder->getDetailsByDomain(
			                                 $params['Login'],
                                             $params['Password'],
                                             $params['Role'],
                                             $params['Language'],
                                             $params['Parent ID'],
                                             $domain,
                                             array('RegistrantContactDetails')); //, 'AdminContactDetails', 'TechContactDetails', 'BillingContactDetails'));
        
        $this->logger->log(5, 'Directi Returned: '.print_r($ret, true));
                                                    
        if (!is_array($ret)) return new NE_Error('Error contacting Directi', 131);
        
        if (isset($ret['faultstring']) && $ret['faultstring'] != '') {
            $errors = explode('#~#', $ret['faultstring']);
            if (isset($errors[2])) {
                $error = $errors[2];
            } else {
                $error = $ret['faultstring'];
            }
            return new NE_Error($error, 1001);
        }
        
        $name = split(' ', $ret['registrantcontact']['name'], 2);
        
        $info = array();
        // some info might not be available when the privacy protection is enabled for the domain
        $info['Registrant']['OrganizationName']  = array($this->user->lang('Organization'), $ret['registrantcontact']['company']);
        $info['Registrant']['FirstName'] = array($this->user->lang('First Name'), $name[0]);
        $info['Registrant']['LastName'] = array($this->user->lang('Last Name'), isset($name[1])? $name[1] : '');
        $info['Registrant']['Address1']  = array($this->user->lang('Address').' 1', $ret['registrantcontact']['address1']);
        $info['Registrant']['Address2']  = array($this->user->lang('Address').' 2', isset($ret['registrantcontact']['address2'])? $ret['registrantcontact']['address2'] : '');
        $info['Registrant']['Address3']  = array($this->user->lang('Address').' 3', isset($ret['registrantcontact']['address3'])? $ret['registrantcontact']['address3'] : '');
        $info['Registrant']['City']      = array($this->user->lang('City'), $ret['registrantcontact']['city']);
        $info['Registrant']['StateProv']  = array($this->user->lang('Province').'/'.$this->user->lang('State'), isset($ret['registrantcontact']['state'])? $ret['registrantcontact']['state'] : '');
        $info['Registrant']['Country']   = array($this->user->lang('Country'), $ret['registrantcontact']['country']);
        $info['Registrant']['PostalCode']  = array($this->user->lang('Postal Code').'/'.$this->user->lang('Zip'), $ret['registrantcontact']['zip']);
        $info['Registrant']['EmailAddress']     = array($this->user->lang('E-mail'), $ret['registrantcontact']['emailaddr']);
        $info['Registrant']['Phone']  = array($this->user->lang('Phone Country Code'), $ret['registrantcontact']['telnocc'].$ret['registrantcontact']['telno']);
        
        return $info;
        
    }
    
    function setContactInformation($params)
    {
        require_once dirname(__FILE__).'/lib/DomOrder.class.php';
        require_once dirname(__FILE__).'/lib/DomContact.class.php';
        
        $params['sld'] = strtolower($params['sld']);
        $params['tld'] = strtolower($params['tld']);
        $domain = $params['sld'].".".$params['tld'];
        if ($params['Use testing server']) {
            $demo = "demo";
        } else {
            $demo = "";
        }

        $DomOrder = new DomOrder(dirname(__FILE__).'/lib/wsdl/'.$demo.'DomOrder.wsdl');
        
        $ret = $DomOrder->getDetailsByDomain(
			                                 $params['Login'],
                                             $params['Password'],
                                             $params['Role'],
                                             $params['Language'],
                                             $params['Parent ID'],
                                             $domain,
                                             array('RegistrantContactDetails')); //, 'AdminContactDetails', 'TechContactDetails', 'BillingContactDetails'));
        if (!is_array($ret)) return new NE_Error('Error contacting Directi', 131);
        
        if (isset($ret['faultstring']) && $ret['faultstring'] != '') {
            $errors = explode('#~#', $ret['faultstring']);
            if (isset($errors[2])) {
                $error = $errors[2];
            } else {
                $error = $ret['faultstring'];
            }
            return new NE_Error($error, 1001);
        }
        
        $DomContact = new DomContact(dirname(__FILE__).'/lib/wsdl/'.$demo.'DomContact.wsdl');
        
        $cc = $this->getCountryCode($params['Registrant_Country']);
        $phone = $this->_validatePhone($params['Registrant_Phone'], $cc);
        
        
        $ret2 = $DomContact->mod(
                            $params['Login'],
                            $params['Password'],
                            $params['Role'],
                            $params['Language'],
                            $params['Parent ID'],
                            $ret['registrantcontact']['contactid'],
                            $params['Registrant_FirstName']. ' '. $params['Registrant_LastName'],
                            $params['Registrant_OrganizationName'],
                            $params['Registrant_EmailAddress'],
                            $params['Registrant_Address1'],
                            $params['Registrant_Address2'],
                            $params['Registrant_Address3'],
                            $params['Registrant_City'],
                            $params['Registrant_StateProv'],
                            $params['Registrant_Country'],
                            $params['Registrant_PostalCode'],
                            $cc,
                            $phone,
                            '',
                            ''
                            );
        $this->logger->log(5, 'Ret2: '.print_r($ret2, true));

        if (!is_array($ret2)) return new NE_Error('Error contacting Directi', 131);
        
        if (isset($ret2['faultstring']) && $ret2['faultstring'] != '') {
            $errors = explode('#~#', $ret2['faultstring']);
            if (isset($errors[2])) {
                $error = $errors[2];
            } else {
                $error = $ret2['faultstring'];
            }
            return new NE_Error($error, 1001);
        }
        
        return $ret2['actionstatusdesc'];
        
        
    }
    
    function getNameServers($params)
    {
        require_once dirname(__FILE__).'/lib/DomOrder.class.php';
        
        $params['sld'] = strtolower($params['sld']);
        $params['tld'] = strtolower($params['tld']);
        $domain = $params['sld'].".".$params['tld'];
        if ($params['Use testing server']) {
            $demo = "demo";
        } else {
            $demo = "";
        }

        $DomOrder = new DomOrder(dirname(__FILE__).'/lib/wsdl/'.$demo.'DomOrder.wsdl');
        
        $ret = $DomOrder->getDetailsByDomain(
			                                 $params['Login'],
                                             $params['Password'],
                                             $params['Role'],
                                             $params['Language'],
                                             $params['Parent ID'],
                                             $domain,
                                             array('NsDetails'));
                                             
        $i = 1;
        $ns = array();
        $ns['hasDefault'] = 0;
        while (isset($ret['ns'.$i])) {
            $ns[] = $ret['ns'.$i];
            $i++;
        }
        return $ns;
    }
    
    function setNameServers($params)
    {
        require_once dirname(__FILE__).'/lib/DomOrder.class.php';
        
        $params['sld'] = strtolower($params['sld']);
        $params['tld'] = strtolower($params['tld']);
        $domain = $params['sld'].".".$params['tld'];
        if ($params['Use testing server']) {
            $demo = "demo";
        } else {
            $demo = "";
        }

        $DomOrder = new DomOrder(dirname(__FILE__).'/lib/wsdl/'.$demo.'DomOrder.wsdl');
        
        $ret = $DomOrder->getDetailsByDomain(
			                                 $params['Login'],
                                             $params['Password'],
                                             $params['Role'],
                                             $params['Language'],
                                             $params['Parent ID'],
                                             $domain,
                                             array('OrderDetails'));
        
        if (!isset($ret['orderid']) || isset($ret['faultstring']) && $ret['faultstring'] != '') {
            $errors = explode('#~#', $ret['faultstring']);
            if (isset($errors[2])) {
                $error = $errors[2];
            } else {
                $error = $ret['faultstring'];
            }
            return new NE_Error($error, 1001);
        }
        
        $orderId = $ret['orderid'];
        
        $ns = array();
        foreach ($params['ns'] as $key => $value) {
            $ns['ns'.$key] = $value;
        }
        
        
        
        $ret = $DomOrder->modifyNameServer(
                                             $params['Login'],
                                             $params['Password'],
                                             $params['Role'],
                                             $params['Language'],
                                             $params['Parent ID'],
                                             $orderId,
                                             $ns);
        if (!is_array($ret)) return new NE_Error('Error contacting Directi', 131);
        if (isset($ret['faultstring']) && $ret['faultstring'] != '') {
            $errors = explode('#~#', $ret['faultstring']);
            if (isset($errors[2])) {
                $error = $errors[2];
            } else {
                $error = $ret['faultstring'];
            }
            return new NE_Error($error, 1001);
        }
    }
    
    function checkNSStatus($params)
    {
        // seems to always return false
        return new NE_Error("this is not supported", 1000);
        
        /*require_once dirname(__FILE__).'/lib/DomOrder.class.php';
        
        $params['sld'] = strtolower($params['sld']);
        $params['tld'] = strtolower($params['tld']);
        $domain = $params['sld'].".".$params['tld'];
        if ($params['Use testing server']) {
            $demo = "demo";
        } else {
            $demo = "";
        }

        $DomOrder = new DomOrder(dirname(__FILE__).'/lib/wsdl/'.$demo.'DomOrder.wsdl');
        
        $ret = $DomOrder->checkNameServer(
			                                 $params['Login'],
                                             $params['Password'],
                                             $params['Role'],
                                             $params['Language'],
                                             $params['Parent ID'],
                                             array($params['check_ns']),
                                             array('domcno'));
        if (!is_array($ret)) return new NE_Error('Error contacting Directi', 131);
        $this->logger->log(5, 'checkNSStatus: '.print_r($ret, true));
        if (isset($ret['faultstring']) && $ret['faultstring'] != '') {
            $errors = explode('#~#', $ret['faultstring']);
            if (isset($errors[2])) {
                $error = $errors[2];
            } else {
                $error = $ret['faultstring'];
            }
            return new NE_Error($error, 1001);
        }
        NE_Lib::printR($ret, true);
        */
    }
    
    function registerNS($params)
    {
        require_once dirname(__FILE__).'/lib/DomOrder.class.php';
        
        $params['sld'] = strtolower($params['sld']);
        $params['tld'] = strtolower($params['tld']);
        $domain = $params['sld'].".".$params['tld'];
        if ($params['Use testing server']) {
            $demo = "demo";
        } else {
            $demo = "";
        }

        $DomOrder = new DomOrder(dirname(__FILE__).'/lib/wsdl/'.$demo.'DomOrder.wsdl');
        
        $ret = $DomOrder->getDetailsByDomain(
			                                 $params['Login'],
                                             $params['Password'],
                                             $params['Role'],
                                             $params['Language'],
                                             $params['Parent ID'],
                                             $domain,
                                             array('OrderDetails'));

        if (!is_array($ret)) return new NE_Error('Error contacting Directi', 131);
        
        if (!isset($ret['orderid']) || isset($ret['faultstring']) && $ret['faultstring'] != '') {
            $errors = explode('#~#', $ret['faultstring']);
            if (isset($errors[2])) {
                $error = $errors[2];
            } else {
                $error = $ret['faultstring'];
            }
            return new NE_Error($error, 1001);
        }
        
        $orderId = $ret['orderid'];
        
        $ret = $DomOrder->addChildNameServer(
                                             $params['Login'],
                                             $params['Password'],
                                             $params['Role'],
                                             $params['Language'],
                                             $params['Parent ID'],
                                             $orderId,
                                             $params['nsname'],
                                             array($params['nsip']));
                                             
        if (!is_array($ret)) return new NE_Error('Error contacting Directi', 131);
        
        if (isset($ret['faultstring']) && $ret['faultstring'] != '') {
            $errors = explode('#~#', $ret['faultstring']);
            if (isset($errors[2])) {
                $error = $errors[2];
            } else {
                $error = $ret['faultstring'];
            }
            return new NE_Error($error, 1001);
        }
        
        if (isset($ret['actionstatus']) && $ret['actionstatus'] == 'Failed') {
            return new NE_Error($ret['actionstatus'].': '.$ret['actionstatusdesc'], 1002);
        }
        
        return $ret['actionstatus'].': '.$ret['actiontypedesc'];
    }
    
    function editNS($params)
    {
        require_once dirname(__FILE__).'/lib/DomOrder.class.php';
        
        $params['sld'] = strtolower($params['sld']);
        $params['tld'] = strtolower($params['tld']);
        $domain = $params['sld'].".".$params['tld'];
        if ($params['Use testing server']) {
            $demo = "demo";
        } else {
            $demo = "";
        }

        $DomOrder = new DomOrder(dirname(__FILE__).'/lib/wsdl/'.$demo.'DomOrder.wsdl');
        
        $ret = $DomOrder->getDetailsByDomain(
			                                 $params['Login'],
                                             $params['Password'],
                                             $params['Role'],
                                             $params['Language'],
                                             $params['Parent ID'],
                                             $domain,
                                             array('OrderDetails'));

        if (!is_array($ret)) return new NE_Error('Error contacting Directi', 131);
        
        if (!isset($ret['orderid']) || isset($ret['faultstring']) && $ret['faultstring'] != '') {
            $errors = explode('#~#', $ret['faultstring']);
            if (isset($errors[2])) {
                $error = $errors[2];
            } else {
                $error = $ret['faultstring'];
            }
            return new NE_Error($error, 1001);
        }
        
        $orderId = $ret['orderid'];
        
        $ret = $DomOrder->modifyChildNameServerIp(
                                             $params['Login'],
                                             $params['Password'],
                                             $params['Role'],
                                             $params['Language'],
                                             $params['Parent ID'],
                                             $orderId,
                                             $params['nsname'],
                                             $params['nsoldip'],
                                             $params['nsnewip']);
                                             
        if (!is_array($ret)) return new NE_Error('Error contacting Directi', 131);
        
        if (isset($ret['faultstring']) && $ret['faultstring'] != '') {
            $errors = explode('#~#', $ret['faultstring']);
            if (isset($errors[2])) {
                $error = $errors[2];
            } else {
                $error = $ret['faultstring'];
            }
            return new NE_Error($error, 1001);
        }
        
        return $this->user->lang('Name Server edited successfully.');
    }
    
    function deleteNS($params)
    {
        return new NE_Error("this is not supported", 1000);
    }
    
    function getGeneralInfo($params)
    {
        require_once dirname(__FILE__).'/lib/DomOrder.class.php';
        
        $params['sld'] = strtolower($params['sld']);
        $params['tld'] = strtolower($params['tld']);
        $domain = $params['sld'].".".$params['tld'];
        if ($params['Use testing server']) {
            $demo = "demo";
        } else {
            $demo = "";
        }

        $DomOrder = new DomOrder(dirname(__FILE__).'/lib/wsdl/'.$demo.'DomOrder.wsdl');
        
        $ret = $DomOrder->getDetailsByDomain(
			                                 $params['Login'],
                                             $params['Password'],
                                             $params['Role'],
                                             $params['Language'],
                                             $params['Parent ID'],
                                             $domain,
                                             array('OrderDetails', 'StatusDetails', 'DomainStatus'));
        
        $this->logger->log(5, 'Directi Result: '.print_r($ret, true));                                     
        if (!is_array($ret)) return new NE_Error('Error contacting Directi', 131);
        
        if (isset($ret['faultstring']) && $ret['faultstring'] != '') {
            $errors = explode('#~#', $ret['faultstring']);
            if (isset($errors[2])) {
                $error = $errors[2];
            } else {
                $error = $ret['faultstring'];
            }
            return new NE_Error($error, 1001);
        }
        
        $data = array();
        $data['expiration'] = date('m/d/Y', $ret['endtime']);
        $data['domain'] = $ret['domainname'];
        $data['id'] = $ret['orderid'];
        $data['registrationstatus'] = $ret['currentstatus'];
        $data['purchasestatus'] = isset($ret['domainstatus'][0])? $ret['domainstatus'][0] : $this->user->lang('Unknown');
        $data['autorenew'] = $ret['isOrderSuspendedUponExpiry'] == 'false'? false : true;
        
        return $data;
    }
    
    function fetchDomains($params)
    {
        require_once dirname(__FILE__).'/lib/DomOrder.class.php';
        
        if ($params['Use testing server']) {
            $demo = "demo";
        } else {
            $demo = "";
        }

        $DomOrder = new DomOrder(dirname(__FILE__).'/lib/wsdl/'.$demo.'DomOrder.wsdl');
        
        $ret = $DomOrder->listOrder(
			                                 $params['Login'],
                                             $params['Password'],
                                             $params['Role'],
                                             $params['Language'],
                                             $params['Parent ID'],
                                             null,
                                             null,
                                             null,
                                             false,
                                             null,
                                             array("Active"), // hide 'Deleted', "Suspended", "InActive", "Pending Delete Restorable"
                                             null,
                                             null,
                                             null,
                                             null,
                                             null,
                                             null,
                                             null,
                                             null,
                                             25,
                                             $params['page'],
                                             array('entity.description asc'));
                                             
        $this->logger->log(5, 'Directi Returned: '.print_r($ret, true));
                                             
        if (!is_array($ret)) return new NE_Error('Error contacting Directi', 131);
        
        if (isset($ret['faultstring']) && $ret['faultstring'] != '') {
            $errors = explode('#~#', $ret['faultstring']);
            if (isset($errors[2])) {
                $error = $errors[2];
            } else {
                $error = $ret['faultstring'];
            }
            return new NE_Error($error, 1001);
        }
        
        $domainsList = array();
        require_once 'modules/domains/models/DomainName.php';
        for ($i = 1; $i <= $ret['recsonpage']; $i++) {
            $dom = DomainName::splitDomain($ret[$i]['entity.description']);
            $data['id'] = $ret[$i]['orders.orderid']; 
            $data['sld'] = $dom[0]; 
            $data['tld'] = $dom[1];
            $data['exp'] = date('m/d/Y', $ret[$i]['orders.endtime']);
            $domainsList[] = $data;
        }
        $metaData = array();
        $metaData['total'] = $ret['recsindb'];
        $metaData['start'] = 1 + ($params['page'] - 1) * 25;
        $metaData['end'] = ($params['page']) * 25;
        $metaData['numPerPage'] = 25;
        return array($domainsList, $metaData);
    }
    
    function setAutorenew($params)
    {
        return new NE_Error("This function is not supported", 1000);
    }
    
    function getRegistrarLock($params)
    {
        return new NE_Error("This function is not supported", 1000);
    }
    
    function setRegistrarLock($params)
    {
        return new NE_Error("This function is not supported", 1000);
    }
    
    function sendTransferKey($params)
    {
        return new NE_Error("This function is not supported", 1000);
    }
    
    function getDNS($params)
    {
        return new NE_Error("This function is not supported", 1000);
    }
    
    function setDNS($params)
    {
        return true;
    }

    function hasPrivacyProtection($contactInfo)
    {
        return ($contactInfo['OrganizationName'][1] == 'PrivacyProtect.org');
    }
}

?>
