WSF/PHP Samples
Basic functionalities
Echo service, accepts a payload and returns the same. Two way (in-out) sample.
Run client | WSDL | show client code | show server code

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

$requestPayloadString = <<<XML
<ns1:echoString xmlns:ns1="http://wso2.org/wsfphp/samples"><text>Hello World!</text></ns1:echoString>
XML;

try {

    $client = new WSClient(array( "to" => "http://localhost/samples/echo_service.php" ));
                
    $responseMessage = $client->request( $requestPayloadString );
    
    printf("Response = %s <br>", htmlspecialchars($responseMessage->str));

} catch (Exception $e) {

    if ($e instanceof WSFault) {
        printf("Soap Fault: %s\n", $e->Reason);
    } else {
        printf("Message = %s\n",$e->getMessage());
    }

}
?>



<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* sample test payload */
$requestPayloadString = <<<XML
<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
   <soapenv:Header/>
   <soapenv:Body>
     <ns1:echoString xmlns:ns1="http://wso2.org/wsfphp/samples">
         <text>Hello World!</text>
     </ns1:echoString>
    </soapenv:Body>
</soapenv:Envelope>
XML;

function echoFunction($inMessage) {

    $outMessage = new WSMessage($inMessage->str);

    return $outMessage;
}

$operations = array("echoString" => "echoFunction");

$service = new WSService(array("operations" => $operations));
        
$service->reply($requestPayloadString);

?>


Echo service with WS-Addressing.
Run client | WSDL | show client code | show server code

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

$requestPayloadString = <<<XML
<ns1:echo xmlns:ns1="http://wso2.org/wsfphp/samples"><text>Hello World!</text></ns1:echo>
XML;

try {

    $reqMessage = new WSMessage($requestPayloadString,
        array( "to" => "http://localhost/samples/echo_service_addr.php",
               "action" => "http://wso2.org/wsfphp/samples/echoString"));
              
    $client = new WSClient(array("useWSA" => TRUE));
                
    $responseMessage = $client->request($reqMessage);
    
    printf("Response = %s \n", htmlspecialchars($responseMessage->str));

} catch (Exception $e) {

    if ($e instanceof WSFault) {
        printf("Soap Fault : %s\n", $e->Reason);
    } else {
        printf("Message = %s\n",$e->getMessage());
    }

}
?>



<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function echoFunction($inMessage) {

    $returnMessage = new WSMessage($inMessage->str);

    return $returnMessage;
}

$operations = array("echoString" => "echoFunction");
$actions = array("http://wso2.org/wsfphp/samples/echoString" => "echoString");

$service = new WSService(array( "operations" => $operations, 
                                "actions" => $actions));
        
$service->reply();

?>


Client for echo service using SOAP 1.1 protocol
Run client (show code)

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

$requestPayloadString = <<<XML
<ns1:echoString xmlns:ns1="http://wso2.org/wsfphp/samples"><text>Hello World!</text></ns1:echoString>
XML;

try {

    $client = new WSClient(array("to"=>"http://localhost/samples/echo_service.php",
                                 "useSOAP"=>1.1, 
                                 "action"=>"http://localhost/samples/echo_service.php/echoString"));

    $responseMessage = $client->request($requestPayloadString);
    
    printf("Response = %s <br>", htmlspecialchars($responseMessage->str));

} catch (Exception $e) {

    if ($e instanceof WSFault) {
        printf("Soap Fault: %s\n", $e->Reason);
    } else {
        printf("Message = %s\n",$e->getMessage());
    }

}
?>


Echo sample showing how to use the same client object instance to do repeated calls
Run client (show code)

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

$requestPayloadStrings = array();

for ($i = 0 ; $i < 10; $i++) {
$tmp = "Hello World "."$i";
$requestPayloadString = <<<XML
<ns1:echoString xmlns:ns1="http://ws.apache.org/axis2/c/samples">
   <text>$tmp</text>
</ns1:echoString>
XML;
array_push($requestPayloadStrings,$requestPayloadString);
}

try
{
    $serviceClient = new WSClient();

    for($i = 0 ; $i < 10; $i++) {
        $msg = new WSMessage($requestPayloadStrings[$i],
                             array( "to" => "http://localhost/samples/echo_service.php"));
        $responsePayload = $serviceClient->request($msg);
        printf("Round %s<br>",$i);
        printf("--------<br>");
        printf("Response = %s <br><br>", htmlspecialchars($responsePayload->str));

        printf("Last Request = %s<br><br>",htmlspecialchars($serviceClient->getLastRequest()));
        printf("Last Response = %s<br><br>",htmlspecialchars($serviceClient->getLastResponse()));
    }

} catch (Exception $e) {
   if ($e instanceof WSFault) {
       printf("Soap Fault : %s<br>", $e->Reason());
   } else {
       printf("Fault Message = %s<br>",$e->getMessage());
   }
}
?>


Notify service, accepts a payload, but does not reply. One way (in-only) sample.
Run client | WSDL | show client code | show server code

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

$requestPayloadString = <<<XML
<ns1:notifyString xmlns:ns1="http://wso2.org/wsfphp/samples"><text>Hello World!</text></ns1:notifyString>
XML;

try {

    $client = new WSClient(
        array( "to" => "http://localhost/samples/notify_service.php"));
                
    $client->send($requestPayloadString);
    
    printf("Request sent to endpoint\n");
    
} catch (Exception $e) {

    if ($e instanceof WSFault) {
        printf("Soap Fault: %s\n", $e->Reason);
    } else {
        printf("Message = %s\n",$e->getMessage());
    }

}
?>



<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function notifyFunction($inMessage) {

    return;
}

$operations = array("notifyString" => "notifyFunction");

$service = new WSService(array("operations" => $operations));
        
$service->reply();

?>


Client that receives a soap fault
Run client | WSDL | show client code | show server code

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function sendFault($inMessage) {
    throw new WSFault("Sender", "Testing WSFault");
}

$operations = array("getFault" => "sendFault");

$service = new WSService(array("operations" => $operations));
        
$service->reply();

?>



<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

$requestPayloadString = <<<XML
<ns1:getFault xmlns:ns1="http://wso2.org/wsfphp/samples"><text>Hello World!</text></ns1:getFault>
XML;

try {

    $client = new WSClient( array( "to" => "http://localhost/samples/fault_service.php" ));

                
    $responseMessage = $client->request($requestPayloadString);
    
} catch (Exception $e) {

    if ($e instanceof WSFault) {
        printf("Soap Fault Reason: %s\n", $e->Reason);
        printf("Soap Fault Code: %s \n", $e->Code);

    } else {
        printf("Message = %s\n",$e->getMessage());
    }
}
?>


Math service for add, sub, mul and div operations.(In math directory)
WSDL (show code)

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* sample test payload */
$reqPayloadString = <<<XML
<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
   <soapenv:Header/>
   <soapenv:Body>
      <ns1:add xmlns:ns1="http://ws.apache.org/axis2/services/math">
         <param1>40</param1>
         <param2>8</param2>
      </ns1:add>
   </soapenv:Body>
</soapenv:Envelope>
XML;

function addFunction($inMessage) {

    
    $simplexml = new SimpleXMLElement($inMessage->str);
    $value1 = $simplexml->param1[0];
    $value2 = $simplexml->param2[0];
    $Result = $value1 + $value2;    
     $resPayload = <<<XML
<ns1:result xmlns:ns1="http://ws.axis2.org/axis2/php/math">$Result</ns1:result>
XML;
    $returnMessage = new WSMessage($resPayload);

    return $returnMessage;
}


function subFunction($inMessage) {

    $simplexml = new SimpleXMLElement($inMessage->str);
    $value1 = $simplexml->param1[0];
    $value2 = $simplexml->param2[0];
    $Result = $value1 - $value2;    
    $resPayload = <<<XML
<ns1:result xmlns:ns1="http://ws.axis2.org/axis2/php/math">$Result</ns1:result>
XML;

    $returnMessage = new WSMessage($resPayload);

    return $returnMessage;


}


function mulFunction($inMessage) {
    
    $simplexml = new SimpleXMLElement($inMessage->str);
    $value1 = $simplexml->param1[0];
    $value2 = $simplexml->param2[0];
    $Result = $value1 * $value2;    
    $resPayload = <<<XML
<ns1:result xmlns:ns1="http://ws.axis2.org/axis2/php/math">$Result</ns1:result>
XML;

    $returnMessage = new WSMessage($resPayload);

    return $returnMessage;
}



function divFunction($inMessage) {

    $simplexml = new SimpleXMLElement($inMessage->str);
    $value1 = $simplexml->param1[0];
    $value2 = $simplexml->param2[0];
    $Result = $value1 / $value2;    
    $resPayload = <<<XML
<ns1:result xmlns:ns1="http://ws.axis2.org/axis2/php/math">$Result</ns1:result>
XML;

    $returnMessage = new WSMessage($resPayload);

    return $returnMessage;
}


$operations = array("add" => "addFunction",
                    "sub" => "subFunction",
                    "mul" => "mulFunction",
                    "div" => "divFunction");

$svr = new WSService(array("operations" => $operations));
        
$svr->reply($reqPayloadString);

?>


Client with GUI for math service.Send the request and accept the reply from math service.(In math directory)
Run client (show code)

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
$getResult = $_POST["getResult"];
$operation = $_POST["operation"];
$epr = $_POST["epr"];
$param1 = $_POST["param1"];
$param2 = $_POST["param2"];
		    
?>

<html>
<head>
<title> Math Sample </title>
</head>
<body>
<form method="post" action="<?php echo $PHP_SELF;?>">
<table cols="2" border="1" cellpadding="10" cellspacing="0" align="center" width="100%">
<tr>
<td>
<h4>Operations</h4>

Add : <input type="radio" value="add" name="operation" checked>

Subtract: <input type="radio" value="sub" name="operation">

Multiply: <input type="radio" value="mul" name="operation">

Divide: <input type="radio" value="div" name="operation">
<br/><br/>
<h4>Target Endpoint</h4>
Endpoint:<input type="text" size="60" maxlength="60" name="epr" 
          value="http://localhost/samples/math_service.php"><br />

<h4>Parameters</h4>
Parameter 1:<input type="text" size="6" maxlength="10" name="param1" value="10">
Parameter 2:<input type="text" size="6" maxlength="10" name="param2" value="20"><br/>
<br/>

<input type="submit" value="submit" name="getResult">
<input type="submit" value="Reset" name="reset">






</td>
</tr>
</table>

</form>
<?php
if (isset($_POST['getResult']))
{
      if (isset($_GET['param1']) && isset($_GET['param2']))
      {
	$epr = $_GET['epr'];
	$param1 = $_GET['param1'];
	$param2 = $_GET['param2'];
	$operation  = $_GET['operation'];
      }
    
     
if (isset($param1) &&  isset($param2))
    {
      /*
      echo $operation;
      echo $param1;
      echo $param2;
      */

$reqPayloadString = <<<XML
<ns1:$operation xmlns:ns1="http://ws.apache.org/axis2/php/math">
     <param1>$param1</param1>
      <param2>$param2</param2>
</ns1:$operation>
XML;

     try
       {
	    $client = new WSClient(array(
				      "to"=>$epr));
	    $response = $client->request($reqPayloadString);
	 
	    if ($response)
	    {
	         echo "Result : ".$response->str."";
	    }
       } 
  
     catch (Exception $e)
       {
	    if ($e instanceof WSFault)
	    {
	     printf("Soap Fault: %s\n", $e->Reason);
	    }
	 else
	   {
	     printf("Message = %s\n",$e->getMessage());
	   }
      }
    }
}

?>




</body>
</html>



Client using REST GET call access a service using REST
Run client (show code)

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

$requestPayloadString = <<<XML
    <ns1:echoString xmlns:ns1="http://wso2.org/wsfphp/samples">
        <text>Hello World!</text>
    </ns1:echoString>
XML;

try {

    $client = new WSClient( array("to" => "http://localhost/samples/echo_service.php/echoString",
                                  "useSOAP" => FALSE,
                                  "HTTPMethod" => "GET"));

                
    $responseMessage = $client->request($requestPayloadString);
    
    printf("Response = %s <br>", htmlspecialchars($responseMessage->str));

} catch (Exception $e) {

    if ($e instanceof WSFault) {
        printf("Soap Fault: %s\n", $e->Reason);
    } else {
        printf("Message = %s\n",$e->getMessage());
    }

}
?>


Client that adds custom soap headers
Run client (show code)

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

$requestPayloadString = <<<XML
    <ns1:echoString xmlns:ns1="http://wso2.org/wsfphp/samples">
        <text>Hello World!</text>
    </ns1:echoString>
XML;

try {

    $client = new WSClient(array( "to" => "http://localhost/samples/echo_service.php" ));

    $header1 = new WSHeader(array( "ns" => "http://test.org",
                                   "name" => "header1",
                                   "data" => "value1",
                                   "mustUnderstand" => false));


    $msg = new WSMessage($requestPayloadString , array( "inputHeaders" => array($header1)));
    $client->request($msg);

    $sentMsg = $client->getLastRequest();
    $recvMsg = $client->getLastResponse();        

    echo "\nSent message \n";
    echo htmlspecialchars($sentMsg);
   
    echo "\n\n Received message \n";
    echo htmlspecialchars($recvMsg);

} catch (Exception $e) {
    if ($e instanceof WSFault) {
        printf("Soap Fault: %s\n", $e->Reason);
    } else {
        printf("Message = %s\n",$e->getMessage());
    }
}
?>


Function API samples
Echo service implemented with ws_reply() function.
(show code)

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

include_once('wsf.php');

function echoFunction($inMessage) {

    $returnMessage = new WSMessage($inMessage->str);

    return $returnMessage;
}

$operations = array("echoString" => "echoFunction");

ws_reply(array("operations" => $operations));
        
?>


Client for reply echo service, using ws_request() function with payload in domDocument format.
Run client (show code)

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

include_once('wsf.php');

$requestPayloadString = <<<XML
    <ns1:echoString xmlns:ns1="http://wso2.org/wsfphp/samples">
        <text>Hello World!</text>
    </ns1:echoString>
XML;

$document = new domDocument;
$document->loadXML($requestPayloadString);


try {

    $responseMessage = ws_request($document, 
                        array("to" => "http://localhost/samples/reply_echo_service.php"));
    
    printf("Response = %s <br>", htmlspecialchars($responseMessage->str));

} catch (Exception $e) {

    if ($e instanceof WSFault) {
        printf("Soap Fault: %s\n", $e->Reason);
    } else {
        printf("Message = %s\n",$e->getMessage());
    }
}

