<?php
define('idDiGIR_uddiSearch','$Id: DiGIR_uddiSearch.php,v 1.2 2003/05/06 20:33:23 vieglais Exp $');
if (defined('idDIGIR_VERSION_REQUEST'))
    return;
/****************************************************************************
$Id: DiGIR_uddiSearch.php,v 1.2 2003/05/06 20:33:23 vieglais Exp $

Description:
This page is a hack that locates services in UDDI that support a particular
service interface type (identified by tmodel).  The default tmodel resolves to the
DiGIR service type.

SOAP messages to the UDDI are hard coded (the nusoap lib doesn't retrieve the
data properly).

Further links to UDDI info (via soapclient.com) are provided.

Author : Dave Vieglais (vieglais@ku.edu)
Date Created:  23 Aug 2002
Dependencies:
    nusoap.php (http://dietrich.ganx4.com/nusoap/index.php)
    phpXPath (v3.2, http://www.carrubbers.org/scripts/php/xpath/ )
    DiGIR_utils.php (DiGIR.sourceforge.net)


== License ==
Copyright (c) 2002 The University of Kansas Natural History Museum and
Biodiversity Research Center.  All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
with the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

*  Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimers.

* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimers in the
documentation and/or other materials provided with the distribution.

* Neither the names of The University of Kansas Natural History Museum and
Biodiversity Research Center, The University of Kansas at Lawrence, nor the
names of its contributors may be used to endorse or promote products derived
from this Software without specific prior written permission.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*****************************************************************************/

