<?php

# ----------------------------------------------------- #
#                 class cbNotification                  #
# ----------------------------------------------------- #

class cbNotification {

  private $dom;
  private $xpQuery;

  private $errorStack = array();

# -------------- private functions -------------------- #

  private function XPathQuery($queryStr) {

    if (!is_object($this->dom) ||
        !is_object($this->xpQuery))
      return false;

    if ($queryStr == '') {
      $this->AddError(__METHOD__."($queryStr)", 'Empty XPath Expression');
      return false;
    }

    $result = @$this->xpQuery->query($queryStr);

    if (!$result) {
      $this->AddError(__METHOD__."($queryStr)", 'Invalid XPath Expression');
      return false;
    }
    
    if ($result->length < 1)
      return false;
    
    return $result;
  }

  private function addError($title, $message) {
    return array_push($this->errorStack, array('title'   => $title,
                                               'message' => $message)
                     );
  }

# -------------- public functions -------------------- #

  public function loadXml($xmlStr) {

    $this->dom = new DomDocument('1.0', 'UTF-8');
    $this->dom->loadXml($xmlStr);

    $this->xpQuery = new DomXPath($this->dom);
   
    preg_match('/xml\.cleverbridge\.com\/([^\/]+)\//i', $xmlStr, $found);
    $xmlVersion = $found[1];

    // registration of namespace cbn is in root element - not necessary
    // $this->xpQuery->registerNamespace('cbn','http://xml.cleverbridge.com/'.$xmlVersion.'/cleverbridgeNotification.xsd');

    // registration of namespace cbt is not in root element
    $this->xpQuery->registerNamespace('cbt','http://xml.cleverbridge.com/'.$xmlVersion.'/cleverbridgeTypes.xsd');

    return true;
  }

  public function getItemData($nodeName) {

    if (($result = $this->xPathQuery("//cbn:ValidatePreviousLicenseCartItemRequest/cbn:Item/cbt:".trim($nodeName))) === false) {
      $this->AddError(__METHOD__."($runningNo, $nodeName)", 'Item data not found');
      return false;
    }    

    return $result->item(0)->nodeValue;
  }
  
  public function getErrors() {
    return $this->errorStack;
  }
  
  public function hasErrors() {
    return (sizeof($this->errorStack) > 0);    
  }

}


# ----------------------------------------------------- #
#                     Usage Sample                      #
# ----------------------------------------------------- #

$requestStr = '';

if (isset($HTTP_RAW_POST_DATA) && $HTTP_RAW_POST_DATA != '')
  $requestStr .= $HTTP_RAW_POST_DATA;

// see if XML data is included in request
if ($requestStr == '') {
  Header('HTTP/1.1 400 Bad Request');
  Header('Content-Type: text/plain');
  print ('XML not found!');
  exit;
}

$cbn = new cbNotification();
$cbn->loadXml($requestStr);

if ($cbn->hasErrors()) {
  // set your Error Header
  Header('HTTP/1.1 400 Bad Request');
  Header('Content-Type: text/plain');
  print_r ($cbn->getErrors());

} else {
   $knownLicense = array('aaaaaaaaaaa', 
                         'bbbbbbbbbbb',
                         'a12345');
                         
   // Expiration Value is  the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
   $keyExpiration = array('aaaaaaaaaa'  => 849042,
                          'bbbbbbbbbbb' => 5435343,
                          'a12345'      => 5353553543535353);

   $previousLicense = strtolower(trim($cbn->getItemData('PreviousLicense')));

   if (!in_array($previousLicense, $knownLicense) or $keyExpiration[$previousLicense] < time())
     $valid = 'false';
   else
     $valid = 'true';

  // create XML Str with DOM Object
  $dom = new DomDocument('1.0', 'UTF-8');
  $rootNode = $dom->appendchild($dom->createElementNs('http://xml.cleverbridge.com/2.170/cleverbridgeUpgradeManagement.xsd','cbn:ValidatePreviousLicenseCartItemResponse'));
  $rootNode->appendchild($dom->createElement('cbn:Valid', $valid));
  if ($valid != 'true') {
    $errorId = '';
    $errorMessage = '';

    if (in_array($previousLicense, $knownLicense))
      $errorId = 'KNF';
    elseif ($keyExpiration[$previousLicense] < time())
      $errorId = 'KEP';
    else {
      $errorId = 'CUS';
      $errorMessage = 'We do not accept the key. Reason custom text';
    }
    $rootNode->appendchild($dom->createElement('cbn:ErrorId', $errorId));

    if ($errorMessage != '')
      $rootNode->appendChild($dom->createElement('cbn:Text', $errorMessage));
  }

  // example how to return a text key  
  Header('Content-Type: text/xml');
  print $dom->saveXML();  
}

?>