<?php
include("AuthentParse.php");

/*This is the main class that will be used
  as data for the Authentify calls.

  see testXML.php for an example of this
  calss in use.

  Also see AuthentSend.php or AuthentComms.php for how it gets
  sent and retrieved.
 */

class Message{
  var $tsoid = null;
  var $application = null;
  var $licensekey = null;
  var $teid = null;
  var $sgid = null;
  var $asid = null;
  var $timestamp = null;
  var $replyTo = null;
  var $action = null;
  var $type = null;
  var $statusCode = null;
  var $statusText = null;
  var $data;

  var $dataNamespace = "xmlns:dat='http://xml.authentify.net/CommonDataSchema.xml'";
  var $dataPrefix    = "dat:";


  function Message($xml = ""){
    if(empty($xml)){
      $this->data = array();
    }else{
      $ap = new AuthentXMLParser(&$this);
      $ap->parse($xml);
      $ap->free();
    }
  }

  function toXML(){
    $header = "";
    if(isset($this->tsoid)){
      $header .= "      <tsoid>".$this->tsoid."</tsoid>\n";
    }
    if(isset($this->application)){
      $header .= "      <application>".$this->application."</application>\n";
    }
    if(isset($this->licensekey)){
      $header .= "      <licensekey>".$this->licensekey."</licensekey>\n";
    }
    if(isset($this->teid)){
      $header .= "      <teid>".$this->teid."</teid>\n";
    }
    if(isset($this->sgid)){
      $header .= "      <sgid>".$this->sgid."</sgid>\n";
    }
    if(isset($this->asid)){
      $header .= "      <asid>".$this->asid."</asid>\n";
    }
    if(isset($this->timestamp)){
      $header .= "      <timestamp>".$this->timestamp."</timestamp>\n";
    }
    if(isset($this->replyTo)){
      $header .= "      <replyTo>".$this->replyTo."</replyTo>\n";
    }

    $data = "";
    if(!empty($this->data)){
      foreach($this->data as $key => $value){
	$data .= $value->toXML("            ", $this->dataPrefix, $key);
	$data .="\n";
      }
    }


    $xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>
<AuthentXML xmlns = \"http://xml.authentify.net/MessageSchema.xml\" version = \"1.0\">
   <header>
%header%   </header>
   <body>
      <$this->type>\n";

    if(isset($this->action)){
      $xml .= "         <action>".$this->action."</action>\n";
    }

    if( !empty($data)){
      $xml .="         <data ".$this->dataNamespace.">
%data%         </data>\n";
    }

    if( isset($this->statusCode) || isset($this->statusText) ){
      $xml .= "         <status>\n";
      if( isset($this->statusCode) ){
	$xml .= "            <statusCode>".$this->statusCode."</statusCode>\n";
      }
      if( isset($this->statusText) ){
	$xml .= "            <statusText>".$this->statusText."</statusText>\n";
      }

      $xml .= "         </status>\n";
    }

    $xml .="      </$this->type>
   </body>
</AuthentXML>";
    //    $xml = str_replace("%type%", $this->type, $xml);
    $xml = str_replace("%header%", $header, $xml);
    $xml = str_replace("%data%", $data, $xml);
    return $xml;
  }

}


/*Node for the data section of XML

  Each node can have childNodes. This allows
  for constructs like the following:

  <data xmlns:dat="http://xml.authentify.net/commonDataSchema.xml">
   <namedData>
  	<dataItem name="Bob">7878</dataItem>
   </namedData>
  </data>

  This would look in the code like so:
  (This is condensed and would not work as is,  see
  testXML.php for a full example.)

  $msg = new Message();
  $msg->data["namedData"] = new DataNode();
  $dataItemParams = array();
  $dataItemParams["name"] = "Bob";
  $msg->data["namedData"]->childNodes["dataItem"] = new DataNode("7878", $dataItemParams);
*/

class DataNode{
  var $text;
  var $attributes;
  var $childNodes;
  var $extraIndent = "   ";

  function DataNode($text="", $atts=array()){
    $this->text = $text;
    $this->attributes = $atts;
    $this->childNodes = array();
  }

  function toXML($indent="", $prefix="", $name=""){
    $xml = "$indent<$prefix$name";
    foreach ($this->attributes as $key => $value) {
      $xml .= " $key=\"$value\"";
    }
    $xml .= ">".$this->text;
    if(!empty($this->childNodes)){
      $xml .= "\n";
      foreach ($this->childNodes as $key => $value) {
	$xml .= $value->toXML($indent.$this->extraIndent, $prefix, $key);
	$xml .= "\n";
      }
      $xml .= "$indent";
    }
    $xml .= "</$prefix$name>";
    return $xml;
  }
}