/**
* This method is taken from the NUSOAP library by Dietrich
Ayala <dietrich@ganx4.com>.  The license information is repeated
here for your reference:
=======================	
NuSOAP - Web Services Toolkit for PHP
Copyright (c) 2002 NuSphere Corporation

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

=======================	

* This method sends a SOAP package to a SOAP endpoint and returns the
* respone package.	
* @param array params Array of operating parameters:
*	proxyhost
*	proxyporthost
*	port
*	username
*	password
* 	encoding
*	path
*	url
*	protocol_version
*	title
*	version
*	soapaction
* @param string data The SOAP package to send
* @return string The SOAP response.
*/
function SOAPsend(&$params,$data, $timeout=0, &$errno, &$error_str)
{
	flush();
	$outgoing_payload = "";
	//$this->debug('entered send() with data of length: '.strlen($data));
	if($params['proxyhost'] != '' && $params['proxyport'] != '')
	{
    	//$this->debug('setting proxy host and port');
        $host = $params['proxyhost'];
        $port = $params['proxyport'];
    }
    else
    {
		$host = $params['host'];
		$port = $params['port'];
	}
	if($timeout > 0)
	{
		$fp = fsockopen($host, $port, $errno, $error_str, $timeout);
	}
	else
	{
		$fp = fsockopen($host, $port, $errno, $error_str);
	}
	if (!$fp)
	{
//		$this->debug('Couldn\'t open socket connection to server: '.$host);
//		$this->setError('Couldn\'t open socket connection to server: '.$host);
		return false;
	}
//	$this->debug('socket connected');
	$credentials = '';
	$encoding_headers = '';
	if ($params['username'] != '')
	{
//    	$this->debug('setting http auth credentials');
		$credentials = 'Authorization: Basic '.base64_encode($params['username'].":".$params['password']).'\r\n';
	}
	if($params['proxyhost'] && $params['proxyport'])
	{
		$outgoing_payload = "POST ".$params['url']." HTTP/".$params['protocol_version']."\r\n";
	}
	else
	{
		$outgoing_payload = "POST ".$params['path']." HTTP/".$params['protocol_version']."\r\n";
	}
	if($params['encoding'] != '')
	{
		if(function_exists('gzdeflate'))
		{
			$encoding_headers = "Accept-Encoding: ".$params['encoding']."\r\n".
                                "Connection: close\r\n";
                                set_magic_quotes_runtime(0);
		}
	}
//dv - added charset="utf-8"
	$outgoing_payload .=
		"User-Agent: ".$params['title']."/".$params['version']."\r\n".
		//"User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)\r\n".
		"Host: ".$params['host']."\r\n".
		$credentials.
		"Content-Type: text/xml; charset=\"utf-8\"\r\nContent-Length: ".strlen($data)."\r\n".
		$encoding_headers.
		"SOAPAction: \"".$params['soapaction']."\""."\r\n\r\n".
		$data;
	// send
	if(!fputs($fp, $outgoing_payload, strlen($outgoing_payload)))
	{
//		$this->setError('couldn\'t write message data to socket');
//		$this->debug('Write error');
	}
//	$this->debug('wrote data to socket');
	// get response
	$incoming_payload = '';
	$strlen = 0;
	while( $data = fread($fp, 32768) )
	{
		$incoming_payload .= $data;
		$strlen += strlen($data);
	}
//	$this->debug('received '.strlen($this->incoming_payload).' bytes of data from server');
	// close filepointer
	fclose($fp);
//	$this->debug('closed socket');
	// connection was closed unexpectedly
	if($incoming_payload == '')
	{
//		$this->setError('no response from server');
		return false;
	}
//	$this->debug('received incoming payload: '.strlen($this->incoming_payload));
	$data = $incoming_payload."\r\n\r\n\r\n\r\n";
	//$res = preg_split("/\r?\n\r?\n/s",$data);
	// remove 100 header
	if(ereg('^HTTP/1.1 100',$data))
	{
		if($pos = strpos($data,"\n\n"))
		{
			$data = ltrim(substr($data,$pos));
		}
		elseif($pos = strpos($data,"\r\n\r\n"))
		{
			$data = ltrim(substr($data,$pos));
		}
	}//
	//print 'w/o 100:-------------<pre>'.$data.'</pre><br>--------------<br>';
	// separate content from HTTP headers
	if(preg_match("/(.*?)\r?\n\r?\n(.*)/s",$data,$result))
	{
//		$this->debug('found proper separation of headers and document');
//		$this->debug('getting rid of headers, stringlen: '.strlen($data));
		$header_array = explode("\r\n",$result[1]);
		$data = $result[2];
//		$this->debug('cleaned data, stringlen: '.strlen($clean_data));
		// clean headers
		foreach($header_array as $header_line)
		{
			$arr = explode(':',$header_line);
			$headers[trim($arr[0])] = trim($arr[1]);
        }
    	//print "headers: $result[1]<br>";
		//print "data: $result[2]<br>";
	}
	else
	{
		$this->setError('no proper separation of headers and document');
		return false;
	}
	// decode transfer-encoding
	if($headers['Transfer-Encoding'] == 'chunked')
	{
		$data = $this->decodeChunked($data);
		//print "<pre>\nde-chunked:\n---------------\n$data\n\n---------------\n</pre>";
	}
	// decode content-encoding
	if($headers['Content-Encoding'] != '')
	{
		if($headers['Content-Encoding'] == 'deflate' || $headers['Content-Encoding'] == 'gzip')
		{
			// if decoding works, use it. else assume data wasn't gzencoded
			if(function_exists('gzinflate'))
			{
				if($headers['Content-Encoding'] == 'deflate' && $degzdata = @gzinflate($data))
				{
					$data = $degzdata;
				}
				elseif($headers['Content-Encoding'] == 'gzip' && $degzdata = gzinflate(substr($data, 10)))
				{
					$data = $degzdata;
				}
				else
				{
//					$this->setError('Errors occurred when trying to decode the data');
				}
				//print "<xmp>\nde-inflated:\n---------------\n$data\n-------------\n</xmp>";
			}
			else
			{
//				$this->setError('The server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
			}
		}
	}
	if(strlen($data) == 0)
	{
//		$this->debug('no data after headers!');
//		$this->setError('no data present after HTTP headers');
		return false;
	}
//	$this->debug('end of send()');
	return $data;
}

////////////////////////////////////////////////////////////////////////
// UDDI methods

class UDDI
{
    var $endPoint;
    var $xparser;
    var $debug;
    
    function UDDI($endpoint="http://registry.gbif.net/uddi/inquiry")
    {
        $debug = 0;
        include_once("xpath/XPath.class.php");
        $this->endPoint = $endpoint;
    	$this->xparser = new XPath();
        $this->xparser->setVerbose(0);
        $this->xparser->setXmlOption(XML_OPTION_CASE_FOLDING,false);
        $this->xparser->setXmlOption(XML_OPTION_SKIP_WHITE,true);
    }
    
