<?php
/*
EasyGUI XP is free software released under the terms of the following BSD license.

Copyright (c) 2005,2006 Gaetan Lauff (glauff@plansoft.de)
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

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

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

- Neither the name of the developer nor the names of its contributors may 
be used to endorse or promote products derived from this software without 
specific prior written permission. 

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/**
 * Class XMLRequest
 *
 * This Class requests an XML File for processing 
 * from an EasyKat Server running in ek_internet mode
 * 
 * @author Gaetan Lauff <glauff@plansoft.de>
 * @version	XP $Id: class.ek_request.php 12 2006-02-21 11:27:33Z glauff $
 * @package base
 */
class EK_Request
{
	/**
	 * The Application Name
	 * @var string
	 */
	var $appname;
	
	/**
	 * The Filename of the xml File 
	 * @var string
	 */
	var $xmlFile;
      
    /**
     * @var string
     */
    var $queryresult;
    
    /**
     * @var string
     */
    var $querydata;
    
    /**
     * Complete Request
     * @var string
     */
    var $request_header;
      
    /**
     * @var integer
     */
    var $port;

    /**
     * @var boolean
     */
    var $logging;
    
    /**
     * @var object
     */
    var $errorHandler;
     
    /**
     * @var string
     */ 
    var $host;
    
    /**
    * Constructor
    *
    * @param	string	$host	Hostname on which to request
    * @param	string	$port	Port on which to request
    *
    * @return 	void
    * 
    * @access	public
    */
    function EK_Request( $host, $port )
    {
    	$host = ( empty( $host ) ) ? 'localhost' : $host;
    	$port = ( empty( $port ) ) ? '8089' : $port;
    	
    	$this->host = $host;
    	$this->port = $port;
    }
      
    /**
    * Starts Request
    *
    * @return string
    *
    * @access public
    */
    function init( )
    {
    	$this->queryresult = $this->execQuery( );
    	return $this->checkRequest();
    }

    /**
    * Checks Server Response
    *
    * If the response is a valid XML File the resulkt is returned
    * Other Files are directly sent to the Browser via header
    *
    * @return void
    */
    function checkRequest( )
    {
	    $ctype 		= trim( $this->getContentType( ) );
	    $clength 	= trim( $this->getContentLength( ) );
		
	    if ( ereg( "application\/vnd\.plansoft", $ctype ) ) {
			$filename = strtolower( $this->getFilename( ) );
			
			if (empty($filename)) {
				trigger_error( "XML Request failed !\r\n<br/>Reason: " . $this->queryresult[1] . " answered with empty filename!", E_USER_ERROR );
			}
			
			if( !file_exists( $filename ) ) {
				trigger_error( "XML Request failed !\r\nReason: Cannot find file: ".$filename, E_USER_ERROR );
			}
			
	       	if ( ereg( "(.+)\.xml", $filename ) || ereg( "(.+)\.xsd", $filename ) || ereg( "(.+)\.eks", $filename ) ) {
	       		return $filename;
	       	} elseif ( ereg( "(.+)\.html", $filename ) || ereg( "(.+)\.htm", $filename ) ) {
				header( "Expires: Sat, 18 May 2002 05:00:00 GMT" );    
				header( "Last-Modified: " . gmdate ("D, d M Y H:i:s") . " GMT" );
				header( "Cache-Control: no-cache, must-revalidate" ); // HTTP/1.1   
				header( "Pragma: no-cache" );// HTTP/1.0
				header( "Content-Type: text/html" );
				
				if( !readfile( $filename ) ) {
					trigger_error( 'XML Request: Cannot find file: '.$filename, E_USER_ERROR );
				}
				
				exit(0);
			} else {
				
				$proposed_filename 	= $this->getFilename( );
				$fn_idx 			= sizeof( $this->queryresult ) - 2;
				$filename 			= trim( $this->queryresult[$fn_idx] );
				$pathparts 			= pathinfo( $filename );
				$dlFile 			= $proposed_filename.$pathparts["basename"];
				$content_type 		= str_replace( "SecondType:", "", explode( "|", $ctype ) );
				
				header( "Expires: Sat, 18 May 2002 05:00:00 GMT" );    
				header( "Last-Modified: " . gmdate ("D, d M Y H:i:s") . " GMT" );
				header( "Cache-Control: no-cache, must-revalidate" );
				header( "Pragma: no-cache" );
				header( "Server: EasyGUI/2.0" );
				header( "Content-Type: ".$content_type );
	   			header( "Content-Length: ".filesize($filename) );
				header( "Content-Disposition: filename=$proposed_filename" );
			}
		} elseif ( $ctype == 'text/html' ) {
			$i = 0;
			
			foreach ( $this->queryresult as $result ) {
				if ( $i++ < 6 ) {
					header( $result );
				} else {
					if ( !empty( $result ) ) {
						print $result;
					}
				}
			}
		} else {
			trigger_error( 'XML Request: Server has gone away ! '.$ctype, E_USER_ERROR );
		}
    }
	