?>


Client for reply echo service, using ws_request() function with payload in Axis2Message format.
Run client (show code)

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

include_once('wsf.php');

$requestPayloadString = <<<XML
    <ns1:echoString xmlns:ns1="http://wso2.org/wsfphp/samples">
        <text>Hello World!</text>
    </ns1:echoString>
XML;

try {

    $requestMessage = new WSMessage($requestPayloadString, 
                        array("to" => "http://localhost/samples/reply_echo_service.php"));
    
    $responseMessage = ws_request($requestMessage);
    
    printf("Response = %s <br>", htmlspecialchars($responseMessage->str));

} catch (Exception $e) {

    if ($e instanceof WSFault) {
        printf("Soap Fault: %s\n", $e->Reason);
    } else {
        printf("Message = %s\n",$e->getMessage());
    }
}

?>


Client for reply echo service, using ws_request() function with payload in string format.
Run client (show code)

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

include_once('wsf.php');

$requestPayloadString = <<<XML
    <ns1:echoString xmlns:ns1="http://wso2.org/wsfphp/samples">
        <text>Hello World!</text>
    </ns1:echoString>
XML;

try {

    $responseMessage = ws_request($requestPayloadString, 
                        array( "to" => "http://localhost/samples/reply_echo_service.php"));
    
    printf("Response = %s <br>", htmlspecialchars($responseMessage->str));

} catch (Exception $e) {

    if ($e instanceof WSFault) {
        printf("Soap Fault: %s\n", $e->Reason);
    } else {
        printf("Message = %s\n",$e->getMessage());
    }
}

?>


Accessing search providers
Google search sample. Note: Needs a valid google key. Insert your key in the key element of the payload string given in this sample.
Run Client (show code)
Google spell sample. Note: Needs a valid google key. Insert your key in the key element of the payload string given in this sample.
Run Client (show code)

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/** 
  * Note: This is a simole example written just as a proof of concept. 
  * You may write a nice web interface to improve the usability.    
  * This sample sends a Goole key and a phrase to Google spell service. 
  * If everyting goes right, it returns a spell corrected version of 
  * the prase you submit.
  * Google spell uses SOAP 1.1.
  */

$requestPayloadString = <<<XML
<ns1:doSpellingSuggestion x:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns1="urn:GoogleSearch" xmlns:x="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" xmlns:xsd="http://www.w3.org/1999/XMLSchema">
    <key xsi:type="xsd:string">your_key_here</key>
    <phrase xsi:type="xsd:string">tamperature</phrase>
</ns1:doSpellingSuggestion>
XML;

try {
    $client = new WSClient(array( "to" => "http://api.google.com/search/beta2", 
                                  "useSOAP" => 1.1)); 
    $responseMessage = $client->request($requestPayloadString);

    printf("Response = %s <br/>\n", htmlspecialchars($responseMessage->str));

} catch (Exception $e) {
    if ($e instanceof WSFault) {
        printf("Soap Fault: %s\n", $e->Reason);
    } else {
        printf("Message = %s\n",$e->getMessage());
    }
    
}


?>


A client assessing yahoo search using REST
Run client (show code)

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

$requestPayloadString = <<<XML
<webSearch><appid>ApacheRestDemo</appid><query>SriLanka</query><form/></webSearch>
XML;

try {

    $client = new WSClient(
        array("to"=>"http://search.yahooapis.com/WebSearchService/V1/webSearch",
	      "HTTPMethod"=>GET,
	      "useSOAP"=>FALSE));
				
    $responseMessage = $client->request($requestPayloadString);
    
    printf("Response = %s <br>", htmlspecialchars($responseMessage->str));

} catch (Exception $e) {

	if ($e instanceof WSFault) {
		printf("Soap Fault: %s\n", $e->Reason);
	} else {
		printf("Message = %s\n",$e->getMessage());
	}
}

?>


MTOM / Base64 Attachments
MTOM sample where the service sends an attachment to the client. The image used is located in the resources folder.
Run client | WSDL | show client code | show server code

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

$requestPayloadString = <<<XML
<download></download>
XML;

try {

    $client = new WSClient(
        array( "to" => "http://localhost/samples/mtom/mtom_download_service.php",
               "useMTOM" => TRUE,
               "responseXOP" => TRUE));

    $requestMessage = new WSMessage($requestPayloadString);                    
    $responseMessage = $client->request($requestMessage);
    
    printf("Response = %s \n", $responseMessage->str);

    $cid2stringMap = $responseMessage->attachments;
    $cid2contentMap = $responseMessage->cid2contentType;
    $imageName;
    if($cid2stringMap && $cid2contentMap){
        foreach($cid2stringMap as $i=>$value){
            $f = $cid2stringMap[$i];
            $contentType = $cid2contentMap[$i];
            if(strcmp($contentType,"image/jpeg") ==0){
                $imageName = $i."."."jpg";
                if(stristr(PHP_OS, 'WIN')) {
                    file_put_contents($imageName, $f);
                }else{
                    file_put_contents("/tmp/".$imageName, $f);
                }
            }
        }
    }else{
        printf("attachments not received ");
    }
    
} catch (Exception $e) {

    if ($e instanceof WSFault) {
        printf("Soap Fault: %s\n", $e->Reason);
    } else {
        printf("Message = %s\n",$e->getMessage());
    }
}
?>



<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function sendAttachment($msg)
{
$responsePayloadString = <<<XML
        <ns1:download xmlns:ns1="http://wso2.org/wsfphp/samples/mtom">
            <ns1:fileName>test.jpg</ns1:fileName>
                <ns1:image xmlmime:contentType="image/jpeg" xmlns:xmlmime="http://www.w3.org/2004/06/xmlmime">
                    <xop:Include xmlns:xop="http://www.w3.org/2004/08/xop/include" href="cid:myid1"></xop:Include>
                </ns1:image>
        </ns1:download>
XML;
    $f = file_get_contents("../resources/axis2.jpg");                                        

    $responseMessage = new WSMessage($responsePayloadString, 
            array( "attachments" => array("myid1" => $f)));  
    return $responseMessage;    
}

$operations = array("download" => "sendAttachment");

$service = new WSService(array("operations" => $operations, "useMTOM" => TRUE));

$service->reply();

?>


MTOM sample where the service saves an attachment sent by the client. You have to save the file to a globally writable folder. This sample uses '/tmp'.
Run client | WSDL | show server code | show client code

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

$requestPayloadString = <<<XML
<ns1:upload xmlns:ns1="http://wso2.org/wsfphp/samples/mtom">
               <ns1:fileName>test.jpg</ns1:fileName>
               <ns1:image xmlmime:contentType="image/jpeg" xmlns:xmlmime="http://www.w3.org/2004/06/xmlmime">
                  <xop:Include xmlns:xop="http://www.w3.org/2004/08/xop/include" href="cid:myid1"></xop:Include>
               </ns1:image>
</ns1:upload>
XML;

try {
    $f = file_get_contents("../resources/axis2.jpg");
    
    $requestMessage = new WSMessage($requestPayloadString, 
        array("to" => "http://localhost/samples/mtom/mtom_upload_service.php",
        "attachments" => array("myid1" => $f)));
    
    $client = new WSClient(array("useMTOM" => TRUE));

    $responseMessage = $client->request($requestMessage);
    
    echo $responseMessage->str;

} catch (Exception $e) {
    if ($e instanceof WSFault) {
        printf("Soap Fault: %s\n", $e->Reason);
    } else {
        printf("Message = %s\n",$e->getMessage());
    }
}
?>



<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function getAttachment($inMessage) {
    
    $cid2stringMap = $inMessage->attachments;
    $cid2contentMap = $inMessage->cid2contentType;
    $imageName;
    $file_saved = 0;

    foreach($cid2stringMap as $i=>$value){
        $f = $cid2stringMap[$i];
        $contentType = $cid2contentMap[$i];
        if(strcmp($contentType,"image/jpeg") ==0){
            $imageName = $i."."."jpg";
            if (stristr(PHP_OS, 'WIN')) {
                $file_saved = file_put_contents($imageName, $f);
            }else{                
                $file_saved = file_put_contents("/tmp/".$imageName, $f);
            }
        }
    }
    
if($file_saved){
$responsePayload = <<<XML
<ns1:response xmlns:ns1="http://wso2.org/wsfphp/samples/mtom">Image Saved</ns1:response>
XML;
}
else{
$responsePayload = <<<XML
<ns1:response xmlns:ns1="http://wso2.org/wsfphp/samples/mtom">Image Saving Failed</ns1:response>
XML;
}

    $returnMessage = new WSMessage($responsePayload);

    return $returnMessage;
}

$operations = array("upload" => "getAttachment");

$service = new WSService( array( "operations" => $operations, 
                                "requestXOP" => TRUE));
        
$service->reply();

?>


A service that receives a base64 string attachement and saves it to a file.
Run client | WSDL | show client code | show server code

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

$requestPayloadString = <<<XML
<ns1:upload xmlns:ns1="http://wso2.org/wsfphp/samples/mtom">
               <ns1:fileName>test.jpg</ns1:fileName>
               <ns1:image xmlmime:contentType="image/jpeg" xmlns:xmlmime="http://www.w3.org/2004/06/xmlmime">
                  <xop:Include xmlns:xop="http://www.w3.org/2004/08/xop/include" href="cid:myid1"></xop:Include>
               </ns1:image>
</ns1:upload>
XML;

try {
    $f = file_get_contents("../resources/axis2.jpg");
    
    $requestMessage = new WSMessage($requestPayloadString, 
        array("to" => "http://localhost/samples/mtom/mtom_upload_service_base64.php",
        "attachments" => array("myid1" => $f)));
    
    $client = new WSClient(array("useMTOM" =>FALSE));

    $responseMessage = $client->request($requestMessage);
    
    echo $responseMessage->str;

} catch (Exception $e) {
    if ($e instanceof WSFault) {
        printf("Soap Fault: %s\n", $e->Reason);
    } else {
        printf("Message = %s\n",$e->getMessage());
    }
}
?>



<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function getAttachment($inMessage) {
    
    $cid2stringMap = $inMessage->attachments;
    $cid2contentMap = $inMessage->cid2contentType;
    $imageName;
    
    $arraysize = count($cid2contentMap);
    if($arraysize == 0){
	    $dom = new DomDocument();
	    $dom->loadXML($inMessage->str);
	    $images = $dom->documentElement->getElementsByTagName('image');
        $image = $images->item(0);
        if (stristr(PHP_OS, 'WIN')) {
            file_put_contents("base64image.txt",$image->nodeValue);
            $str = base64_decode($image->nodeValue);
            file_put_contents("decoded_image.jpg", $str);
        }else{
            file_put_contents("/tmp/base64image.txt",$image->nodeValue);
		$str = base64_decode($image->nodeValue);
            file_put_contents("decoded_image.jpg", $str);
        }
    }

$responsePayload = <<<XML
<ns1:response xmlns:ns1="http://wso2.org/wsfphp/samples/mtom">Image Saved</ns1:response>
XML;

    $returnMessage = new WSMessage($responsePayload);

    return $returnMessage;
}

$operations = array("upload" => "getAttachment");

$service = new WSService(
            array(
                "operations" => $operations, 
                "requestXOP"=>TRUE));
        
$service->reply();

?>


WSDL generation
WSDL generation sample service for doc-lit style
Run client | WSDL | show client code | show server code

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class getPriceRequestWrapper
{
    public $item_name;
    public $amount;
}

class getPriceResponseWrapper
{
    public $price;
}

$class_map = array("getPrice" => "getPriceRequestWrapper",
                   "getPriceResponse" => "getPriceResponseWrapper");

try {

    $client = new WSClient(array("wsdl" => "http://localhost/samples/wsdl_generation/doclit_service.php?wsdl",
                                 "classmap" => $class_map));

    $proxy = $client->getProxy();	

    $input = new getPriceRequestWrapper();
    $input->item_name = "wso2";
    $input->amount = 10;

    $val = $proxy->getPrice($input);

    printf("The Total Price is: %s \n", $val->price);

} catch (Exception $e) {
    if ($e instanceof WSFault) {
        printf("Soap Fault Reason: %s\n", $e->Reason);
        printf("Soap Fault Code: %s \n", $e->Code);
        
    } else {
        printf("Message = %s\n",$e->getMessage());
    }
  }
?>



<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

$item = array("abc" => 101.5, "wso2" => 250.50, "xyz" => 99.99);

/** BuyItem function
 * @param string $item_name of the item to buy
 * (maps to the xs:string XML schema type )
 * @param int $amount no of items to buy
 * (maps to the xs:nonNegativeInteger XML schema type)
 * @return float $price total price
 *(maps to the xs:double XML schema type )
 */
function getPriceFunction($item_name ,$amount)
{
    global $item;
    if ($item_name && $amount){
        if(isset($item[$item_name])){
            return array("price" => ($item[$item_name] * $amount));
        }
        else
            return NULL;
    }
    return array("price" => 200043);
}


$operations = array("getPrice"=>"getPriceFunction");
$opParams = array("getPriceFunction"=>"MIXED");

$svr = new WSService(array("operations"=>$operations, 
			   "bindingStyle"=>"doclit",
		   	   "opParams"=>$opParams));


$svr->reply();


?>

    


WSDL generation sample service for rpc style
WSDL (show code)

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


/** The  purchaseOrder function
 * @param int $count the number of widgets to buy
 * (maps to the xs:nonNegativeInteger XML schema type )
 * @param string $date the date those items were sold
 * (maps to the xs:gDay XML schema type)
 * @return string $t time for buying it
 * (maps to the xs:QName XML schema type )
 */
function purchaseOrder($x,$y)
{
    return array("return"=>$x*$y);
}


$operations = array("purchaseOrder"=>"purchaseOrder");
$opParams = array("purchaseOrder"=>"MIXED");
$svr = new WSService(array("operations"=>$operations, "bindingStyle"=>"rpc-enc", "opParams" => $opParams));


$svr->reply();


?>

    


Security samples
UsernameToken sample
Run client | WSDL | show client code | show server code

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// User defined function implementing service operation 
function echoFunction($inMessage) {
    $returnMessage = new WSMessage($inMessage->str);
    return $returnMessage;
}

// Operations and associated options
$operations = array("echoString" => "echoFunction");
$actions = array("http://wso2.org/wsfphp/samples/echoString" => "echoString");