    function _UDDIOperation($payload)
    {
        $params=array();
        $params['title'] = 'DiGIR';
        $params['version'] = '1.0.0';
        $params['protocol_version'] = '1.0';
        $params['encoding'] = '';
        $params['charset_encoding'] = 'UTF-8';
        $params['soapaction'] = '';
        $error_str = false;

        $params['url'] = $this->endPoint;
        $u = parse_url($this->endPoint);
        foreach($u as $k => $v)
        {
            $params[$k] = $v;
        }
        if(isset($u['query']) && $u['query'] != '')
        {
            $params['path'] .= '?' . $u['query'];
        }
        if(!isset($u['port']) && $u['scheme'] == 'http')
        {
            $params['port'] = 80;
        }
        $errno = 0;
        $error_str = "";
        $res = SOAPsend($params,$payload,30,$errno,$error_str);
        return $res;
    }
    
/**
* Given a business key and /or a list of tmodels
* returns a list of matching service identifiers.
*
* @param $businessKey string id of business key.  Can be blank.
* @param $tmodels array Array of tmodels that the service supports.  These
* are ANDed by the UDDI registry to locate matching services.
*/
    function find_service($businessKey,$tmodels)
    {
    	$env = "<soap:Envelope
	     xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'
         xmlns:xsd='http://www.w3.org/2001/XMLSchema'
         xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>
         <soap:Body><find_service businessKey='".$businessKey."'
         xmlns='urn:uddi-org:api' generic='1.0'>
         <findQualifiers></findQualifiers>
         <tModelBag>";
         foreach($tmodels as $tmodel)
         {
             $stmp = "<tModelKey>".$tmodel."</tModelKey>\n";
             $env .= $stmp;
         }
         $env.= "</tModelBag></find_service></soap:Body></soap:Envelope>";
         $res = $this->_UDDIOperation($env);

         if ($this->debug)
         {
             echo "<h3>Service Details</h3>";
             echo "<h4>Sent Package</h4>\n";
             echo "<pre>".htmlEntities($env)."</pre>\n";
             echo "<h4>Result</h4>\n";
             echo "<pre>".htmlEntities($res)."</pre>\n";
         }

         
         $this->xparser->reset();
         $this->xparser->importFromString($res);

         $fnode = $this->xparser->match("//*/serviceInfo");
         $ares = array();
         foreach ($fnode as $node)
         {
		      $attrs = $this->xparser->getAttributes($node,'serviceKey');
		      array_push($ares,$attrs);
         }	
         return $ares;
    }
    
/**
* Given a list of service type tModels, this method resolves all businesses
* that have services that support the tModels.
*
* @param string $tmodel The business identifier (tmodel) to resolve.
* @return array An array: businesskey, name, description
*/
    function find_business($tmodels)
    {
	   $env = "<soap:Envelope
       xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'
       xmlns:xsd='http://www.w3.org/2001/XMLSchema'
       xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>
       <soap:Body>
       <find_business xmlns='urn:uddi-org:api' generic='1.0' maxRows='1000'>
       <findQualifiers></findQualifiers>
       <tModelBag>";
	   foreach($tmodels as $tmodel)
	   {
           $stmp = "<tModelKey>".$tmodel."</tModelKey>\n";
           $env .= $stmp;
       }
       $env.= "</tModelBag></find_business></soap:Body></soap:Envelope>";
	
	   $res = $this->_UDDIOperation($env);

       if ($this->debug)
       {
           echo "<h3>findBusiness_tModel</h3>";
           echo "<h4>Sent Package</h4>\n";
           echo "<pre>".htmlEntities($env)."</pre>\n";
           echo "<h4>Result</h4>\n";
           echo "<pre>".htmlEntities($res)."</pre>\n";
       }
	   $this->xparser->reset();
	   $this->xparser->importFromString($res);
       $fnode = $this->xparser->match("//*/businessInfo");
       $ares = array();
       foreach ($fnode as $node)
       {
           $attrs = $this->xparser->getAttributes($node,'businessKey');
		   $a = array();
           $a["businessKey"] = $attrs;
           $a["name"] = $this->xparser->wholeText($node."/name[1]");
           $a["description"] = $this->xparser->wholeText($node."/description[1]");
           array_push($ares,$a);
       }	
	   return $ares;
    }
    
/**
* Gets details about a service, including it's binding endpoint.
*
* @param string $serviceKey The service key to resolve.
* @return array Associative array giving details on the located service.
*/
    function get_serviceDetail($serviceKey)
    {
	   $env = "<soap:Envelope
       xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'
       xmlns:xsd='http://www.w3.org/2001/XMLSchema'
       xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>
       <soap:Body><get_serviceDetail xmlns='urn:uddi-org:api' generic='1.0'>
       <serviceKey>";
	   $env .= $serviceKey;
       $env .="</serviceKey></get_serviceDetail></soap:Body></soap:Envelope>";
       $res = $this->_UDDIOperation($env);
       if ($this->debug)
       {
        echo "<h3>Service Details</h3>";
        echo "<h4>Sent Package</h4>\n";
        echo "<pre>".htmlEntities($env)."</pre>\n";
	    echo "<h4>Result</h4>\n";
        echo "<pre>".htmlEntities($res)."</pre>\n";
       }
       $this->xparser->reset();
	   $this->xparser->importFromString($res);
	   $fnode = $this->xparser->match("//*/businessService");
	   $ares = array();
	   foreach ($fnode as $node)
       {
           $attrs = $this->xparser->getAttributes($node);
           $a = array();
           $a["businessKey"] = $attrs["businessKey"];
           $a["serviceKey"] = $attrs["serviceKey"];
           $a['name'] = $this->xparser->wholeText($node."/name[1]");
           $a['description'] =
                $this->xparser->wholeText($node."/description[1]");
           $a['binding'] = array();
           $bnode = $this->xparser->match($node."/bindingTemplates/bindingTemplate");
           foreach ($bnode as $xp)
           {
               $attrs = $this->xparser->getAttributes($xp);
               $b = array();
               $b['bindingKey'] = $attrs['bindingKey'];
               $b['description'] = $this->xparser->wholeText($xp.'/description[1]');
               $b['accessPoint'] = $this->xparser->wholeText($xp.'/accessPoint[1]');
               array_push($a['binding'],$b);
           }
		   array_push($ares,$a);
	   }	
	   return $ares;
    }
    