    /**
    * Starts Query on EasyKat Server on a specific port
    *
    * @return string	If the server is reachable the method returns the Result of the query as string
    *
    * @access public
    */
    function execQuery( )
    {
	    if ( !$fp = fsockopen( $this->host, $this->port, $errno, $errstr, 10 ) ) {
	    	trigger_error( $errstr . '<br/><br/>Server on Host: ' . $this->host . ' Port: ' . $this->port . ' not running', E_USER_ERROR );
		} else {	
			$i 				= 0;
			$queryresult	= array();
			
			if ( !empty( $_POST ) ) {
				foreach( $_POST as $var => $val ) {
	     			$this->querydata .= $var . '=' . urlencode($val) . '&';
				}
			} elseif( !empty( $_GET ) ) {
				foreach( $_GET as $var => $val )  {
	     			$this->querydata .= $var . '=' . urlencode($val) . '&';
				}
			} else {
				$this->querydata .= 'APPNAME=' . urlencode( APPNAME );
			}
			
	     	$this->request_header = "POST /ekat HTTP/1.1\r\n";
			$this->request_header .= "Content-type: application/x-www-form-urlencoded\r\n";
			$this->request_header .= "Content-length: " . strlen( $this->querydata ) . "\r\n\r\n";
			$this->request_header .= $this->querydata . "\r\n";
			
		    fputs( $fp, $this->request_header );
		    	
		    while ( !feof( $fp ) ) {
		    	$queryresult[$i++] = fgets( $fp, 128 );
		    }

		    fclose( $fp );
		    
		    if ( EK_LOG_REQUEST ) {
		    	$this->writeRequestLog($queryresult);
		    }
		    	
			return $queryresult;
		}
		
		return false;
    }
    
    /**
     * Returns the content type of the query result
     *
     * @return 	mixed	The content type as a string, FALSE if it's not found
     *
     * @access 	private
     */
    function getContentType( )
    {
    	if ( is_array( $this->queryresult ) ) {
	    	foreach ( $this->queryresult as $line ) {
	     		if ( ereg( "^(Content-type|Content-Type):(.+)", $line, $regs ) ) {
	     			return $regs[2];
	     		}
	    	}
    	}
	    
	    return false;
    }

    /**
     * Returns the content length of the query result
     *
     * @return 	mixed	The content length as string, FALSE otherwise
     *
     * @access 	private
     */
    function getContentLength( ) 
    {
    	if ( is_array( $this->queryresult ) ) {
			foreach ( $this->queryresult as $line ){
				if ( ereg( "^Content-length:(.+)", $line, $regs ) ) {
					return $regs[1];
				}
			}
    	}
		
		return false;
    }

    /**
     * Returns the filename from the query result
     *
     * @return string
     *
     * @access private
     */
    function getFilename()
    {
	  	return end( $this->queryresult );
    }
    
    /**
     * If EK_LOG_REQUEST is set to true a request log is written
     *
     * The Request Log is written to the logs directory under the application
     * If the logs directory doesn't exist, it's created
     *
     * @param 	string	&$queryresult	A reference to the query result
     *
     * @return 	void
     *
     * @access private
     * @todo Make Request log directory configurable
     */
    function writeRequestLog( &$queryresult )
    {
    	$logfile = APPPATH . "/logs/" . APPNAME . "_request_[".date('Y-m-d')."].log";
    	
		if (!file_exists( $logfile )) {
			$loginfo = pathinfo( $logfile );
			$logdir = $loginfo['dirname'];

			if (!file_exists( $logdir ) ) {
				mkdir( $logdir );
			}
					
			if (!$fp = fopen( $logfile, 'w+')) {
				print "Logfile " . $logfile . " cannot be created !";
				exit(0);
			}
				
			fputs ( $fp, 'Log file created on ' . date('Y-m-d H:i:s') ."\r\n" . str_repeat('=', 80) ."\r\n" );
			fclose( $fp );
		}
			
    	$fsd = fopen( $logfile, "a" );
		fputs ( $fsd, str_repeat( "-", 80 ) . "\r\n" );
		fputs ( $fsd, "Checking new incoming request from " . $_SERVER['REMOTE_ADDR'] . " at " . date( "l dS of F Y, H.i:s" ) . "\r\n" );
		fputs ( $fsd, "Request Data:\r\n\r\n" );
		fputs ( $fsd, $this->request_header . "\r\n\r\n" );
		fputs ( $fsd, str_repeat( "-", 80 ) . "\r\n\r\n" );
		fputs ( $fsd, "Server Response:\r\n\r\n" );
		
		if ( is_array( $queryresult ) ) {
			foreach ( $queryresult as $line ) {
	           	fputs ( $fsd, $line );
			}
		} else {
	       	fputs ( $fsd, $queryresult . "\r\n\r\n" );
		}
	    
	    fputs ($fsd, "\r\n\r\n".str_repeat("-", 80)."\r\n");
	    fclose($fsd);
    }
}
?>