// Security options
$security_options = array("useUsernameToken" => TRUE);
$policy = new WSPolicy(array("security"=>$security_options));
$security_token = new WSSecurityToken(array("user" => "Raigama",
                                            "password" => "RaigamaPW",
                                            "passwordType" => "Digest"));

// Create service with options
$service = new WSService(array("operations" => $operations,
                               "actions" => $actions,
                               "policy" => $policy,
                               "securityToken" => $security_token));

// Reply to requests
$service->reply();

?>



<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// Request payload string 
$reqPayloadString = <<<XML
<ns1:echo xmlns:ns1="http://wso2.org/wsfphp/samples"><text>Hello World!</text></ns1:echo>
XML;

try {
    // Create message with request payload and options
    $reqMessage = new WSMessage($reqPayloadString,
                         array("to" => "http://localhost/samples/security/username_token/service.php",
                               "action" => "http://wso2.org/wsfphp/samples/echoString"));
   
    // Set up security options
    $security_options = array("useUsernameToken" => TRUE );
    $policy = new WSPolicy(array("security" => $security_options));
    $security_token = new WSSecurityToken(array("user" => "Raigama",
                                                "password" => "RaigamaPW",
                                                "passwordType" => "Digest"));
    
    // Create client with options
    $client = new WSClient(array("useWSA" => TRUE,
                                 "policy" => $policy,
                                 "securityToken" => $security_token));
	
    // Send request and capture response
    $resMessage = $client->request($reqMessage);
    
    printf("Response = %s \n", $resMessage->str);

} catch (Exception $e) {

	if ($e instanceof WSFault) {
		printf("Soap Fault: %s\n", $e->Reason);
	} else {
		printf("Message = %s\n",$e->getMessage());
	}
}
?>


UsernameToken sample client based on a policy file
Run client | WSDL | show client code | show server code | show policy code

<wsp:Policy xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
    <wsp:ExactlyOne>
        <wsp:All>
            <sp:AsymmetricBinding xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
                <wsp:Policy>
                    <sp:InitiatorToken>
                        <wsp:Policy>
                            <sp:X509Token sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/AlwaysToRecipient">
                                <wsp:Policy>
                                    <sp:WssX509V3Token10/>
                                </wsp:Policy>
                            </sp:X509Token>
                        </wsp:Policy>
                    </sp:InitiatorToken>
                    <sp:RecipientToken>
                        <wsp:Policy>
                            <sp:X509Token sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/Never">
                                <wsp:Policy>
                                    <sp:WssX509V3Token10/>
                                </wsp:Policy>
                            </sp:X509Token>
                        </wsp:Policy>
                    </sp:RecipientToken>
                    <sp:Layout>
                        <wsp:Policy>
                            <sp:Strict/>
                        </wsp:Policy>
                    </sp:Layout>
                </wsp:Policy>
            </sp:AsymmetricBinding>
            <sp:SignedSupportingTokens xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
            <wsp:Policy>
                <sp:UsernameToken sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/Always"/>
            </wsp:Policy>
            </sp:SignedSupportingTokens>
        </wsp:All>
    </wsp:ExactlyOne>
</wsp:Policy>



<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// User defined function implementing service operation 
function echoFunction($inMessage) {
    $returnMessage = new WSMessage($inMessage->str);
    return $returnMessage;
}

// Operations and associated options
$operations = array("echoString" => "echoFunction");
$actions = array("http://wso2.org/wsfphp/samples/echoString" => "echoString");

// Security options
$policy_xml = file_get_contents("policy.xml");
$policy = new WSPolicy($policy_xml);
$security_token = new WSSecurityToken(array("user" => "Alice",
                                            "password" => "abcd!123",
                                            "passwordType" => "Digest"));

// Create service with options
$service = new WSService(array("operations" => $operations,
                               "actions" => $actions,
                               "policy" => $policy,
                               "securityToken" => $security_token));

// Reply to requests
$service->reply();

?>



<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// Request payload string 
$reqPayloadString = <<<XML
<ns1:echo xmlns:ns1="http://wso2.org/wsfphp/samples"><text>Hello World!</text></ns1:echo>
XML;

try {
    // Create message with request payload and options
    $reqMessage = new WSMessage($reqPayloadString,
                         array("to" => "http://localhost/samples/security/username_token/policy_file_based/service.php",
                               "action" => "http://wso2.org/wsfphp/samples/echoString"));
   
    // Set up security options
    $policy_xml = file_get_contents("policy.xml");
    $policy = new WSPolicy($policy_xml);
    $security_token = new WSSecurityToken(array("user" => "Alice",
                                                "password" => "abcd!123",
                                                "passwordType" => "Digest"));
    
    // Create client with options
    $client = new WSClient(array("useWSA" => TRUE,
                                 "policy" => $policy,
                                 "securityToken" => $security_token));
	
    // Send request and capture response
    $resMessage = $client->request($reqMessage);
    
    printf("Response = %s \n", $resMessage->str);

} catch (Exception $e) {

	if ($e instanceof WSFault) {
		printf("Soap Fault: %s\n", $e->Reason);
	} else {
		printf("Message = %s\n",$e->getMessage());
	}
}
?>


UsernameToken sample client for password call back method
Run client | WSDL | show client code | show server code

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// Username Password mapping table
$user_pass_mapping = array(
					"Raigama" => "RaigamaPW",
					"Alice" => "abcd!123",
					"Bob" => "wxyz!123");

function echoFunction($inMessage) {

	$returnMessage = new WSMessage($inMessage->str);

	return $returnMessage;
}

function get_my_password_function($username)
{
	//logic to get password from any source (ex: using mysql database
	// etc)
	global $user_pass_mapping;

	if(isset($user_pass_mapping[$username])){
		$password = $user_pass_mapping[$username];
		return $password;
	}
	else
	 return NULL;

}

$operations = array("echoString" => "echoFunction");
$actions = array("http://wso2.org/wsfphp/samples/echoString" => "echoString");
$sec_array = array("useUsernameToken" => TRUE);

$policy = new WSPolicy(array("security"=>$sec_array));
$sec_token = new WSSecurityToken(array("passwordCallback" => "get_my_password_function",
                                       "passwordType" => "Digest"));

$svr = new WSService(array("operations" => $operations,
                           "actions" => $actions,
                           "policy" => $policy,
                           "securityToken" => $sec_token));

$svr->reply();

?>



<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

$reqPayloadString = <<<XML
<ns1:echo xmlns:ns1="http://wso2.org/wsfphp/samples"><text>Hello World!</text></ns1:echo>
XML;

try {

    $reqMessage = new WSMessage($reqPayloadString,
                                array("to" => "http://localhost/samples/security/username_token/call_back/service.php",
                                      "action" => "http://wso2.org/wsfphp/samples/echoString"));
    
    $sec_array = array("useUsernameToken" => TRUE );
    $policy = new WSPolicy(array("security" => $sec_array));
    $sec_token = new WSSecurityToken(array("user" => "Raigama",
                                           "password" => "RaigamaPW",
                                           "passwordType" => "Digest"));
    
    $client = new WSClient(array("useWSA" => TRUE,
                                 "policy" => $policy,
                                 "securityToken" => $sec_token));
				
    $resMessage = $client->request($reqMessage);
    
    printf("Response = %s \n", $resMessage->str);

} catch (Exception $e) {

	if ($e instanceof WSFault) {
		printf("Soap Fault: %s\n", $e->Reason);
	} else {
		printf("Message = %s\n",$e->getMessage());
	}

}
?>


Timestamp client
Run client | WSDL | show client code | show server code

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function echoFunction($inMessage) {

    $returnMessage = new WSMessage($inMessage->str);

    return $returnMessage;
}

$operations = array("echoString" => "echoFunction");
$actions = array("http://wso2.org/wsfphp/samples/echoString" => "echoString");
$sec_array = array("includeTimeStamp" => TRUE);

$policy = new WSPolicy(array("security"=> $sec_array));
$sec_token = new WSSecurityToken(array("ttl" => 100));

$svr = new WSService(array("operations" => $operations,
                           "actions" => $actions,
                           "policy" => $policy,
                           "securityToken" => $sec_token));
        
$svr->reply();

?>





<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

$reqPayloadString = <<<XML
<ns1:echo xmlns:ns1="http://wso2.org/wsfphp/samples"><text>Hello World!</text></ns1:echo>
XML;

try {

    $reqMessage = new WSMessage($reqPayloadString,
                                array("to"=>"http://localhost/samples/security/timestamp/service.php",
                                      "action" => "http://wso2.org/wsfphp/samples/echoString"));
    
    $sec_array = array("includeTimeStamp" => TRUE );
    $policy = new WSPolicy(array("security" => $sec_array));
    $sec_token = new WSSecurityToken(array("ttl" => 60));
    
    $client = new WSClient(array("useWSA" => TRUE,
                                 "policy" => $policy,
                                 "securityToken" => $sec_token));
				
    $resMessage = $client->request($reqMessage);
    
    printf("Response = %s \n", $resMessage->str);

} catch (Exception $e) {

	if ($e instanceof WSFault) {
		printf("Soap Fault: %s\n", $e->Reason);
	} else {
		printf("Message = %s\n",$e->getMessage());
	}

}
?>


Timestamp client based on a policy file
Run client | WSDL | show client code | show server code | show policy code

<wsp:Policy xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
    <wsp:ExactlyOne>
        <wsp:All>
            <sp:AsymmetricBinding xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
                <wsp:Policy>
                    <sp:InitiatorToken>
                        <wsp:Policy>
                            <sp:X509Token sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/AlwaysToRecipient">
                                <wsp:Policy>
                                    <sp:WssX509V3Token10/>
                                </wsp:Policy>
                            </sp:X509Token>
                        </wsp:Policy>
                    </sp:InitiatorToken>
                    <sp:RecipientToken>
                        <wsp:Policy>
                            <sp:X509Token sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/Never">
                                <wsp:Policy>
                                    <sp:WssX509V3Token10/>
                                </wsp:Policy>
                            </sp:X509Token>
                        </wsp:Policy>
                    </sp:RecipientToken>
                    <sp:Layout>
                        <wsp:Policy>
                            <sp:Strict/>
                        </wsp:Policy>
                    </sp:Layout>
                    <sp:IncludeTimestamp/>
                </wsp:Policy>
            </sp:AsymmetricBinding>
        </wsp:All>
    </wsp:ExactlyOne>
</wsp:Policy>


<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function echoFunction($inMessage) {

    $returnMessage = new WSMessage($inMessage->str);

    return $returnMessage;
}

$operations = array("echoString" => "echoFunction");
$actions = array("http://wso2.org/wsfphp/samples/echoString" => "echoString");

$policy_xml = file_get_contents("policy.xml");
$policy = new WSPolicy($policy_xml);
$sec_token = new WSSecurityToken(array("ttl" => 100));

$svr = new WSService(array("operations" => $operations,
                           "actions" => $actions,
                           "policy" => $policy,
                           "securityToken" => $sec_token));
        
$svr->reply();

?>





<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

$reqPayloadString = <<<XML
<ns1:echo xmlns:ns1="http://wso2.org/wsfphp/samples"><text>Hello World!</text></ns1:echo>
XML;

try {

    $reqMessage = new WSMessage($reqPayloadString,
                                array("to"=>"http://localhost/samples/security/timestamp/policy_file_based/service.php",
                                      "action" => "http://wso2.org/wsfphp/samples/echoString"));
    
    $policy_xml = file_get_contents("policy.xml");
    $policy = new WSPolicy($policy_xml);
    $sec_token = new WSSecurityToken(array("ttl" => 60));
    
    $client = new WSClient(array("useWSA" => TRUE,
                                 "policy" => $policy,
                                 "securityToken" => $sec_token));
				
    $resMessage = $client->request($reqMessage);
    
    printf("Response = %s \n", $resMessage->str);

} catch (Exception $e) {

	if ($e instanceof WSFault) {
		printf("Soap Fault: %s\n", $e->Reason);
	} else {
		printf("Message = %s\n",$e->getMessage());
	}

}
?>


Encryption Client
Run client | WSDL | show client code | show server code

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function echoFunction($inMessage) {

    $returnMessage = new WSMessage($inMessage->str);

    return $returnMessage;
}

$pub_key = ws_get_cert_from_file("../keys/alice_cert.cert");
$pvt_key = ws_get_key_from_file("../keys/bob_key.pem");

$operations = array("echoString" => "echoFunction");
$sec_array = array("encrypt" => TRUE,
                    "algorithmSuite" => "Basic256Rsa15",
                    "securityTokenReference" => "IssuerSerial");

$actions = array("http://wso2.org/wsfphp/samples/echoString" => "echoString");
 
$policy = new WSPolicy(array("security"=> $sec_array));
$sec_token = new WSSecurityToken(array("privateKey" => $pvt_key,
                                       "receiverCertificate" => $pub_key));

$svr = new WSService(array("actions" => $actions,
                           "operations" => $operations,
                           "policy" => $policy,
                           "securityToken" => $sec_token));
        
$svr->reply();

?>



<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

$reqPayloadString = <<<XML
<ns1:echo xmlns:ns1="http://wso2.org/wsfphp/samples"><text>Hello World!</text></ns1:echo>
XML;

try {
    $rec_cert = ws_get_cert_from_file("../keys/bob_cert.cert");
    $pvt_key = ws_get_key_from_file("../keys/alice_key.pem");
    
    $reqMessage = new WSMessage($reqPayloadString,
                                array("to" => "http://localhost/samples/security/encryption/service.php",
                                      "action" => "http://wso2.org/wsfphp/samples/echoString"));
    
    $sec_array = array("encrypt" => TRUE,
                       "algorithmSuite" => "Basic256Rsa15",
                       "securityTokenReference" => "IssuerSerial");
    
    $policy = new WSPolicy(array("security" => $sec_array));
    $sec_token = new WSSecurityToken(array("privateKey" => $pvt_key,
                                           "receiverCertificate" => $rec_cert));
    
    $client = new WSClient(array("useWSA" => TRUE,
                                 "policy" => $policy,
                                 "securityToken" => $sec_token));
				
    $resMessage = $client->request($reqMessage);
    
    printf("Response = %s \n", $resMessage->str);

} catch (Exception $e) {

	if ($e instanceof WSFault) {
		printf("Soap Fault: %s\n", $e->Reason);
	} else {
		printf("Message = %s\n",$e->getMessage());
	}

}
?>


Encryption Client based on a policy file
Run client | WSDL | show client code | show server code | show policy code