    function get_tModelDetail($tmodels)
    {
	   $env = "<soap:Envelope
       xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'
       xmlns:xsd='http://www.w3.org/2001/XMLSchema'
       xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>
       <soap:Body><get_tModelDetail xmlns='urn:uddi-org:api' generic='1.0'>";
       foreach ($tmodels as $tmodel)
       {
            $env .= "<tModelKey>".$tmodel."</tModelKey>";
       }
       $env .= "</get_tModelDetail></soap:Body></soap:Envelope>";
       $res = $this->_UDDIOperation($env);
       if ($this->debug)
       {
        echo "<h3>Service Details</h3>";
        echo "<h4>Sent Package</h4>\n";
        echo "<p>".htmlEntities($env)."</p>\n";
	    echo "<h4>Result</h4>\n";
        echo "<p>".htmlEntities($res)."</p>\n";
       }
       $this->xparser->reset();
	   $this->xparser->importFromString($res);
	   $fnode = $this->xparser->match("//tModel");
	   $ares = array();
	   foreach ($fnode as $node)
       {
           $attrs = $this->xparser->getAttributes($node);
           $a = array();
           $a['tModel'] = $attrs['tModelKey'];
           $a["operator"] = $attrs["operator"];
           $a["authorizedName"] = $attrs["authorizedName"];
           $a['name'] = $this->xparser->wholeText($node."/name[1]");
           $a['description'] =
                $this->xparser->wholeText($node."/description[1]");
           $a['overviewDoc'] =
                $this->xparser->wholeText($node."/overviewDoc[1]/description[1]");
           $a['overviewURL'] =
                $this->xparser->wholeText($node."/overviewDoc[1]/overviewURL[1]");
           array_push($ares,$a);

	   }	
	   return $ares;
    }
}


/*=========================================*/

