<?php

require_once dirname(__FILE__).'/../../../classes/error_ce.php';
require_once dirname(__FILE__).'/../../../classes/observable.php';
require_once dirname(__FILE__).'/lib/apiutil.php';


function plugin_directi_variables()
{
    $variables = array(
       'Plugin Name' => array (
            'type'          => 'hidden',
            'description'   => 'How CE sees this plugin (not to be confused with the Signup Name)',
            'value'         => 'Directi',
         ),
        'Use Directi to check and register domains' => array(
            'type'          => 'yesno',
            'description'  => "If you don't use any registrar, the domain check is done with whois.",
            'value'         => 0,
        ),
        'Use testing server' => array(
            'type'          => 'yesno',
            'description'   => '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.',
            'value'         => 0,
        ),
        'Login' => array(
            'type'          => 'text',
            'description'   => 'Enter your username for your Directi reseller account.',
        ),
        'Password'  => array(
            'type'          => 'password',
            'description'   => 'Enter the password for your Directi reseller account.',
        ),
        'Role'  => array(
            'type'          => 'hidden',
            'description'   => 'Type of account.',
            'value'         => 'reseller',
        ),
        'Language'  => array(
            'type'          => 'hidden',
            'description'   => 'Language preference.',
            'value'         => 'en',
        ),
        'Parent ID'  => array(
            'type'          => 'text',
            'description'   => 'This can be found in your Directi profile.',
            'value'         => '',
        ),
    );

    return $variables;
}


// returns array(code [,message]), where code is:
// 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 lookup domain
function plugin_directi_check_domain($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
			                 );
    $GLOBALS['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 {
        $GLOBALS['logger']->log(5, 'Directi Result: [status]=>'.$return[$domain]['status'].' [error]=>'.$return[$domain]['error']);
        return array(5);
    }
}


// possible return values: array(code [,message])
// -1:  error trying to purchase domain
// 0:   domain not available
// >0:  Operation successfull, returns orderid
function plugin_directi_register_domain($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 = _plugin_Directi_getCountryCode($params['RegistrantCountry']);
    $telno = _plugin_Directi_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'
        			             );
    $GLOBALS['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']);
            $GLOBALS['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
    			                 );
    $GLOBALS['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
        			             );
        $GLOBALS['logger']->log(5, '$domContact->add('.print_r($return,true).')');
        $return = $DomContact->addDefaultContact(
                                       $params['Login'],
                                       $params['Password'],
                                       $params['Role'],
                                       $params['Language'],
                                       $params['Parent ID'],
                                       $custID
                                       );
        $GLOBALS['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
                                    );
       $GLOBALS['logger']->log(5, 'setContactDetails('.print_r($return,true).')');
    }

    // Create a new domain order object
    $DomOrder = new DomOrder(dirname(__FILE__).'/lib/wsdl/'.$demo.'DomOrder.wsdl');
    /*$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"
                                    );
    $GLOBALS['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"
                                    );
    $GLOBALS['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'])) {
        $GLOBALS['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 {
        $GLOBALS['logger']->log(5, 'Directi Result: [error]=>'.$return[$domain]['error'].' [faultstring]=>'.$return['faultstring']);
        return array(-1,array($return[$domain]['error']));
    }
}

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

function _plugin_directi_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);
}

?>