<wsp:Policy xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
    <wsp:ExactlyOne>
        <wsp:All>
            <sp:AsymmetricBinding xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
                <wsp:Policy>
                    <sp:InitiatorToken>
                        <wsp:Policy>
                            <sp:X509Token sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/AlwaysToRecipient">
                                <wsp:Policy>
                                    <sp:WssX509V3Token10/>
                                </wsp:Policy>
                            </sp:X509Token>
                        </wsp:Policy>
                    </sp:InitiatorToken>
                    <sp:RecipientToken>
                        <wsp:Policy>
                            <sp:X509Token sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/Never">
                                <wsp:Policy>
                                    <sp:WssX509V3Token10/>
                                </wsp:Policy>
                            </sp:X509Token>
                        </wsp:Policy>
                    </sp:RecipientToken>
                    <sp:AlgorithmSuite>
                        <wsp:Policy>
                            <sp:Basic256Rsa15/>
                        </wsp:Policy>
                    </sp:AlgorithmSuite>
                    <sp:Layout>
                        <wsp:Policy>
                            <sp:Strict/>
                        </wsp:Policy>
                    </sp:Layout>
                </wsp:Policy>
            </sp:AsymmetricBinding>
            <sp:Wss10 xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
                <wsp:Policy>
                    <sp:MustSupportRefKeyIdentifier/>
                    <sp:MustSupportRefEmbeddedToken/>
                    <sp:MustSupportRefIssuerSerial/>
                </wsp:Policy>
            </sp:Wss10>
            <sp:EncryptedParts xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
                <sp:Body/>
            </sp:EncryptedParts>
        </wsp:All>
    </wsp:ExactlyOne>
</wsp:Policy>



<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function echoFunction($inMessage) {

    $returnMessage = new WSMessage($inMessage->str);

    return $returnMessage;
}

$pub_key = ws_get_cert_from_file("../../keys/alice_cert.cert");
$pvt_key = ws_get_key_from_file("../../keys/bob_key.pem");

$operations = array("echoString" => "echoFunction");

$actions = array("http://wso2.org/wsfphp/samples/echoString" => "echoString");

$policy_xml = file_get_contents("policy.xml");
$policy = new WSPolicy($policy_xml);
$sec_token = new WSSecurityToken(array("privateKey" => $pvt_key,
                                       "receiverCertificate" => $pub_key));

$svr = new WSService(array("actions" => $actions,
                           "operations" => $operations,
                           "policy" => $policy,
                           "securityToken" => $sec_token));
        
$svr->reply();

?>



<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

$reqPayloadString = <<<XML
<ns1:echo xmlns:ns1="http://wso2.org/wsfphp/samples"><text>Hello World!</text></ns1:echo>
XML;

try {
    $rec_cert = ws_get_cert_from_file("../../keys/bob_cert.cert");
    $pvt_key = ws_get_key_from_file("../../keys/alice_key.pem");
    
    $reqMessage = new WSMessage($reqPayloadString,
                                array("to" => "http://localhost/samples/security/encryption/policy_file_based/service.php",
                                      "action" => "http://wso2.org/wsfphp/samples/echoString"));
    
    $policy_xml = file_get_contents("policy.xml"); 
    $policy = new WSPolicy($policy_xml);
    $sec_token = new WSSecurityToken(array("privateKey" => $pvt_key,
                                           "receiverCertificate" => $rec_cert));
    
    $client = new WSClient(array("useWSA" => TRUE,
                                 "policy" => $policy,
                                 "securityToken" => $sec_token));
				
    $resMessage = $client->request($reqMessage);
    
    printf("Response = %s \n", $resMessage->str);

} catch (Exception $e) {

	if ($e instanceof WSFault) {
		printf("Soap Fault: %s\n", $e->Reason);
	} else {
		printf("Message = %s\n",$e->getMessage());
	}

}
?>


Signing Client
Run client | WSDL | show client code | show server code

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function echoFunction($inMessage) {

    $returnMessage = new WSMessage($inMessage->str);

    return $returnMessage;
}

$cert = ws_get_cert_from_file("../keys/bob_cert.cert");
$pvt_key = ws_get_key_from_file("../keys/bob_key.pem");

$operations = array("echoString" => "echoFunction");

$sec_array = array("sign" => TRUE,
                    "algorithmSuite" => "Basic256Rsa15",
                    "securityTokenReference" => "KeyIdentifier");

$policy = new WSPolicy(array("security"=>$sec_array));

$sec_token = new WSSecurityToken(array("privateKey" => $pvt_key,
                                       "certificate" => $cert));

$actions = array("http://wso2.org/wsfphp/samples/echoString" => "echoString");

$svr = new WSService(array("operations" => $operations,
                           "actions" => $actions,
                           "policy" => $policy,
                           "securityToken" => $sec_token));
        
$svr->reply();

?>



<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

$reqPayloadString = <<<XML
<ns1:echo xmlns:ns1="http://wso2.org/wsfphp/samples"><text>Hello World!</text></ns1:echo>
XML;

try {
    $my_cert = ws_get_cert_from_file("../keys/alice_cert.cert");
    $my_key = ws_get_key_from_file("../keys/alice_key.pem");
    $rec_cert = ws_get_cert_from_file("../keys/bob_cert.cert");
    
    $reqMessage = new WSMessage($reqPayloadString,
                                array("to" => "http://localhost/samples/security/signing/service.php",
                                      "action" => "http://wso2.org/wsfphp/samples/echoString"));
    
    $sec_array = array("sign"=>TRUE,
                       "algorithmSuite" => "Basic256Rsa15",
                       "securityTokenReference" => "IssuerSerial");
    
    $policy = new WSPolicy(array("security"=>$sec_array));
    $sec_token = new WSSecurityToken(array("privateKey" => $my_key,
                                           "certificate" => $my_cert,
                                           "receiverCertificate" => $rec_cert));
    
    $client = new WSClient(array("useWSA" => TRUE,
                                 "policy" => $policy,
                                 "securityToken" => $sec_token));
				
    $resMessage = $client->request($reqMessage);
    
    printf("Response = %s \n", $resMessage->str);

} catch (Exception $e) {

	if ($e instanceof WSFault) {
		printf("Soap Fault: %s\n", $e->Reason);
	} else {
		printf("Message = %s\n",$e->getMessage());
	}

}
?>


Signing Client based on a policy file
Run client | WSDL | show client code | show server code | show policy code

<wsp:Policy xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
    <wsp:ExactlyOne>
        <wsp:All>
            <sp:AsymmetricBinding xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
                <wsp:Policy>
                    <sp:InitiatorToken>
                        <wsp:Policy>
                            <sp:X509Token sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/AlwaysToRecipient">
                                <wsp:Policy>
                                    <sp:WssX509V3Token10/>
                                </wsp:Policy>
                            </sp:X509Token>
                        </wsp:Policy>
                    </sp:InitiatorToken>
                    <sp:RecipientToken>
                        <wsp:Policy>
                            <sp:X509Token sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/Never">
                                <wsp:Policy>
                                    <sp:WssX509V3Token10/>
                                </wsp:Policy>
                            </sp:X509Token>
                        </wsp:Policy>
                    </sp:RecipientToken>
                    <sp:AlgorithmSuite>
                        <wsp:Policy>
                            <sp:Basic256Rsa15/>
                        </wsp:Policy>
                    </sp:AlgorithmSuite>
                    <sp:Layout>
                        <wsp:Policy>
                            <sp:Strict/>
                        </wsp:Policy>
                    </sp:Layout>
                </wsp:Policy>
            </sp:AsymmetricBinding>
            <sp:Wss10 xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
                <wsp:Policy>
                    <sp:MustSupportRefKeyIdentifier/>
                    <sp:MustSupportRefEmbeddedToken/>
                    <sp:MustSupportRefIssuerSerial/>
                </wsp:Policy>
            </sp:Wss10>
            <sp:SignedParts xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
                <sp:Body/>
                <sp:Header Namespace="http://www.w3.org/2005/08/addressing"/>
            </sp:SignedParts>
        </wsp:All>
    </wsp:ExactlyOne>
</wsp:Policy>



<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function echoFunction($inMessage) {

    $returnMessage = new WSMessage($inMessage->str);

    return $returnMessage;
}

$cert = ws_get_cert_from_file("../../keys/bob_cert.cert");
$pvt_key = ws_get_key_from_file("../../keys/bob_key.pem");

$operations = array("echoString" => "echoFunction");

$policy_xml = file_get_contents("policy.xml");
$policy = new WSPolicy($policy_xml);

$sec_token = new WSSecurityToken(array("privateKey" => $pvt_key,
                                       "certificate" => $cert));

$actions = array("http://wso2.org/wsfphp/samples/echoString" => "echoString");

$svr = new WSService(array("operations" => $operations,
                           "actions" => $actions,
                           "policy" => $policy,
                           "securityToken" => $sec_token));
        
$svr->reply();

?>



<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

$reqPayloadString = <<<XML
<ns1:echo xmlns:ns1="http://wso2.org/wsfphp/samples"><text>Hello World!</text></ns1:echo>
XML;

try {
    $my_cert = ws_get_cert_from_file("../../keys/alice_cert.cert");
    $my_key = ws_get_key_from_file("../../keys/alice_key.pem");
    $rec_cert = ws_get_cert_from_file("../../keys/bob_cert.cert");
    
    $reqMessage = new WSMessage($reqPayloadString,
                                array("to" => "http://localhost/samples/security/signing/policy_file_based/service.php",
                                      "action" => "http://wso2.org/wsfphp/samples/echoString"));
    
    $policy_xml = file_get_contents("policy.xml"); 
    $policy = new WSPolicy($policy_xml);
    $sec_token = new WSSecurityToken(array("privateKey" => $my_key,
                                           "certificate" => $my_cert,
                                           "receiverCertificate" => $rec_cert));
    
    $client = new WSClient(array("useWSA" => TRUE,
                                 "policy" => $policy,
                                 "securityToken" => $sec_token));
				
    $resMessage = $client->request($reqMessage);
    
    printf("Response = %s \n", $resMessage->str);

} catch (Exception $e) {

	if ($e instanceof WSFault) {
		printf("Soap Fault: %s\n", $e->Reason);
	} else {
		printf("Message = %s\n",$e->getMessage());
	}

}
?>


Replay Attack
Run client | WSDL | show client code | show server code

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function echoFunction($inMessage) {

    $returnMessage = new WSMessage($inMessage->str);

    return $returnMessage;
}

function array_contains($array_of_string, $str) {
    foreach ($array_of_string as $value) {
        if(strcmp($value, $str) == 0) {
            return TRUE;            
        }
    }
    return FALSE;
}

function replay_detect_callback($msg_id, $time_created) {
    
    $max_duration = 5;
    if (stristr(PHP_OS, 'WIN')) {
        $replay_file = "replay.content";
    }else{
        $replay_file = "/tmp/replay.content";
    }
    $list_of_records = array(); 
    clearstatcache();   
    if(file_exists($replay_file))
    {
        $length = filesize($replay_file);
        $fp_rf = fopen($replay_file, "r");
        if(flock($fp_rf, LOCK_SH)) {
            $content = fread($fp_rf, $length);
            flock($fp_rf, LOCK_UN);
            $tok_rec = strtok($content, '@');
            while($tok_rec) {
                $list_of_records[] = $tok_rec;
                $tok_rec = strtok('@');
            }
        } else {
            echo "Couldn't lock the ".$replay_file." for reading!";
        }
        fclose($fp_rf);
    }else {
        $fp_rf_w = fopen($replay_file, "w");
        if(flock($fp_rf_w, LOCK_EX)) {
            fwrite($fp_rf_w, $msg_id.$time_created.'@');
            flock($fp_rf_w, LOCK_UN);
        } else {
            echo "Couldn't lock the ".$replay_file." for writing!";
        }
        fclose($fp_rf_w);
        return TRUE;
    }

    if(array_contains($list_of_records, $msg_id.$time_created)) {
        return FALSE;
    } else {
        $elements = count($list_of_records);
        if($elements == $max_duration) {
            $new_rcd_list = array_splice($list_of_records, 1);
            $new_rcd_list[] = $msg_id.$time_created;
            $fp_rf_w = fopen($replay_file, "w");
            if(flock($fp_rf_w, LOCK_EX)) {
                foreach($new_rcd_list as $value) {
                    fwrite($fp_rf_w, $value.'@');
                }
                flock($fp_rf_w, LOCK_UN);
            } else {
                echo "Couldn't lock the file for writing!";
            }
            fclose($fp_rf_w);
        } else {
            $list_of_records[] = $msg_id.$time_created;
            $fp_rf_w = fopen($replay_file, "w");
            if(flock($fp_rf_w, LOCK_EX)) {
                foreach($list_of_records as $value) {
                    fwrite($fp_rf_w, $value.'@');
                }
                flock($fp_rf_w, LOCK_UN);
            } else {
                echo "Couldn't lock the file for writing!";
            }

            fclose($fp_rf_w);
        }
    }

    return TRUE;
}

$operations = array("echoString" => "echoFunction");
$actions = array("http://wso2.org/wsfphp/samples/echoString" => "echoString");

$security_options = array("useUsernameToken" => TRUE);
$policy = new WSPolicy(array("security"=>$security_options));
$security_token = new WSSecurityToken(array("user" => "Raigama",
                                            "password" => "RaigamaPW",
                                            "passwordType" => "Digest",
                        "replayDetectionCallback" => "replay_detect_callback",
                        "enableReplayDetect" => TRUE));


$svr = new WSService(array("operations" => $operations,
                           "actions" => $actions,
                           "policy" => $policy,
                           "securityToken" => $security_token));
        
$svr->reply();

?>




<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


$reqPayloadString = <<<XML
<ns1:echo xmlns:ns1="http://wso2.org/wsfphp/samples"><text>Hello World!</text></ns1:echo>
XML;

try {

    $reqMessage = new WSMessage($reqPayloadString,
                                array("to"=>"http://localhost/samples/security/replay_detect/service.php",
                                      "action" => "http://wso2.org/wsfphp/samples/echoString"));

    $security_options = array("useUsernameToken" => TRUE );
    $policy = new WSPolicy(array("security" => $security_options));
    $security_token = new WSSecurityToken(array("user" => "Raigama",
                                                "password" => "RaigamaPW",
                                                "passwordType" => "Digest"));

    $client = new WSClient(array("useWSA" => TRUE,
                                "policy" => $policy,
                                "securityToken" => $security_token));

    $resMessage = $client->request($reqMessage);

    printf("Response = %s \n", $resMessage->str);

} catch (Exception $e) {

    if ($e instanceof WSFault) {
        printf("Soap Fault: %s\n", $e->Reason);
    } else {
        printf("Message = %s\n",$e->getMessage());
    }

}
?>