/**
* return array of resources on DiGIR endpoint - queries for metadata and
* parses metadata to get a list of resources.
* code = code
* name = resource name
* schemans = namespace of schema
* schemaloc = location of schema
*/
function getResourceDetails($accessPoint)
{
    $res = array();
	$xp = new XPath();
	$xp->setVerbose(0);
	$xp->setXmlOption(XML_OPTION_CASE_FOLDING,false);
	$xp->setXmlOption(XML_OPTION_SKIP_WHITE,true);
	if (!$xp->importFromFile($accessPoint))
	   return res;

    $rnodes = $xp->match("//resource");
    foreach ($rnodes as $node)
    {
        $ares = array();
        $ares['code'] = $xp->getData($node."/code[1]");
        $ares['name'] = $xp->getData($node."/name[1]");
        $ares['schemans'] = $xp->getData($node."/conceptualSchema[1]");
        $ares['schemaloc'] = $xp->getAttributes($node."/conceptualSchema[1]","schemaLocation");
        array_push($res,$ares);
    }
    return $res;
}


/**
* Makes a URL from a business key to hit on soapClient.com
* @param businessKey $bk The business key to look up.
* @return URL A URL that can be used to discover more information about the
*             specified business key.
*/
function makeFindBusinessURL($bk)
{
    $res = "http://www.soapclient.com/uddi/uddi.sri?";
    $res .= "operator=http%3A%2F%2Fregistry.gbif.net%2Fuddi%2Finquiry";
    $res .= "&businessKey=".urlencode($bk);
    $res .= "&requestname=get_businessDetail";
    return $res;
}

function dateStamp()
{
    $res = gmstrftime("%Y-%m-%dT%H:%M+00:00");
    return $res;
}