/*


function test(){
  //An Example Request XML and Receive XML to test with

  $reqxml ="<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>
<AuthentXML xmlns = \"http://xml.authentify.net/MessageSchema.xml\" version = \"1.0\">
   <header>
         <tsoid>Authentify_Test</tsoid>
         <application>Test</application>
         <asid>Rob_Wells_PayPal</asid>
   </header>
   <body>
      <request>
         <action>PhoneSession</action>
         <data xmlns:dat='http://xml.authentify.net/CommonDataSchema.xml'>
           <dat:confirmNumber>1234</dat:confirmNumber>
           <dat:phoneNumber>773-243-0300x337</dat:phoneNumber>
           <dat:name>
             <dat:firstName>Rob</dat:firstName>
             <dat:lastName>Wells</dat:lastName>
           </dat:name>
           <dat:address>
             <dat:streetAddress>8745 West Higgins Road</dat:streetAddress>
             <dat:postalCode>60631</dat:postalCode>
           </dat:address>
         </data>
      </request>
   </body>
</AuthentXML>
";

$recxml = "<?xml version=\"1.0\"?>
<AuthentXML xmlns=\"http://xml.authentify.net/MessageSchema.xml\" version=\"1.0\">
  <header>
    <tsoid>Authentify_Test</tsoid>
    <application>PayPalTest</application>
    <asid>Rob_Wells_PayPal</asid>
    <teid>b850d217-7e8b-4f36-9690-9f61489fafea</teid>
    <sgid>a75444d3-3dd4-44bc-9437-bcd61114f647</sgid>
    <replyTo>https://r2.authentify.net/s2s/default.asp</replyTo>
    <timestamp>2003-06-01T11:52:39Z</timestamp>
  </header>
  <body>
    <result>
      <action>PhoneSession</action>
      <data xmlns=\"http://xml.authentify.net/MessageSchema.xml\" xmlns:dat=\"http://xml.authentify.net/CommonDataSchema.xml\">
        <dat:zipExchangeDistance>7.838</dat:zipExchangeDistance>
        <dat:phoneLookupStatus>3612</dat:phoneLookupStatus>
        <dat:address>
          <dat:postalCode match=\"2\"/>
          <dat:streetAddress matchVal=\"2\"/>
        </dat:address>
        <dat:name>
          <dat:firstName match=\"1\"/>
          <dat:lastName match=\"0\"/>
        </dat:name>
        <dat:phoneValidityStatus>0</dat:phoneValidityStatus>
        <dat:States>RequestReceived+ParmsOK+DataLookup+LineAllocated</dat:States>
      </data>
      <status>
        <statusCode>3340</statusCode>
      </status>    ob_start();
    print_r($data);
    $output = ob_get_contents();
    ob_end_clean();
    </result>
  </body>
</AuthentXML>";

  //Create the AuthentXMLParser Object,  it is the central class for parsing XML's from Authentify (or to)
  // This is where the parser is initially set up.
  $aParser = new AuthentXMLParser();
  echo "--- Request XML Test ---<br>\n";

  //parse function does the actual parsing,  it takes the whole XML as a string
  //It returns a Message object,  see the Message definition above for available attributes
  $msg = $aParser->parse($reqxml);

  //Message will be null if something went wrong
  if($msg != null){

    //Here you see how attributes ar situated in the message.
    // The data attribute of message is an associative array of DataNode objects.
    // they are keyed on the tag name stripped of the namespace (which is
    // defined in the AuthentXMLParser class).  The DataNodes contain
    // two variables,  text, which is the text of the tag, and attributes
    // which is an associative array keyed on attribute name,  and value
    // being the attribute value.
    echo "Parse Complete<br>\nMessage was for ".$msg->tsoid." ".$msg->application.".<br>\nType of message was ".$msg->type.", status was ".$msg->statusCode."<br>\nMessage Data is :<br>\n";

    //Here we print the message using print_r
    printData($msg);

    echo "<br><br>\n".$msg->toXML();
  }else{
    echo "Parsing Failed";
  }

  //To Reuse the AuthentXMLParser Object you must reset it first,
  // otherwise the parser will throw errors.
  $aParser->reset();
  echo "<br>\n\n--- Received XML Test ---<br>\n";
  $msg = $aParser->parse($recxml);
  if($msg != null){
    echo "Parse Complete<br>\nMessage was for ".$msg->tsoid." ".$msg->application.".<br>\nType of message was ".$msg->type.", status was ".$msg->statusCode."<br>";
    //    array_walk($msg->data, "printNode");
    printData($msg);
  }else{
    echo "Parsing Failed";
  }

  $msg = new Message($recxml);
  if($msg != null){
    echo "Parse Complete<br>\nMessage was for ".$msg->tsoid." ".$msg->application.".<br>\nType of message was ".$msg->type.", status was ".$msg->statusCode."<br>";
    //    array_walk($msg->data, "printNode");
    printData($msg);
  }else{
    echo "Parsing Failed";
  }

}

function printData($data){
    ob_start();
    print_r($data);
    $output = ob_get_contents();
    ob_end_clean();
    $output = str_replace("\n", "<br>\n", $output);
    $output = str_replace(" ", "&nbsp;", $output);
    echo $output;

}
*/
?>