Signing Encryption Timestamp Together based on a policy file
Run client | WSDL | show client code | show server code | show policy code

<wsp:Policy xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
    <wsp:ExactlyOne>
        <wsp:All>
            
            <sp:AsymmetricBinding xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
                <wsp:Policy>
                    
                    <sp:InitiatorToken>
                        <wsp:Policy>
                            <sp:X509Token sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/AlwaysToRecipient">
                                <wsp:Policy>
                                    <sp:WssX509V3Token10 />
                                </wsp:Policy>
                            </sp:X509Token>
                        </wsp:Policy>
                    </sp:InitiatorToken>
                    
                    <sp:RecipientToken>
                        <wsp:Policy>
                            <sp:X509Token sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/Never">
                                <wsp:Policy>
                                    <sp:WssX509V3Token10 />
                                </wsp:Policy>
                            </sp:X509Token>
                        </wsp:Policy>
                    </sp:RecipientToken>
                    
                    <sp:AlgorithmSuite>
                        <wsp:Policy>
                            <sp:Basic256Rsa15 />
                        </wsp:Policy>
                    </sp:AlgorithmSuite>
                    
                    <sp:Layout>
                        <wsp:Policy>
                            <sp:Lax />
                        </wsp:Policy>
                    </sp:Layout>
                    
                    <sp:IncludeTimestamp />
                    <sp:EncryptSignature />
                    <sp:OnlySignEntireHeadersAndBody />
                    
                </wsp:Policy>
            </sp:AsymmetricBinding>
                        
            <sp:Wss10 xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
                <wsp:Policy>
                    <sp:MustSupportRefKeyIdentifier />                  
                    <sp:MustSupportRefIssuerSerial />
                </wsp:Policy>
            </sp:Wss10>

            <sp:SignedParts xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
                <sp:Body />
            </sp:SignedParts>

            <sp:EncryptedParts xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
                <sp:Body />
            </sp:EncryptedParts>
            
        </wsp:All>
    </wsp:ExactlyOne>
</wsp:Policy>


<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function echoFunction($inMessage) {

    $returnMessage = new WSMessage($inMessage->str);

    return $returnMessage;
}

$cert = ws_get_cert_from_file("../keys/bob_cert.cert");
$pvt_key = ws_get_key_from_file("../keys/bob_key.pem");
$pub_key = ws_get_cert_from_file("../keys/alice_cert.cert");

$operations = array("echoString" => "echoFunction");

$policy_xml = file_get_contents("policy.xml");
$policy = new WSPolicy($policy_xml);

$sec_token = new WSSecurityToken(array("privateKey" => $pvt_key,
                                       "certificate" => $cert,
                                       "receiverCertificate" => $pub_key));

$actions = array("http://wso2.org/wsfphp/samples/echoString" => "echoString");

$svr = new WSService(array("operations" => $operations,
                           "actions" => $actions,
                           "policy" => $policy,
                           "securityToken" => $sec_token));

$svr->reply();

?>



<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

$reqPayloadString = <<<XML
<ns1:echo xmlns:ns1="http://wso2.org/wsfphp/samples"><text>Hello World!</text></ns1:echo>
XML;

try {
    $my_cert = ws_get_cert_from_file("../keys/alice_cert.cert");
    $my_key = ws_get_key_from_file("../keys/alice_key.pem");
    $rec_cert = ws_get_cert_from_file("../keys/bob_cert.cert");
    
    $reqMessage = new WSMessage($reqPayloadString,
                                array("to" => "http://localhost/samples/security/complete/service.php",
                                      "action" => "http://wso2.org/wsfphp/samples/echoString"));
    
    
    $policy_xml = file_get_contents("policy.xml");
    $policy = new WSPolicy($policy_xml);
    $sec_token = new WSSecurityToken(array("privateKey" => $my_key,
                                           "certificate" => $my_cert,
                                           "receiverCertificate" => $rec_cert));
    
    $client = new WSClient(array("useWSA" => TRUE,
                                 "useSOAP" => "1.1",
                                 "policy" => $policy,
                                 "securityToken" => $sec_token));
                
    $resMessage = $client->request($reqMessage);
    
    printf("Response = %s \n", $resMessage->str);

} catch (Exception $e) {

    if ($e instanceof WSFault) {
        printf("Soap Fault: %s\n", $e->Reason);
    } else {
        printf("Message = %s\n",$e->getMessage());
    }
}

?>


MTOM upload client with encryption enabled
Run client | WSDL | show client code | show server code

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


function getAttachment($inMessage) {

  $cid2stringMap = $inMessage->attachments;
    $cid2contentMap = $inMessage->cid2contentType;
    $imageName;


    foreach($cid2stringMap as $i=>$value){
        $f = $cid2stringMap[$i];
        $contentType = $cid2contentMap[$i];
        if(strcmp($contentType,"image/jpeg") ==0){
            $imageName = $i."."."jpg";
            file_put_contents("/tmp/".$imageName, $f);
        }
    }

    $arraysize = count($cid2contentMap);
    if($arraysize == 0){
        $dom = new DomDocument();
        $dom->loadXML($inMessage->str);
        $images = $dom->documentElement->getElementsByTagName('image');
        $image = $images->item(0);
        file_put_contents("/tmp/base64image.txt",$image->nodeValue);
    }

$resPayload = <<<XML
<ns1:response xmlns:ns1="http://wso2.org/wsfphp/samples/mtom">Image Saved</ns1:response>
XML;

    $returnMessage = new WSMessage($resPayload);

    return $returnMessage;

}

$pub_key = ws_get_cert_from_file("../../keys/alice_cert.cert");
$pvt_key = ws_get_key_from_file("../../keys/bob_key.pem");

$operations = array("upload" => "getAttachment");
$sec_array = array("encrypt" => TRUE,
                    "algorithmSuite" => "Basic256Rsa15",
                    "securityTokenReference" => "IssuerSerial");

$actions = array("http://wso2.org/upload" => "upload");
 
$policy = new WSPolicy(array("security"=> $sec_array));
$sec_token = new WSSecurityToken(array("privateKey" => $pvt_key,
                                       "receiverCertificate" => $pub_key));

$svr = new WSService(array("actions" => $actions,
                           "operations" => $operations,
                           "policy" => $policy,
                           "requestXOP"=>TRUE,
                           "securityToken" => $sec_token));
        
$svr->reply();

?>



<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

$reqPayloadString = <<<XML
<ns1:upload xmlns:ns1="http://wso2.org/wsfphp/samples/mtom">
               <ns1:fileName>test.jpg</ns1:fileName>
               <ns1:image xmlmime:contentType="image/jpeg" xmlns:xmlmime="http://www.w3.org/2004/06/xmlmime">
                  <xop:Include xmlns:xop="http://www.w3.org/2004/08/xop/include" href="cid:myid1"></xop:Include>
               </ns1:image>
</ns1:upload>
XML;

try {
    $f = file_get_contents("../../../resources/axis2.jpg");

    $rec_cert = ws_get_cert_from_file("../../keys/bob_cert.cert");
    $pvt_key = ws_get_key_from_file("../../keys/alice_key.pem");
    
    $reqMessage = new WSMessage($reqPayloadString,
                                array("to" => "http://localhost/samples/security/secure_mtom/encryption/service.php",
                                      "action" => "http://wso2.org/upload",
                                      "attachments" => array("myid1" => $f)));
    
    $sec_array = array("encrypt" => TRUE,
                       "algorithmSuite" => "Basic256Rsa15",
                       "securityTokenReference" => "IssuerSerial");
    
    $policy = new WSPolicy(array("security" => $sec_array));
    $sec_token = new WSSecurityToken(array("privateKey" => $pvt_key,
                                           "receiverCertificate" => $rec_cert));
    
    $client = new WSClient(array("useWSA" => TRUE,
                                 "useMTOM" => TRUE,
                                 "policy" => $policy,
                                 "securityToken" => $sec_token));
				
    $resMessage = $client->request($reqMessage);
    
    printf("Response = %s \n", $resMessage->str);

} catch (Exception $e) {

	if ($e instanceof WSFault) {
		printf("Soap Fault: %s\n", $e->Reason);
	} else {
		printf("Message = %s\n",$e->getMessage());
	}

}
?>


MTOM upload client with signing enabled
Run client | WSDL | show client code | show server code

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function getAttachment($inMessage) {

	$cid2stringMap = $inMessage->attachments;
	$cid2contentMap = $inMessage->cid2contentType;
	$imageName;
	$file_saved = 0;

	foreach($cid2stringMap as $i=>$value){
		$f = $cid2stringMap[$i];
		$contentType = $cid2contentMap[$i];
		if(strcmp($contentType,"image/jpeg") ==0){
			$imageName = $i."."."jpg";
			$file_saved = file_put_contents("/tmp/".$imageName, $f);
		}
	}

	if($file_saved){
		$resPayload = <<<XML
<ns1:response xmlns:ns1="http://wso2.org/wsfphp/samples/mtom">Image Saved</ns1:response>
XML;
	}
	else{
		$resPayload = <<<XML
<ns1:response xmlns:ns1="http://wso2.org/wsfphp/samples/mtom">Image Saving Failed</ns1:response>
XML;
	}

	$returnMessage = new WSMessage($resPayload);

	return $returnMessage;
}
$pub_key = ws_get_cert_from_file("../../keys/alice_cert.cert");

$pub_key = ws_get_cert_from_file("../../keys/alice_cert.cert");
$pvt_key = ws_get_key_from_file("../../keys/bob_key.pem");

$policy_xml = file_get_contents("policySignOnlyMtom.xml");
$policy = new WSPolicy($policy_xml);

$sec_token = new WSSecurityToken(array("privateKey" => $pvt_key,
                                       "receiverCertificate" =>$pub_key));

$actions = array("http://wso2.org/upload" => "upload");
$operations = array("upload" => "getAttachment");

$server = new WSService(array(
                "operations" => $operations,
				"actions" => $actions, 
                "requestXOP"=>TRUE,
				"policy" => $policy,
				"securityToken" => $sec_token));

$server->reply();

?>



<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

$reqPayloadString = <<<XML
<ns1:upload xmlns:ns1="http://wso2.org/wsfphp/samples/mtom">
               <ns1:fileName>test.jpg</ns1:fileName>
               <ns1:image xmlmime:contentType="image/jpeg" xmlns:xmlmime="http://www.w3.org/2004/06/xmlmime">
                  <xop:Include xmlns:xop="http://www.w3.org/2004/08/xop/include" href="cid:myid1"></xop:Include>
               </ns1:image>
</ns1:upload>
XML;

try {
	$f = file_get_contents("../../../resources/axis2.jpg");

	$reqMessage = new WSMessage($reqPayloadString,
	array("to" => "http://localhost/samples/security/secure_mtom/signing/service.php",
              "action" => "http://wso2.org/upload",
              "attachments" => array("myid1" => $f)));

	$my_cert = ws_get_cert_from_file("../../keys/alice_cert.cert");
	$my_key = ws_get_key_from_file("../../keys/alice_key.pem");
	$rec_cert = ws_get_cert_from_file("../../keys/bob_cert.cert");

	$policy_xml = file_get_contents("policySignOnlyMtom.xml");

	$policy = new WSPolicy($policy_xml);
	$sec_token = new WSSecurityToken(array("privateKey" => $my_key,
                                           "certificate" => $my_cert,
                                           "receiverCertificate" => $rec_cert));

	$client = new WSClient(array("useMTOM" => TRUE,
                                     "useSOAP" => "1.1",
                                     "useWSA" => TRUE,
                                     "policy" => $policy,
                                     "securityToken" => $sec_token));

	$resMessage = $client->request($reqMessage);
	echo $resMessage->str."\n";

} catch (Exception $e) {
	if ($e instanceof WSFault) {
		printf("Soap Fault: %s\n", $e->Code);
		printf("Soap FaultReason: %s\n", $e->Reason);
	} else {
		printf("Message = %s\n",$e->getMessage());
	}
}
?>


Secure Conversation - Scenario1
Run client | WSDL | show client code | show server code | show policy code | show sts policy code