///////////////////////////////////////////////////////////////////
function generateJavaScript($params)
{
    $gVar = $params['gvar'];
    echo "//Generated by DiGIR_uddiSearch.php\n";
    echo "//tModel used = ".$tmodel."\n";
    echo "var $gVar = new Array();\n";
    $uddi = new UDDI(UDDIinquire);

    //add localhost
    echo "var atmp = new Array();\n";
    $scriptpath = substr($_SERVER['SCRIPT_NAME'],0,strrpos($_SERVER['SCRIPT_NAME'],'/')+1);
    $apoint = "http://localhost".$scriptpath."DiGIR.php";
    
    echo "atmp['accessPoint'] = '".$apoint."';\n";
    echo "atmp['name'] = 'localhost';\n";
    echo "atmp['institution'] = 'localhost';\n";
    if ($params['listresources'] == 1)
    {
        echo "atmp['resources'] = new Array();\n";
        //client also wants a list of resources exposed by the
        // provider!
        echo "// resources from ".$apoint."\n";
        $reslist = getResourceDetails($apoint);
        foreach ($reslist as $resitem)
        {
            echo "var rtmp = new Array();\n";
            echo "rtmp['code']='".$resitem['code']."';\n";
            echo "rtmp['name']='".$resitem['name']."';\n";
            echo "rtmp['schemans']='".$resitem['schemans']."';\n";
            echo "rtmp['schemaloc']='".$resitem['schemaloc']."';\n";
            echo "atmp['resources'][atmp['resources'].length] = rtmp;\n";
        }
        echo $gVar."[".$gVar.".length] = atmp;\n";
    }
	
    if ($params['uddisearch'] > 0)
    {
        $tModels = explode(',',$params['tmodel']);
        $buss = $uddi->find_business($tModels);
        foreach ($buss as $busKey)
        {
            $sres = $uddi->find_service($busKey['businessKey'],$tModels);
            foreach ($sres as $svc)
            {
                $serviceD = $uddi->get_serviceDetail($svc);
                foreach ($serviceD as $a)
                {
                    foreach ($a['binding'] as $b)
                    {
                        echo "var atmp = new Array();\n";
                        echo "atmp['accessPoint'] = '".$b['accessPoint']."';\n";
                        echo "atmp['name'] = '".$a['name']."';\n";
                        echo "atmp['institution'] = '".$busKey['name']."';\n";
                        if ($params['listresources'] == 1)
                        {
                            echo "atmp['resources'] = new Array();\n";
                            //client also wants a list of resources exposed by the
                            // provider!
                            echo "// resources from ".$b['accessPoint']."\n";
                            $reslist = getResourceDetails($b['accessPoint']);
                            foreach ($reslist as $resitem)
                            {
                                echo "var rtmp = new Array();\n";
                                echo "rtmp['code']='".$resitem['code']."';\n";
                                echo "rtmp['name']='".$resitem['name']."';\n";
                                echo "rtmp['schemans']='".$resitem['schemans']."';\n";
                                echo "rtmp['schemaloc']='".$resitem['schemaloc']."';\n";
                                echo "atmp['resources'][atmp['resources'].length] = rtmp;\n";
                            }
                            echo $gVar."[".$gVar.".length] = atmp;\n";
                        }
                    }
                }
            }
        }
    }
}
///////////////////////////////////////////////////////////////////
/////////////// Start generateRSS()
function generateRSS($params)
{
    echo "<";
    echo "?xml version='1.0' encoding='ISO-8859-1' ?";
    echo ">\n";
////RSS output
?>
<rdf:RDF
 xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
 xmlns="http://purl.org/rss/1.0/"
 xmlns:dc="http://purl.org/dc/elements/1.1/"
 xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/"
 xmlns:syn="http://purl.org/rss/1.0/modules/syndication/"
>

<channel rdf:about="http://use.perl.org/">
<title>DiGIR Service Instances</title>
<link>http://digir.sourceforge.net/</link>
<description>Current list of DiGIR Service Instances</description>
<dc:language>en-us</dc:language>
<dc:date><?echo dateStamp();?></dc:date>
<dc:publisher>DiGIR.sourceforge.net</dc:publisher>
<dc:creator>vieglais@ku.edu</dc:creator>
<dc:subject>Technology</dc:subject>
<syn:updatePeriod>daily</syn:updatePeriod>
<syn:updateFrequency>1</syn:updateFrequency>
<syn:updateBase>1970-01-01T00:00+00:00</syn:updateBase>
<image rdf:resource="http://digir.sourceforge.net/images/digir.gif" />
<textinput rdf:resource="http://digir.sourceforge.net/images/digir.gif" />
</channel>

<image rdf:about="http://digir.sourceforge.net/images/digir.gif">
<title>DiGIR</title>
<url>http://digir.sourceforge.net/images/digir.gif</url>
<link>http://digir.sourceforge.net/</link>
</image>

<?php
/*
Dump each service like this:
<item rdf:about="http://use.perl.org/article.pl?sid=02/08/19/1230217">
<title>This Week on perl5-porters (11-18 August 2002)</title>
<link>http://use.perl.org/article.pl?sid=02/08/19/1230217</link>
<description>From sunny and hot and about to burst out in thunderstorms, downtown Echt, comes this weeks perl5-porters summary, brought to you by Elizabeth Mattijsen.</description>
<dc:creator>pudge</dc:creator>
<dc:subject>summaries</dc:subject>
<dc:date>2002-08-19T14:12:07+00:00</dc:date>
<slash:section>articles</slash:section>
<slash:comments>0</slash:comments>
<slash:hitparade>0,0,0,0,0,0,0</slash:hitparade>
</item>
*/

    $uddi = new UDDI(UDDIinquire);
	$tModels = explode(',',$params['tmodel']);
    $ares = $uddi->find_business($tModels);
    foreach ($ares as $ab)
    {
	   $sres = $uddi->find_service($ab['businessKey'],$tModels);
	   foreach ($sres as $svc)
	   {
			$serviceD = $uddi->get_serviceDetail($svc);
			foreach ($serviceD as $a)
			{
            	foreach ($a['binding'] as $b)
	            {
    	            echo "<item rdf:about='".$b['accessPoint']."'>\n";
        	        echo "<title>".$a['name']." (".$a['name'].")</title>\n";
	                echo "<link>".$b['accessPoint']."</link>\n";
    	            echo "<dc:date>".dateStamp()."</dc:date>\n";
            	    echo "</item>\n";
            }
        }
	}
}
?>
</rdf:RDF>
<?php
}
////////////// End generateRSS()

