<?php

/**
 * Basic example of authentication against the BroadSoft OCI-P SOAP interface.
 *
 * The NuSOAP toolkit can be obtained from: http://sourceforge.net/projects/nusoap/
 */
require_once('nusoap.php');

// Fixed parameters
$endpoint 'http://ews.xdp.broadsoft.com/webservice/services/ProvisioningService';
$session  time();
$userId   'user@xdp.broadsoft.com';
$password 'welcome1';

// Stage 1: the AuthenticationRequest
$sAuthenticationRequest = <<<EOF
<BroadsoftDocument protocol = "OCI" xmlns="C" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<sessionId xmlns="">$session</sessionId>
<command xsi:type="AuthenticationRequest" xmlns="">
<userId>$userId</userId>
</command>
</BroadsoftDocument>
EOF;

// Stage 2: the LoginRequest
$sLoginRequest = <<<EOF
<BroadsoftDocument protocol = "OCI" xmlns="C" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<sessionId xmlns="">$session</sessionId>
<command xsi:type="LoginRequest14sp4" xmlns="">
<userId>$userId</userId>
<signedPassword>%s</signedPassword>
</command>
</BroadsoftDocument>
EOF;

$client = new nusoap_client($endpoint);

// First stage: post an authentication request
$result $client->call('processOCIMessage', array('arg0' => $sAuthenticationRequest));

// Validate the response
if ($client->fault) {
    print 
htmlentities($result);
    die(
"<p><b>Exiting because of the above error</b></p>");
}

// Get the nonce from the response
if (!preg_match('|<nonce>(\d+)|'$result$m)) {
    die(
"Cannot find nonce in response");
}

// Generate the encrypted password
$encryptedPassword md5("$m[1]:".sha1($password));

// Second stage: set the content for the LoginRequest call, execute, and print the response
$result $client->call('processOCIMessage', array('arg0' => sprintf($sLoginRequest$encryptedPassword)));
print 
htmlentities($result);

?>