<wsp:Policy xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
  <wsp:ExactlyOne>
    <wsp:All>
      <sp:SymmetricBinding xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
        <wsp:Policy>
          <sp:EncryptionToken>
            <wsp:Policy>
              <sp:SecureConversationToken sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/Never">
                <wsp:Policy>
                  <sp:SC10SecurityContextToken/>
                  <sp:BootstrapPolicy>
                    <wsp:Policy xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
                      <wsp:ExactlyOne>
                        <wsp:All>
                          <sp:AsymmetricBinding xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
                            <wsp:Policy>
                              <sp:InitiatorToken>
                                <wsp:Policy>
                                  <sp:X509Token sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/AlwaysToRecipient">
                                    <wsp:Policy>
                                      <sp:WssX509V3Token10/>
                                    </wsp:Policy>
                                  </sp:X509Token>
                                </wsp:Policy>
                              </sp:InitiatorToken>
                              <sp:RecipientToken>
                                <wsp:Policy>
                                  <sp:X509Token sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/Never">
                                    <wsp:Policy>
                                      <sp:WssX509V3Token10/>
                                    </wsp:Policy>
                                  </sp:X509Token>
                                </wsp:Policy>
                              </sp:RecipientToken>
                              <sp:Layout>
                                <wsp:Policy>
                                  <sp:Strict/>
                                </wsp:Policy>
                              </sp:Layout>
                              <sp:IncludeTimestamp/>
                            </wsp:Policy>
                          </sp:AsymmetricBinding>
                          <rampc:RampartConfig xmlns:rampc="http://ws.apache.org/rampart/c/policy">
                            <rampc:TimeToLive>360</rampc:TimeToLive>
                          </rampc:RampartConfig>
                        </wsp:All>
                      </wsp:ExactlyOne>
                    </wsp:Policy>

                  </sp:BootstrapPolicy>
                </wsp:Policy>
              </sp:SecureConversationToken>
            </wsp:Policy>
          </sp:EncryptionToken>
          <sp:SignatureToken>
            <wsp:Policy>
              <sp:SecureConversationToken sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/Never">
                <wsp:Policy>
                  <sp:SC10SecurityContextToken/>
                  <sp:BootstrapPolicy>
                    <wsp:Policy xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
                      <wsp:ExactlyOne>
                        <wsp:All>
                          <sp:AsymmetricBinding xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
                            <wsp:Policy>
                              <sp:InitiatorToken>
                                <wsp:Policy>
                                  <sp:X509Token sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/AlwaysToRecipient">
                                    <wsp:Policy>
                                      <sp:WssX509V3Token10/>
                                    </wsp:Policy>
                                  </sp:X509Token>
                                </wsp:Policy>
                              </sp:InitiatorToken>
                              <sp:RecipientToken>
                                <wsp:Policy>
                                  <sp:X509Token sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/Never">
                                    <wsp:Policy>
                                      <sp:WssX509V3Token10/>
                                    </wsp:Policy>
                                  </sp:X509Token>
                                </wsp:Policy>
                              </sp:RecipientToken>
                              <sp:Layout>
                                <wsp:Policy>
                                  <sp:Strict/>
                                </wsp:Policy>
                              </sp:Layout>
                              <sp:IncludeTimestamp/>
                            </wsp:Policy>
                          </sp:AsymmetricBinding>
                          <rampc:RampartConfig xmlns:rampc="http://ws.apache.org/rampart/c/policy">
                            <rampc:TimeToLive>360</rampc:TimeToLive>
                          </rampc:RampartConfig>
                        </wsp:All>
                      </wsp:ExactlyOne>
                    </wsp:Policy>

                  </sp:BootstrapPolicy>
                </wsp:Policy>
              </sp:SecureConversationToken>
            </wsp:Policy>
          </sp:SignatureToken>
          <sp:AlgorithmSuite>
            <wsp:Policy>
              <sp:Basic256/>
            </wsp:Policy>
          </sp:AlgorithmSuite>
          <sp:Layout>
            <wsp:Policy>
              <sp:Strict/>
            </wsp:Policy>
          </sp:Layout>
          <sp:IncludeTimestamp/>
          <sp:OnlySignEntireHeadersAndBody/>
          <sp:EncryptSignature/>
        </wsp:Policy>
      </sp:SymmetricBinding>
      <sp:SignedSupportingTokens xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
        <wsp:Policy>
          <sp:UsernameToken sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/Always"/>
        </wsp:Policy>
      </sp:SignedSupportingTokens>
      <sp:Wss10 xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
        <wsp:Policy>
          <sp:MustSupportRefKeyIdentifier/>
          <sp:MustSupportRefEmbeddedToken/>
          <sp:MustSupportRefIssuerSerial/>
        </wsp:Policy>
      </sp:Wss10>
      <sp:SignedParts xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
        <sp:Body/>
        <sp:Header Namespace="http://www.w3.org/2005/08/addressing"/>
      </sp:SignedParts>
      <sp:EncryptedParts xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
        <sp:Body/>
      </sp:EncryptedParts>
    </wsp:All>
  </wsp:ExactlyOne>
</wsp:Policy>



<wsp:Policy xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
    <wsp:ExactlyOne>
        <wsp:All>
          <sp:SymmetricBinding xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
            <wsp:Policy>
                <sp:ProtectionToken>
                    <wsp:Policy>
                        <sp:X509Token sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/Never">
                            <wsp:Policy>
                                <sp:RequireDerivedKeys/>
                                <sp:RequireThumbprintReference/>
                                <sp:WssX509V3Token10/>
                            </wsp:Policy>
                        </sp:X509Token>
                    </wsp:Policy>
                </sp:ProtectionToken>
                <sp:AlgorithmSuite>
                    <wsp:Policy>
                        <sp:Basic256/>
                    </wsp:Policy>
                </sp:AlgorithmSuite>
                <sp:Layout>
                    <wsp:Policy>
                        <sp:Strict/>
                    </wsp:Policy>
                </sp:Layout>
                <sp:IncludeTimestamp/>
                <sp:EncryptSignature/>
                <sp:OnlySignEntireHeadersAndBody/>
            </wsp:Policy>
        </sp:SymmetricBinding> 
            <sp:SignedSupportingTokens xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
            <wsp:Policy>
                <sp:UsernameToken sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/Always"/>
            </wsp:Policy>
            </sp:SignedSupportingTokens>
            <sp:Wss10 xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
                <wsp:Policy>
                    <sp:MustSupportRefKeyIdentifier/>
                    <sp:MustSupportRefEmbeddedToken/>
                    <sp:MustSupportRefIssuerSerial/>
                </wsp:Policy>
            </sp:Wss10>
            <sp:EncryptedParts xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
                <sp:Body/>
            </sp:EncryptedParts>
            <sp:SignedParts xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
                <sp:Body/>
            </sp:SignedParts>
        </wsp:All>
    </wsp:ExactlyOne>
</wsp:Policy>


<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function echoFunction($inMessage) {

    $returnMessage = new WSMessage($inMessage->str);

    return $returnMessage;
}

function sct_delete_callback($sct_id,$sct_id_type)
{

}

function sct_store_callback($sct_str, $global_id,$local_id) {
    
    if (stristr(PHP_OS, 'WIN')) {
        $store_file = "sct.content";
    }else{
        $store_file = "/tmp/sct.content";
    }
    
    $fp_store_file_w = fopen($store_file, "a");
    if(flock($fp_store_file_w, LOCK_EX)) {
        if(!is_null($global_id)){
            fwrite($fp_store_file_w, $global_id.'|'.$sct_str.'!');
        }
        if(!is_null($local_id)){
            fwrite($fp_store_file_w,$local_id.'|'.$sct_str.'!');
        }
        flock($fp_store_file_w, LOCK_UN);
    } else {
        echo "Couldn't lock the ".$store_file." for writing!";
    }
    fclose($fp_store_file_w);
    return TRUE;
}

function sct_get_callback($sct_id,$sct_id_type, $is_encryption)
{
    if (stristr(PHP_OS, 'WIN')) {
        $sct_file = "sct.content";
    }else{
        $sct_file = "/tmp/sct.content";
    }
    $sct_array = array();   
    $sct_id_array = array();    
    
    clearstatcache();

    if(file_exists($sct_file))
    {
        $length = filesize($sct_file);
        $fp_rf = fopen($sct_file, "r");
        if(flock($fp_rf, LOCK_SH)) {
            $content = fread($fp_rf, $length);
            flock($fp_rf, LOCK_UN);
            $tok_rec = strtok($content, '!');
            $i = 0;
            while($tok_rec) {
                $msg_id_sct_str = $tok_rec;
                $sct_array[$i] = $msg_id_sct_str;
                $tok_rec = strtok('!');
                $i++;
            }
        } else {
            echo "Couldn't lock the ".$sct_file." for reading!";
        }
        fclose($fp_rf);
    }
    foreach($sct_array as $sctidvalue)
    {
        $tok1 = strtok($sctidvalue,'|');
        $tok2 = strtok('|');
        $sct_id_array[$tok1] = $tok2;
    }

    if(array_key_exists($sct_id, $sct_id_array))
    {
        return $sct_id_array[$sct_id];
    }
    return NULL;
}

$operations = array("echoString" => "echoFunction","SecConv10Issue"=>"echoFunction");
$actions = array("http://wso2.org/wsfphp/samples/echoString" => "echoString",
                "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/SCT" => "SecConv10Issue");
$policy_xml = file_get_contents("policy.xml");
$policy = new WSPolicy($policy_xml);

$policy_xml = file_get_contents("sts_policy.xml");
$sts_policy = new WSPolicy($policy_xml);

$rec_cert = ws_get_cert_from_file("../../keys/alice_cert.cert");
$pvt_key = ws_get_key_from_file("../../keys/bob_key.pem");

$security_token = new WSSecurityToken(array("user" => "Raigama",
                                            "password" => "RaigamaPW",
                                            "passwordType" => "Digest",
                        "storeSCTCallback" => "sct_store_callback",
                        "getSCTCallback" => "sct_get_callback",
                        "privateKey" => $pvt_key, 
                        "receiverCertificate" => $rec_cert,
                            "deleteSCTCallback"=>"sct_delete_callback"));


$svr = new WSService(array("operations" => $operations,
                           "actions" => $actions,
               "opPolicies"=>array("echoString"=>$policy, "SecConv10Issue"=>$sts_policy),
               "useOwnSTS"=>true,
                           "securityToken" => $security_token));
        
$svr->reply();

?>



<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


$reqPayloadString = <<<XML
<ns1:echo xmlns:ns1="http://wso2.org/wsfphp/samples"><text>Hello World!</text></ns1:echo>
XML;

function sct_delete_callback($sct_id,$sct_id_type)
{

}

function sct_store_callback($sct_str, $global_id,$local_id) {
    if (stristr(PHP_OS, 'WIN')) {
        $store_file = "sct_client.content";
    }else{
        $store_file = "/tmp/sct_client.content";
    }
       
    $fp_store_file_w = fopen($store_file, "a");
    if(flock($fp_store_file_w, LOCK_EX)) {
        if(!is_null($global_id)){
            fwrite($fp_store_file_w, $global_id.'|'.$sct_str.'!');
        }
        if(!is_null($local_id)){
            fwrite($fp_store_file_w,$local_id.'|'.$sct_str.'!');
        }
        flock($fp_store_file_w, LOCK_UN);    
    } else {
        echo "Couldn't lock the ".$store_file." for writing!";
    }
    fclose($fp_store_file_w);
    return TRUE;
}

function sct_get_callback($sct_id,$sct_id_type, $is_encryption)
{

    if (stristr(PHP_OS, 'WIN')) {
        $sct_file = "sct_client.content";
    }else{
        $sct_file = "/tmp/sct_client.content";
    }
    $sct_array = array();    
    $sct_id_array = array();    
    
    clearstatcache(); 
        
    if(file_exists($sct_file))
    {
        $length = filesize($sct_file);
        $fp_rf = fopen($sct_file, "r");
        if(flock($fp_rf, LOCK_EX)) {
        $content = fread($fp_rf, $length);
            flock($fp_rf, LOCK_UN);
            $tok_rec = strtok($content, '!');
            $i = 0;
        while($tok_rec) {
                $msg_id_sct_str = $tok_rec;
                $sct_array[$i] = $msg_id_sct_str;
                $tok_rec = strtok('!');
                $i++;
            }
        } else {
            echo "Couldn't lock the ".$sct_file." for reading!";
        }
        fclose($fp_rf);
    }

    foreach($sct_array as $sctidvalue)
    {
        $tok1 = strtok($sctidvalue,'|');
        $tok2 = strtok('|');
    $sct_id_array[$tok1] = $tok2;
    }
    
    if(array_key_exists($sct_id, $sct_id_array))
    {
        return $sct_id_array[$sct_id];
    }
    return NULL;
}

try {
    $rec_cert = ws_get_cert_from_file("../../keys/bob_cert.cert");
    $pvt_key = ws_get_key_from_file("../../keys/alice_key.pem");

    $reqMessage = new WSMessage($reqPayloadString,
        array(
            "to"=>"http://localhost/samples/security/secure_conversation/scenario1/service.php",
            "action" => "http://wso2.org/wsfphp/samples/echoString")
              );
    $policy_xml = file_get_contents("client_policy.xml");
    $policy = new WSPolicy($policy_xml);
    $security_token = new WSSecurityToken(array("user" => "Raigama",
                                                "password" => "RaigamaPW",
                                                "passwordType" => "Digest",
                                                "storeSCTCallback" => "sct_store_callback",
                                                "getSCTCallback" => "sct_get_callback",
                                                "privateKey" => $pvt_key, 
                                                "receiverCertificate" => $rec_cert,
                                                "deleteSCTCallback"=>"sct_delete_callback"));
    
    $client = new WSClient(array("useWSA" => TRUE,
                                 "policy" => $policy,
                                 "securityToken" => $security_token));
                
    $resMessage = $client->request($reqMessage);
    
    printf("Response = %s \n", $resMessage->str);

} catch (Exception $e) {

    if ($e instanceof WSFault) {
        printf("Soap Fault: %s\n", $e->Reason);
    } else {
        printf("Message = %s\n",$e->getMessage());
    }

}
?>


Secure Conversation - Scenario2
Run client | WSDL | show client code | show server code | show policy code

<wsp:Policy xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
  <wsp:ExactlyOne>
    <wsp:All>
      <sp:SymmetricBinding xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
        <wsp:Policy>
          <sp:EncryptionToken>
            <wsp:Policy>
              <sp:SecureConversationToken sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/Never">
                <wsp:Policy>
                  <sp:SC10SecurityContextToken/>
                  <sp:BootstrapPolicy>
                    <wsp:Policy xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
                      <wsp:ExactlyOne>
                        <wsp:All>
                          <sp:AsymmetricBinding xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
                            <wsp:Policy>
                              <sp:InitiatorToken>
                                <wsp:Policy>
                                  <sp:X509Token sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/AlwaysToRecipient">
                                    <wsp:Policy>
                                      <sp:WssX509V3Token10/>
                                    </wsp:Policy>
                                  </sp:X509Token>
                                </wsp:Policy>
                              </sp:InitiatorToken>
                              <sp:RecipientToken>
                                <wsp:Policy>
                                  <sp:X509Token sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/Never">
                                    <wsp:Policy>
                                      <sp:WssX509V3Token10/>
                                    </wsp:Policy>
                                  </sp:X509Token>
                                </wsp:Policy>
                              </sp:RecipientToken>
                              <sp:Layout>
                                <wsp:Policy>
                                  <sp:Strict/>
                                </wsp:Policy>
                              </sp:Layout>
                              <sp:IncludeTimestamp/>
                            </wsp:Policy>
                          </sp:AsymmetricBinding>
                          <rampc:RampartConfig xmlns:rampc="http://ws.apache.org/rampart/c/policy">
                            <rampc:TimeToLive>360</rampc:TimeToLive>
                          </rampc:RampartConfig>
                        </wsp:All>
                      </wsp:ExactlyOne>
                    </wsp:Policy>

                  </sp:BootstrapPolicy>
                </wsp:Policy>
              </sp:SecureConversationToken>
            </wsp:Policy>
          </sp:EncryptionToken>
          <sp:SignatureToken>
            <wsp:Policy>
              <sp:SecureConversationToken sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/Never">
                <wsp:Policy>
                  <sp:SC10SecurityContextToken/>
                  <sp:BootstrapPolicy>
                    <wsp:Policy xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
                      <wsp:ExactlyOne>
                        <wsp:All>
                          <sp:AsymmetricBinding xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
                            <wsp:Policy>
                              <sp:InitiatorToken>
                                <wsp:Policy>
                                  <sp:X509Token sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/AlwaysToRecipient">
                                    <wsp:Policy>
                                      <sp:WssX509V3Token10/>
                                    </wsp:Policy>
                                  </sp:X509Token>
                                </wsp:Policy>
                              </sp:InitiatorToken>
                              <sp:RecipientToken>
                                <wsp:Policy>
                                  <sp:X509Token sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/Never">
                                    <wsp:Policy>
                                      <sp:WssX509V3Token10/>
                                    </wsp:Policy>
                                  </sp:X509Token>
                                </wsp:Policy>
                              </sp:RecipientToken>
                              <sp:Layout>
                                <wsp:Policy>
                                  <sp:Strict/>
                                </wsp:Policy>
                              </sp:Layout>
                              <sp:IncludeTimestamp/>
                            </wsp:Policy>
                          </sp:AsymmetricBinding>
                          <rampc:RampartConfig xmlns:rampc="http://ws.apache.org/rampart/c/policy">
                            <rampc:TimeToLive>360</rampc:TimeToLive>
                          </rampc:RampartConfig>
                        </wsp:All>
                      </wsp:ExactlyOne>
                    </wsp:Policy>

                  </sp:BootstrapPolicy>
                </wsp:Policy>
              </sp:SecureConversationToken>
            </wsp:Policy>
          </sp:SignatureToken>
          <sp:AlgorithmSuite>
            <wsp:Policy>
              <sp:Basic256/>
            </wsp:Policy>
          </sp:AlgorithmSuite>
          <sp:Layout>
            <wsp:Policy>
              <sp:Strict/>
            </wsp:Policy>
          </sp:Layout>
          <sp:IncludeTimestamp/>
          <sp:OnlySignEntireHeadersAndBody/>
          <sp:EncryptSignature/>
        </wsp:Policy>
      </sp:SymmetricBinding>
      <sp:SignedSupportingTokens xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
        <wsp:Policy>
          <sp:UsernameToken sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/Always"/>
        </wsp:Policy>
      </sp:SignedSupportingTokens>
      <sp:Wss10 xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
        <wsp:Policy>
          <sp:MustSupportRefKeyIdentifier/>
          <sp:MustSupportRefEmbeddedToken/>
          <sp:MustSupportRefIssuerSerial/>
        </wsp:Policy>
      </sp:Wss10>
      <sp:SignedParts xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
        <sp:Body/>
        <sp:Header Namespace="http://www.w3.org/2005/08/addressing"/>
      </sp:SignedParts>
      <sp:EncryptedParts xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
        <sp:Body/>
      </sp:EncryptedParts>
    </wsp:All>
  </wsp:ExactlyOne>