///////////// Start generateHTML()
function generateHTML(&$params)
{
?>
<html>
<head>
<title>DiGIR tools - Resolve UDDI Service tModel</title>
</head>
<body>
<h1>Resolve Services</h1>

<?php

    $tModels = explode(',',$params['tmodel']);
    $uddi = new UDDI(UDDIinquire);
    $tmodelDetail = $uddi->get_tModelDetail($tModels);

echo "<h2>Resolving tmodel(s):</h2>";

echo "<table border='1'>";
    echo "<tr><th>tModel</th><th>Overview</th><th>Description</th></tr>";
    foreach ($tmodelDetail as $tModel)
    {
        echo "<tr>";
        echo "<td>".$tModel['tModel']."</td>";
        echo "<td><a href='".$tModel['overviewURL']."'>".$tModel['overviewURL']."</a></td>";
        echo "<td>".htmlEntities($tModel['description'])."</td>";
        echo "</tr>";
    }
echo "</table>";
echo "<p>This page lists all the businesses and services that support the &quot;tModel&quot;";
echo " indicated in the tmodel parameter in the URL for this page.  If no tmodel parameter ";
echo " is supplied, then it defaults to &quot;uuid:a8012280-b3b8-11d7-b4bf-b8a03c50a862&quot;";
echo " which is the service type identifier for services that support a <a href='http://digir.sourceforge.net'>DiGIR</a> interface.</p>";
echo "<p>Click on the business name to see the information registered in <a href='http://uddi.org'>UDDI</a> ";
echo "for that business.  Click on the binding access point to retrieve metadata about that DiGIR service.</p>";
echo "<hr width='66%'/>\n";
    $ares = $uddi->find_business($tModels);

echo "<table border='1'>";
foreach ($ares as $ab)
{
    echo "<tr><td>Business Name</td><td colspan='2'><a href='".makeFindBusinessURL($ab['businessKey'])."'>".$ab['name']."</a></td></tr>";
    echo "<tr><td>Business Key</td><td colspan='2'>".$ab['businessKey']."</td></tr>";
    echo "<tr><td>Business Description</td><td colspan='3'>".$ab['description']."</td></tr>";
	$sres = $uddi->find_service($ab['businessKey'],$tModels);
	foreach ($sres as $svc)
	{
		$serviceD = $uddi->get_serviceDetail($svc);
		foreach ($serviceD as $a)
		{
            echo "<tr><td>Service</td><td>Name</td><td>".$a['name']."</td></tr>";
            echo "<tr><td></td><td>Key</td><td>".$a['serviceKey']."</td></tr>";
            echo "<tr><td></td><td>Description</td><td>".$a['description']."</td></tr>";
            foreach ($a['binding'] as $b)
            {
                echo "<tr><td>Binding</td><td>Key</td><td>".$b['bindingKey']."</td></tr>";
                echo "<tr><td></td><td>Description</td><td>".$b['description']."</td></tr>";
                echo "<tr><td></td><td>Access Point</td><td><a href='".$b['accessPoint']."'>".$b['accessPoint']."</a></td></tr>";
            }
        }
	}
}
echo "</table>";
echo "<hr width='66%'/>\n";
echo "<h3>Script Parameters</h3>
<table border='1'>
<tr><th>parameter</th><th>Description</th></tr>
<tr><td>tmodel</td><td>The tmodel(s) of the interface to resolve.  Default=uuid:a8012280-b3b8-11d7-b4bf-b8a03c50a862.  Can be comma delimited list of tModels</td></tr>
<tr><td>cache</td><td>default (1) = Use cache where possible, 0 = don't use cache</td></tr>
<tr><td>format</td><td>default = html (this output), rss = RDF Site Summary, javascript = javascript output</td></tr>
<tr><td>gvar</td><td>For javascript output = name of global variable created.  Default = g_endPoints</td></tr>
<tr><td>listres</td><td>For javascript, 0 (default) | 1 = query each found provider for resource list</td></tr>
<tr><td>registry</td><td>Which UDDI registry to use.  IBM is default.  Currently only other choice is MICROSOFT</td></tr>
</table>";

echo "</body></html>";
}

//////// End generateHTML()


//==============================================================================
// -- MAIN --

define('PHP_SELF',$_SERVER['PHP_SELF']);
/*//what OS?
if (substr(PHP_OS, 0, 3) == 'WIN')
{
    define('DIGIR_OS_WINDOWS', true);
    define('DIGIR_OS_UNIX',    false);
    define('DIGIR_OS',    'Windows');
    define('PATHSEP',';');
}
else
{
    define('DIGIR_OS_WINDOWS', false);
    define('DIGIR_OS_UNIX',    true);
    define('DIGIR_OS',    'Unix'); // blatant assumption
    define('PATHSEP',':');
}

//force PHP to use only local includes - should all be part of DiGIR as of
//version 1.3 (20 Sep 2002)
//ini_set('include_path','.'.PATHSEP.'pear');
*/
//reduce error output for deprecated method call in xpath
ini_set('allow_call_time_pass_reference','TRUE');

//update the include path to find the libraries
//include_once("Log.php");
//@include_once("localConfig.php");
include_once("DiGIR_globals.php");
include_once("DiGIR_utils.php");

//set the maximum script run time
set_time_limit(DIGIR_MAX_RUNTIME);

//turn on/off debugging output
$dbg = (bool) GetVar('debug',FALSE);
define('_DEBUG',$dbg);
if (!_DEBUG)
{
    error_reporting(E_ALL
                    & ~E_NOTICE
                    & ~E_WARNING
                    & ~E_CORE_WARNING
                    & ~E_COMPILE_WARNING);
  //  if (!defined('DIGIR_USE_CACHE'))
    {
        $dbg = (bool) GetVar('cache',TRUE);
        define('DIGIR_USE_CACHE',$dbg);
    }
}
elseif (!defined('DIGIR_USE_CACHE'))
    define('DIGIR_USE_CACHE',FALSE);

$params = array();
$params['debug'] = _DEBUG;
$params['tmodel'] = GetVar("tmodel","uuid:a8012280-b3b8-11d7-b4bf-b8a03c50a862");
$params['format'] = GetVar("format","html");
$params['searchuddi'] = GetVar("searchUDDI",1);
$getFormat = (int)GetVar("rss",0);
if ($getFormat > 0)
{
    $params['format'] = "rss";
}
$getFormat = (int) GetVar("javascript",0);
if ($getFormat > 0)
{
    $params['format'] = "javascript";
}
$params['gvar'] = GetVar("gvar","g_endPoints");
$params['listresources'] = (int) GetVar('listres',0);

require_once('Cache/Function.php');

//require_once("nusoap/lib/nusoap.php");
include_once("xpath/XPath.class.php");

$InquireServer = GetVar('registry','GBIF');
if ($InquireServer == 'GBIF')
    define ("UDDIinquire","http://registry.gbif.net/uddi/inquiry");
elseif ($InquireServer == 'IBM')
    define ("UDDIinquire","http://www-3.ibm.com/services/uddi/inquiryapi");
else
    define ("UDDIinquire","http://uddi.microsoft.com/inquire");


$cacheLife = DIGIR_UDDI_CACHE_LIFE_SECONDS;
if (!DIGIR_USE_CACHE)
    $cacheLife = 10;  //help prevent abuse

//debug
//$cacheLife = 1;
//$params['format'] = 'javascript';
//$params['listresources'] = 1;

////JavaScript
if ($params['format'] == 'javascript')
{
    $jargs = array("tmodel"=>$params['tmodel'],
                   "gvar"=>$params['gvar'],
                   "listresources"=>$params['listresources'],
                   "searchuddi"=>$params['searchuddi']);
    $cacheParams = array('cache_dir'=>DIGIR_CACHE_DIRECTORY,
                         'filename_prefix'=>'uddiJS_');
    $cache = new Cache_Function('file',
                                $cacheParams,
                                $cacheLife);
    $cache->call('generateJavaScript',$jargs);
    exit;
}
////RSS

if ($params['format'] == 'rss')
{
    $cacheParams = array('cache_dir'=>DIGIR_CACHE_DIRECTORY,
                         'filename_prefix'=>'uddiRSS_');
    $cache = new Cache_Function($container='file',
                                $cacheParams,
                                $expires=$cacheLife);
    $cache->call('generateRSS',$params);
    exit;
}
else
{
    $cacheParams = array('cache_dir'=>DIGIR_CACHE_DIRECTORY,
                         'filename_prefix'=>'uddiHTML_');
    $cache = new Cache_Function('file',
                                $cacheParams,
                                $cacheLife);
    $cache->call('generateHTML',$params);
}
?>