</wsp:Policy>



<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


$reqPayloadString = <<<XML
<ns1:echo xmlns:ns1="http://wso2.org/wsfphp/samples"><text>Hello World!</text></ns1:echo>
XML;

function sct_delete_callback($sct_id,$sct_id_type)
{

}

function sct_store_callback($sct_str, $global_id,$local_id) {

    if (stristr(PHP_OS, 'WIN')) {
        $store_file = "sct_client.content";
    }else{
        $store_file = "/tmp/sct_client.content";
    }
       
    $fp_store_file_w = fopen($store_file, "a");
    if(flock($fp_store_file_w, LOCK_EX)) {
        if(!is_null($global_id)){
            fwrite($fp_store_file_w, $global_id.'|'.$sct_str.'!');
        }else if(!is_null($local_id)){
            fwrite($fp_store_file_w,$local_id.'|'.$sct_str.'!');
        }
        flock($fp_store_file_w, LOCK_UN);
    } else {
        echo "Couldn't lock the ".$store_file." for writing!";
    }
    fclose($fp_store_file_w);
    return TRUE;
}

function sct_get_callback($sct_id,$sct_id_type, $is_encryption)
{

    if (stristr(PHP_OS, 'WIN')) {
        $sct_file = "sct_client.content";
    }else{
        $sct_file = "/tmp/sct_client.content";
    }
    $sct_array = array();    
    $sct_id_array = array();    
    
    clearstatcache(); 
        
    if(file_exists($sct_file))
    {
        $length = filesize($sct_file);
        $fp_rf = fopen($sct_file, "r");
        if(flock($fp_rf, LOCK_EX)) {
        $content = fread($fp_rf, $length);

            flock($fp_rf, LOCK_UN);
            $tok_rec = strtok($content, '!');
            $i = 0;
        while($tok_rec) {
                $msg_id_sct_str = $tok_rec;
                $sct_array[$i] = $msg_id_sct_str;
                $tok_rec = strtok('!');
                $i++;
            }
        } else {
            echo "Couldn't lock the ".$sct_file." for reading!";
        }
        fclose($fp_rf);
    }

    foreach($sct_array as $sctidvalue)
    {
        $tok1 = strtok($sctidvalue,'|');
        $tok2 = strtok('|');
    $sct_id_array[$tok1] = $tok2;
    }
    
    if(array_key_exists($sct_id, $sct_id_array))
    {
        return $sct_id_array[$sct_id];
    }
    return NULL;
}

try {

    $reqMessage = new WSMessage($reqPayloadString,
        array(
            "to"=>"http://localhost/samples/security/secure_conversation/scenario2/service.php",
            "action" => "http://wso2.org/wsfphp/samples/echoString")
              );
    $policy_xml = file_get_contents("policy.xml");
    $policy = new WSPolicy($policy_xml);
    $security_token = new WSSecurityToken(array("user" => "Raigama",
                                                "password" => "RaigamaPW",
                                                "passwordType" => "Digest",
                                                "storeSCTCallback" => "sct_store_callback",
                                                "getSCTCallback" => "sct_get_callback",
                                                "deleteSCTCallback"=>"sct_delete_callback"));
    
    $client = new WSClient(array("useWSA" => TRUE,
                                 "policy" => $policy,
                                 "securityToken" => $security_token));
                
    $resMessage = $client->request($reqMessage);
    
    printf("Response = %s \n", $resMessage->str);

} catch (Exception $e) {

    if ($e instanceof WSFault) {
        printf("Soap Fault: %s\n", $e->Reason);
    } else {
        printf("Message = %s\n",$e->getMessage());
    }

}
?>


<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function echoFunction($inMessage) {

    $returnMessage = new WSMessage($inMessage->str);

    return $returnMessage;
}

function sct_delete_callback($sct_id,$sct_id_type)
{

}

function sct_store_callback($sct_str, $global_id,$local_id) {
    
    if (stristr(PHP_OS, 'WIN')) {
        $store_file = "sct.content";
    }else{
        $store_file = "/tmp/sct.content";
    }
    $fp_store_file_w = fopen($store_file, "a");
    if(flock($fp_store_file_w, LOCK_EX)) {
        if(!is_null($global_id)){
            fwrite($fp_store_file_w, $global_id.'|'.$sct_str.'!');
        }
        if(!is_null($local_id)){
            fwrite($fp_store_file_w,$local_id.'|'.$sct_str.'!');
                }  
        flock($fp_store_file_w, LOCK_UN);
    } else {
        echo "Couldn't lock the ".$store_file." for writing!";
    }
    fclose($fp_store_file_w);
    return TRUE;
}

function sct_get_callback($sct_id,$sct_id_type, $is_encryption)
{
    if (stristr(PHP_OS, 'WIN')) {
        $sct_file = "sct.content";
    }else{
        $sct_file = "/tmp/sct.content";
    }
    $sct_array = array();   
    $sct_id_array = array();    
    
    clearstatcache();

    if(file_exists($sct_file))
    {
        $length = filesize($sct_file);
        $fp_rf = fopen($sct_file, "r");
        if(flock($fp_rf, LOCK_SH)) {
            $content = fread($fp_rf, $length);
            flock($fp_rf, LOCK_UN);
            $tok_rec = strtok($content, '!');
            $i = 0;
            while($tok_rec) {
                $msg_id_sct_str = $tok_rec;
                $sct_array[$i] = $msg_id_sct_str;
                $tok_rec = strtok('!');
                $i++;
            }
        } else {
            echo "Couldn't lock the ".$sct_file." for reading!";
        }
        fclose($fp_rf);
    }
    foreach($sct_array as $sctidvalue)
    {
        $tok1 = strtok($sctidvalue,'|');
        $tok2 = strtok('|');
        $sct_id_array[$tok1] = $tok2;
    }

    if(array_key_exists($sct_id, $sct_id_array))
    {
        return $sct_id_array[$sct_id];
    }
    return NULL;
}

$operations = array("echoString" => "echoFunction");
$actions = array("http://wso2.org/wsfphp/samples/echoString" => "echoString");
$policy_xml = file_get_contents("policy.xml");
$policy = new WSPolicy($policy_xml);

$security_token = new WSSecurityToken(array("user" => "Raigama",
                                            "password" => "RaigamaPW",
                                            "passwordType" => "Digest",
                        "storeSCTCallback" => "sct_store_callback",
                        "getSCTCallback" => "sct_get_callback",
                                    "deleteSCTCallback"=>"sct_delete_callback"));


$svr = new WSService(array("operations" => $operations,
                           "actions" => $actions,
               "opPolicies"=>array("echoString"=>$policy),
               "useOwnSTS"=>true,
                           "securityToken" => $security_token));
        
$svr->reply();

?>



Reliable Messaging Samples
Single Channel two way RM Client
Run client | WSDL | show client code | show server code

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function getAttachment($inMessage) {

    $cid2stringMap = $inMessage->attachments;
    $cid2contentMap = $inMessage->cid2contentType;
    $imageName;

    foreach($cid2stringMap as $i=>$value) {
        $f = $cid2stringMap[$i];
        $contentType = $cid2contentMap[$i];
        if(strcmp($contentType,"image/jpeg") ==0) {
            $imageName = $i."."."jpg";
		if(stristr(PHP_OS, 'WIN')){
		   file_put_contents($imageName, $f);
            }else{
                file_put_contents("/tmp/".$imageName, $f);
            }
        }
    }

$responsePayload = <<<XML
<ns1:response xmlns:ns1="http://wso2.org/wsfphp/samples/mtom">Image Saved</ns1:response>
XML;

    $responseMessage = new WSMessage($responsePayload);

    return $responseMessage;
}

$operations = array("upload" => "getAttachment");
$actions = array("http://wso2.org/wsfphp/samples/mtom" => "upload");

$server = new WSService(array( "operations" => $operations,
                               "actions" => $actions,
                               "requestXOP" => TRUE,
                               "reliable" => TRUE));
$server->reply();

?>



<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

$requestPayloadString = <<<XML
    <ns1:echoString xmlns:ns1="http://wso2.org/wsfphp/samples">
        <text>Hello World!</text>
    </ns1:echoString>
XML;

try {

    $requestMessage = new WSMessage($requestPayloadString,
            array( "action" => "http://wso2.org/wsfphp/samples/echoString"));

    $client = new WSClient(array( "to" => "http://localhost/samples/reliable/echo_service_rm.php",
                                  "reliable" => TRUE));

    $responseMessage = $client->request($requestMessage);
    if($responseMessage){
        echo $responseMessage->str;
    }
    
    $client->wait(10);  
    
} catch (Exception $e) {

    if ($e instanceof WSFault) {
        printf("Soap Fault: %s\n", $e->Reason);
    } else {
        printf("Message = %s\n",$e->getMessage());
    }
}
?>


Single Channel one way RM Service
WSDL (show code)

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

$reqPayloadString = <<<XML
    <ns1:echoString xmlns:ns1="http://wso2.org/wsfphp/samples">
        <text>Hello World!</text>
    </ns1:echoString>
XML;

function echoFunction($inMessage) {
    return new WSMessage($inMessage->str);
}

$operations = array( "echoString" => "echoFunction");
$actions = array( "http://wso2.org/wsfphp/samples/echoString" => "echoString");

$service = new WSService(array( "operations" => $operations,
                            "reliable"=>TRUE));
$service->reply();

?>


Single Channel two way RM Client sending an MTOM attachment
Run client (show code)

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

$requestPayloadString = <<<XML
<ns1:upload xmlns:ns1="http://wso2.org/wsfphp/samples/mtom">
    <ns1:fileName>test.jpg</ns1:fileName>
    <ns1:image xmlmime:contentType="image/jpeg" xmlns:xmlmime="http://www.w3.org/2004/06/xmlmime">
        <xop:Include xmlns:xop="http://www.w3.org/2004/08/xop/include" href="cid:myid1"></xop:Include>
    </ns1:image></ns1:upload>
XML;

try {
    $f = file_get_contents("../resources/axis2.jpg");

    $requestMessage = new WSMessage($requestPayloadString,
                               array( "to" => "http://localhost/samples/reliable/mtom_upload_service_rm.php",
                                      "action" => "http://wso2.org/wsfphp/samples/mtom",
                                      "attachments" => array("myid1" => $f)));

    $client = new WSClient(array( "useMTOM" => TRUE,
                                  "reliable" => TRUE));

    $requestMessage = $client->request($requestMessage);

    echo $requestMessage->str;

    /** wait 10 seconds for the requests to complete */
    $client->wait(10);

} catch (Exception $e) {
    if ($e instanceof WSFault) {
        printf("Soap Fault: %s\n", $e->code);
    } else {
        printf("Message = %s\n",$e->getMessage());
    }
}
?>


Single Channel one way RM Client
Run client | WSDL | show client code | show server code

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function pingFunction($inMessage) {
    return ;
}

$operations = array( "pingString" => "pingFunction" );
$actions = array( "http://wso2.org/wsfphp/samples/pingString" => "pingString");
$meps = array( "pingString" => "IN_ONLY" );

$svr = new WSService(array( "operations" => $operations,
                            "opMEP" => $meps,
                            "reliable"=>TRUE));
$svr->reply();

?>



<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

$requestPayloadString = <<<XML
	<ns1:pingString xmlns:ns1="http://wso2.org/wsfphp/samples">
		<text>Hello World!</text>
	</ns1:pingString>
XML;

try {

    $requestMessage = new WSMessage($requestPayloadString,
			array( "to" => "http://localhost/samples/reliable/ping_service_rm.php",
                   "action" => "http://wso2.org/wsfphp/samples/pingString"));

    $client = new WSClient(array( "reliable" => TRUE , "useWSA" => TRUE));
    
    $client->send($requestMessage);

    echo "Message Sent to the Endpoint";

    $client->wait(10);

} catch (Exception $e) {

	if ($e instanceof WSFault) {
		printf("Soap Fault: %s\n", $e->Reason);
	} else {
		printf("Message = %s\n",$e->getMessage());
	}
}
?>


RM 1.1. Client - Terminating the message using terminateOutgoingRM function
Run client (show code)

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


$reqPayloadString = <<<XML
    <ns1:echoString xmlns:ns1="http://wso2.org/wsfphp/samples">
        <text>Hello World!</text>
    </ns1:echoString>
XML;

try {

    $msg = new WSMessage($reqPayloadString,
            array("action" => "http://wso2.org/wsfphp/samples/echoString"));

    $client = new WSClient(array( "to"=>"http://localhost/samples/reliable/echo_service_rm.php",
                        "reliable"=>"1.1",
                        "willContinueSequence" => TRUE));
    $result = $client->request($msg);

    if($result){
    echo $result->str;
    }
    /** Terminate outgong rm function can be used to terminate the sequence only when using RM 1.1 */
    $client->terminateOutgoingRM();
    $client->wait(10);

} catch (Exception $e) {

    if ($e instanceof WSFault) {
        printf("Soap Fault: %s\n", $e->Reason);
    } else {
        printf("Message = %s\n",$e->getMessage());
    }
}
?>


RM 1.1. Client - Ping client
Run client (show code)

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

$requestPayloadString = <<<XML
    <ns1:pingString xmlns:ns1="http://wso2.org/wsfphp/samples">
        <text>Hello World!</text>
    </ns1:pingString>
XML;

try {

    $requestMessage = new WSMessage($requestPayloadString,
            array( "to" => "http://localhost/samples/reliable/ping_service_rm.php",
                   "action" => "http://wso2.org/wsfphp/samples/pingString"));

    $client = new WSClient(array( "reliable" => "1.1" , "useWSA" => TRUE));

    $client->send($requestMessage);

    echo "Message Sent to the Endpoint";

    $client->wait(10);

} catch (Exception $e) {

    if ($e instanceof WSFault) {
        printf("Soap Fault: %s\n", $e->Reason);
    } else {
        printf("Message = %s\n",$e->getMessage());
    }
}
?>

WSDL mode
WSDL mode Client using WSDL 1.1
Run client | WSDL | show client code | show server code

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function QueryPurchaseOrderFunction($pro_name, $quantity, $date, $orderNo) {


	$return_value = array("shipTo" => array("name" => "Jane Smith",
											"street" => "YorkStreet",
											"city" => "colombo", 
											"state" => "Sri Lanka", 
											"zip" => 32343),
	
                          "billTo" => array("name" => "John Smith", 
                          					"street" => "Maple Street", 
                          					"city" => "LA", "state" => "USA", 
                          					"zip" => 55432),
	
                          "product" => array("productId" => 2344, 
                          					"shippingDate" => date(20080101), 
                          					"status" => TRUE));
	return $return_value;
}

$operations = array("QueryPurchaseOrder" => "QueryPurchaseOrderFunction");

$svr = new WSService(array("wsdl"=>"sample_wsdl_11.wsdl",
                           "operations" => $operations));

$svr->reply();

?>



<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

try {

    $client = new WSClient(array("wsdl"=>"sample_wsdl_11.wsdl",
                                 ));

    $proxy = $client->getProxy();	

    $return_val =  $proxy->QueryPurchaseOrder(array("productName"=> "Testing",
                                             "quantity" => 234,
                                             "date" => "2003-12-34",
                                             "orderNo" => 345));  
      
    printf("<strong>Shipping address </strong><br/>");
    printf("Name : %s <br/>", $return_val["shipTo"]["name"]);
    printf("Street : %s <br/>", $return_val["shipTo"]["street"]);
    printf("City : %s <br/>", $return_val["shipTo"]["city"]);
    printf("State : %s <br/>", $return_val["shipTo"]["state"]);
    printf("Zip : %s <br/>", $return_val["shipTo"]["zip"]);
    
    printf("<br/><strong>Billing address </strong><br/>");
    printf("Name : %s <br/>", $return_val["billTo"]["name"]);
    printf("Street : %s <br/>", $return_val["billTo"]["street"]);
    printf("City : %s <br/>", $return_val["billTo"]["city"]);
    printf("State : %s <br/>", $return_val["billTo"]["state"]);
    printf("Zip : %s <br/>", $return_val["billTo"]["zip"]);
    
    printf("<br/><strong>Product info </strong><br/>");
    printf("Product ID : %s <br/>", $return_val["product"]["productId"]);
    printf("ShippingDate : %s <br/>", $return_val["product"]["shippingDate"]);
    printf("Status : %s <br/>", $return_val["product"]["status"]);
   

} catch (Exception $e) {

		printf("Message = %s\n",$e->getMessage());
}
?>


WSDL mode Client using WSDL 2.0
Run client | WSDL | show client code | show server code

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function GetPriceFunction($arg1, $arg2) {
    
    $return_value = array("Price" => 234.431);
    return $return_value;
}

$operations = array("GetPrice" => "GetPriceFunction");

$svr = new WSService(array("wsdl"=>"sample_wsdl_20.wsdl", 
                           "operations" => $operations));
        
$svr->reply();

?>



<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

try {

    $client = new WSClient(array("wsdl"=>"sample_wsdl_20.wsdl"));

    $proxy = $client->getProxy();	

    $return_val =  $proxy->GetPrice(array("ProductType"=> "Testing",
                                          "ItemNo" => 234));    
    printf("Price is : %s <br/>", $return_val["Price"]);

} catch (Exception $e) {
    if ($e instanceof WSFault) {
        printf("Soap Fault Reason: %s<br/>", $e->Reason);
        printf("Soap Fault Code: %s <br/>", $e->Code);
        
    } else {
        printf("Message = %s<br/>",$e->getMessage());
    }
  }
?>


Client demonstrating Addressing, MTOM
Run client | WSDL | show client code | show server code

<?php
$imageID = "1.jpg";
function submit($recvMsg) {
    global $imageID;
    $simplexml = new SimpleXMLElement($recvMsg->str);
    foreach ($simplexml->children("http://www.wso2.net/wsf/prototype") as $tag => $childNode) {
        foreach ($childNode->children("http://www.wso2.net/wsf/prototype") as $tag2 => $childNode2) {
            foreach ($childNode2->children("http://www.wso2.net/wsf/prototype") as $tag3 => $childNode3) {
                if (strcmp($tag3, "strElement") == 0){
                    $imageID = $childNode3;
                }
            }
        }
    }

    $resPayloadString = <<<XML
    <ns1:submitResponse xmlns:ns1="http://www.wso2.net/wsf">
    <pro:testDocOut xmlns:pro="http://www.wso2.net/wsf/prototype">
            <pro:intStrElement>
                    <pro:intElement>12</pro:intElement>
                    <pro:strElement>$imageID</pro:strElement>
            </pro:intStrElement>
            <pro:binaryElement>
            <xop:Include xmlns:xop="http://www.w3.org/2004/08/xop/include" href="cid:a"></xop:Include>
	    </pro:binaryElement>	
            <pro:anyElement>
                    <test123>1 2 3 4 5 6</test123>
            </pro:anyElement>
    </pro:testDocOut>
    </ns1:submitResponse>
XML;
      
  $f = file_get_contents("./service_resources/".$imageID); 	
  return new WSMessage($resPayloadString , 
		array(
			"attachments"=>array("a"=>$f),
                  "defaultAttachmentContentType"=>"image/jpeg"
		     ));
} 
$actions = array("http://www.wso2.net/products/wsf_php/demo/submit"=>"submit");
$ops = array("submit"=>"submit");
$service = new WSService(array("operations"=>$ops,
                               "actions"=>$actions,
                               "useMTOM"=>TRUE));
$service->reply();

?>


<?php

$scenario = $_POST["scenario"];
$epr = $_POST["epr"];
$imageID = 1;
$qosAddr = $_POST["qosAddr"];
$qosMTOM;
$qosRM;

session_start();
$message = "";
if (!isset($_SESSION['message'])) {
		    $_SESSION['message'] = "";
} else {
    if (isset($_POST['submit']) || !isset($_GET['imageID'])) {
       	$_SESSION['message'] = "";
    }
    $message = $_SESSION['message'];
}
?>

<html>
	<head>
		<title>WSF/PHP MTOM ADDRESSING</title>
	</head>
	<body>
	<form method="post" action="<?php echo $PHP_SELF;?>">
	<table cols="2" border="1" cellpadding="10" cellspacing="0" align="center" width="100%">
	<tr>
	    <td>
	<h4>Request Reply Senario</h4>

<h4>Target Endpoint</h4>
Endpoint:<input type="text" size="60" maxlength="60" name="epr" value="http://localhost/samples/sudoku/sudoku_service.php"><br />
<h4>WS-*</h4>
Addressing : <input type="checkbox" value="Addressing" name="qosAddr"><br/>
XOP/MTOM : <input type="checkbox" checked="true" disabled value="MTOM" name="qosMTOM"><br/>
<!--Reliable Messaging : <input type="checkbox" value="RM" name="qosRM"><br /-->
<br />
<br />
<input type="submit" value="submit" name="submit">
</form>
<br/>
<br/>
<?php
echo "<form method=\"post\" action=\"http://".$_SERVER['SERVER_NAME'].":".$_SERVER["SERVER_PORT"]."/samples/sudoku/sudoku_client.php?act=delete\">";
echo "<input type=\"submit\" value=\"Reset \" name=\"reset\">";
echo "</form>";
echo "</td>";
?>

<?php

if (isset($_POST['submit']) || isset($_GET['imageID'])) {
if (isset($_GET['imageID'])){
    $imageID = $_GET['imageID'];
    $epr = $_GET['epr'];
    $qosAddr = $_GET['qosAddr'];
}


echo "<td>";

echo "<h2> Here are the Results</h2> <br/><br/>";

$reqPayloadString = <<<XML
<ns1:submit xmlns:ns1="http://www.wso2.net/wsf">
<pro:testDocIn xmlns:pro="http://www.wso2.net/wsf/prototype">
        <pro:intStrElement>
                <pro:intElement>12</pro:intElement>
                <pro:strElement>$imageID.jpg</pro:strElement>
        </pro:intStrElement>
        <pro:binaryElement/>
        <pro:anyElement>
                <test123>1 2 3 4 5 6</test123>
        </pro:anyElement>
</pro:testDocIn>
</ns1:submit>
XML;


try {
    $msg = new WSMessage($reqPayloadString,
			array("to"=>$epr,
			"action"=>"http://www.wso2.net/products/wsf_php/demo/submit"));
    
    $client_options = array();
    $client_options["useMTOM"] = TRUE;
    $client_options["responseXOP"] = TRUE;
    if($qosAddr){
    	$client_options["useWSA"] = TRUE;
    }

    $client = new WSClient($client_options);

    $message = $message.">>> Sending SOAP request to ".$epr." requesting for image ".$imageID.".jpg<br/>";
    $resMsg = $client->request($msg);
   
    $cid2str = $resMsg->attachments;
    $cid2cnt = $resMsg->cid2contentType;	    
    if($cid2str){
    foreach($cid2str as $i=>$value){
	$f = $cid2str[$i];
	file_put_contents("./client_resources/".$imageID.".jpg", $f);
    }
    }   
    
    $message = $message."<<< Saved image ".$imageID.".jpg received<br/>";
    $sentMsg = $client->getLastRequest();
    $recvMsg = $client->getLastResponse();
    echo "<strong>Showing solution blocks ".$imageID." out of 9</strong>";
    echo "<table><tr>";
    for ($counter = 1; $counter <= $imageID; $counter++) {
        echo "<td><img src='./client_resources/".$counter.".jpg'/></td>";
        if (($counter % 3) == 0 ) {
            echo "</tr><tr>";
        }
    }
    echo "</tr></table>";

    if ($imageID < 9) {
        $imageID += 1;
        echo "<script type='text/javascript'>";
        echo "function reload() {";
        echo "window.location=";
        echo "'http://".$_SERVER['SERVER_NAME'].":".$_SERVER["SERVER_PORT"]."/samples/sudoku/sudoku_client.php";
        echo "?imageID=".$imageID."&epr=".$epr."&qosAddr=".$qosAddr."';}";
        echo "setTimeout('reload()',1000)";
        echo "</script>";
    }
  
} catch (Exception $e) {
    if ($e instanceof WSFault) {
        printf("Soap Fault: %s\n", $e->Reason);
    } else {
        printf("Message = %s\n",$e->getMessage());
    }

}
    
echo "</td>";
}
else {
echo "<td>.";
echo "</td>";
}
?>
</tr>
</table>
<?php
echo $message."<br/>";
echo "<strong>Showing Sent/Received Message </strong>";
echo "<table><tr>";
echo "<td><textarea type=\"text\" rows=\"15\" cols=\"60\">";
echo $sentMsg."";
echo "</textarea></td>";
if($recvMsg)
{
echo "<td><textarea type=\"text\" rows=\"15\" cols=\"60\">";
echo $recvMsg."";
echo "</textarea></td>";	 
}
echo "</tr></table>";
$_SESSION['message'] = $message;
?>
</body>
</html>


Client by enabling HTTPS- Please refer README.SSL_CLIENT
Run client (show code)

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

$requestPayloadString = <<<XML
    <ns1:echoString xmlns:ns1="http://wso2.org/wsfphp/samples">
        <text>Hello World!</text>
    </ns1:echoString>
XML;

try {

    $client = new WSClient(array( "to" => "https://localhost/samples/echo_service.php",
                                  "CACert" => "./resources/cacert.pem"));
    $responseMessage = $client->request($requestPayloadString);
    echo $responseMessage->str;
        
} catch (Exception $e) {
    if ($e instanceof WSFault) {
        printf("Soap Fault: %s\n", $e->Code);
    } else {
        printf("Message = %s\n",$e->getMessage());
    }
}
?>


Flickr
Flickr client Note: This sample requires a valid flickr api key
Run client (show code)

<?php
/*
 * Copyright 2005,2008 WSO2, Inc. http://wso2.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


$requestPayloadString = <<<XML
<x:FlickrRequest xmlns:x="urn:flickr">
<method>flickr.test.echo</method>
<api_key>your key</api_key>
<name>cars</name>
</x:FlickrRequest>
XML;

try {

    $flicker_client = new WSClient(
        array("to" => "http://api.flickr.com/services/soap/"));

                
    $responseMessage = $flicker_client->request($requestPayloadString);
    
    printf("Response = %s <br>", htmlspecialchars($responseMessage->str));

} catch (Exception $e) {

    if ($e instanceof WSFault) {
        printf("Soap Fault: %s\n", $e->Reason);
    } else {
        printf("Message = %s\n",$e->getMessage());
    }

}
?>