<?php
// +---------------------------------------------------------------------------------------+
// | TenderSystem                                                                          |
// +---------------------------------------------------------------------------------------+
// | The contents of this file are subject to the TenderSystem Public License Version 1.1  |
// | ("License"); you may not use this file except in compliance with the License. You may |
// | obtain a copy of the License at http://www.tendersystem.com/tpl/                      |
// |                                                                                       |
// | Software distributed under the License is distributed on an "AS IS" basis, WITHOUT    |
// | WARRANTY OF ANY KIND, either express or implied. See the License for the specific     |
// | language governing rights and limitations under the License.                          |
// |                                                                                       |
// | All copies of the Covered Code must include the "Powered by TenderSystem" logo and    |
// | ValueCard copyright notice on every user interface screen and in every outgoing       |
// | email in the same form as they appear in the distribution.                            |
// |                                                                                       |
// | The Original Code is: TenderSystem                                                    |
// | The Initial Developer of the Original Code is ValueCard (Pty) Limited.                |
// | Portions created by ValueCard are Copyright (C) 2002 ValueCard (Pty) Limited.         |
// | All Rights Reserved.                                                                  |
// | Contributor(s): __________________.                                                   |
// +---------------------------------------------------------------------------------------+

/**
* Log class
* @package TenderSystem
* @subpackage log
* @copyright Copyright &copy; 2002, ValueCard (Pty) Ltd
* @license http://www.tendersystem.com/tpl/ TenderSystem Public License
* @version 
*/

// Security - ensure that file never called directly
// not required if global variables are off or API is hosted on a non-public server
if (eregi(basename(__FILE__),$_SERVER['PHP_SELF'])) {
    die ("You can't access this file directly...");
}

Class log {
	// set the paramaters
	var $string;
	var $error;
	
    function log_request($type,$params,$cfg) {
		// set the date
        $now = date("j-m-Y H:i:s");
		// set the array into a string
		$text_string = $this->log_string($params);
		$text_string = substr($text_string,0,-1);
		$text_string = $this->string." || ".$text_string;
		if ($cfg['log']['status']) {
			// set the message to log
	        $log_text = str_pad($now,22).str_pad($type,10).$text_string.chr(13).chr(10);
			// set the upload path
			$upload_file = $cfg['log']['file'];
			// determine if dynamic path
			if (substr($upload_file,0,1) == ".") {
				// set complete path
				$upload_file = $cfg['file'].substr($upload_file,1);
			}
	        // log
	        error_log($log_text,3,$upload_file);
		}
		// set the debug string
		if (isset($cfg['debug'])) {
			// get the split position
			$string_pos = strpos($text_string,"||");
			$text_string = substr($text_string,$string_pos+2);
			return "[:".$type.":]".$text_string;
		} else {
			return FALSE;
		}
    }
	
	function log_string($params) {
		// set the first level keys
		$array_keys = array_keys($params);
		// set log string
		$text_string = "";
		// loop through every paramater
		foreach ($array_keys as $key) {
			// determine if it is an array
			if (is_array($params[$key])) {
				// primary key settings
				if ($key == "file") {
					// set the primary key
					$this->string.= " [".$key."]";
					// move to next key
					continue;
				}
				// set the key
				$text_string.= $key."(";
				$text_string.= $this->log_string($params[$key]);
				// remove last comma
				$text_string = substr($text_string,0,-1);
				$text_string.= "),";
			} else {
				if ($key == "password" || $key == "new_password" || $key == "username" || $key == 'ip' || $key == 'newappsettings' || $key == 'debug' || $key == "gui_username" || $key == "gui_password") {
					$this->string.= " [".$key."]";
				} elseif ($key == "session") {
					// md5 session
					$text_string.= $key."=".md5($params[$key]).",";
				} else {
					$text_string.= $key."=".$params[$key].",";
				}
			}
		}
		// return the string
		return $text_string;
	}
	
	function display_log($params,$cfg) {
		// set variables
		$type = $params['displaytype'];
		$page = $params['displaypage'];
		$datefilter = $params['date_filter'];
		// set response type
		$response['type'] = $type;
		// determine if allowable type
		if ($type == "error" || $type == "request" || $type == "php") {
			// determine if allowable size exceeded
			if ($page > $cfg['display']['limit']) {
				// set to the maximum
				$page = $cfg['display']['limit'];
			} elseif (!$page) {
				// set to first page
				$page = 1;
			}
			// set the type and page being displayed in the xml
			$response['classification'] = $type;
			$response['display'] = $page;
			// set file location
			if ($type == "error") {
				// set the error path
				$file = $cfg['error']['file'];
				// determine if dynamic path
				if (substr($file,0,1) == ".") {
					// set complete path
					$file = $cfg['file'].substr($file,1);
				}
			} elseif ($type == "request") {
				// set the request path
				$file = $cfg['log']['file'];
				// determine if dynamic path
				if (substr($file,0,1) == ".") {
					// set complete path
					$file = $cfg['file'].substr($file,1);
				}
			} elseif ($type == "php") {
				// set the php error path
				$file = $cfg['log']['php'];
				// determine if dynamic path
				if (substr($file,0,1) == ".") {
					// set complete path
					$file = $cfg['file'].substr($file,1);
				}
			}
			// instantiate file class
			$new_file = new file;
			// check if file exists
			if(!$new_file->file_check($file,"TRUE",$cfg)){
				// set error
				$this->error = $new_file->error;
				// response	
				return FALSE;
			}
			// open file for reading
			$fp = fopen($file,"r");
			// check if file open okay
			if (!$fp) {
				// instantiate the error class and log
				$new_error = new error;
				$error_text = "Error: Can not open ".$file." in ".__file__." on line ".__line__;
				$new_error->log("FILE","serious",$error_text,$cfg);
				// Cannot open file
				$this->error[] = "77";
				// Error in settings class 
				$this->error[] = "106";
				// response
				return FALSE;
			}
			// read 1024 kb at a time
			while (!feof($fp)) {
				// replace certain
				$log.= str_replace(array('<','>','&#160;',"'",'\"',"\\","."),array('&lt;','&gt;',' ','&apos;','','',' '),fread($fp, 1024));
			}
			// close the file
			fclose($fp);
			// set the limit
			$display_logs = $cfg['display']['logs'];
			// ensure that larger than 0
			if (!$display_logs) {
				// set to a default of 10
				$display_logs = 10;			
			}
			// get every line
			$log = explode("\n", trim($log));
			// filter out certain lines
			if($datefilter) {
				$response['date_filter'] = $datefilter;
				$new_log = array();
				foreach($log as $value) {
					if(strpos($value,$datefilter) !== FALSE && strpos($value,"date_filter=".$datefilter) === FALSE) {
						$new_log[] = $value; 
					}
				}
				$log = $new_log;
			}
			// determine which fields lines to return
			$log_quantity = sizeof($log);
			// determine how many pages options to display
			$page_options = ceil($log_quantity/$display_logs);
			if ($page_options > $cfg['display']['limit']) {
				// set the maximum
				$page_options = $cfg['display']['limit'];
			}
			// set the limit
			$response['limit'] = $page_options;
			if ($response['display'] > $response['limit']) {
				$response['display'] = $response['limit'];
			}
			// work out which logs to display
			$limit_value = $page * $display_logs;
			$limit_value = $log_quantity - $limit_value;
			// return response
			$i = 0;
			$j = $limit_value;
			if ($type == "error") {
				// loop through every log
				while ($i < $display_logs) {
					// seperate the date method and message
					$log_line = $log[$j];
					$response['log'][$i]['date'] = trim(substr($log_line, 0, 22));
					$response['log'][$i]['method'] = trim(substr($log_line, 22, 10));
					$response['log'][$i]['status'] = trim(substr($log_line, 32, 10));
					$response['log'][$i]['message'] = wordwrap(trim(substr($log_line, 42)));
					$i++;
					$j++;
				}
			} elseif ($type == "request") {
				// loop through every log
				while ($i < $display_logs) {
					// seperate the date method and message				
					$log_line = $log[$j];
					if($log_line) {
						$response['log'][$i]['date'] = trim(substr($log_line, 0, 22));
						$response['log'][$i]['method'] = trim(substr($log_line, 22, 10));
						$response['log'][$i]['message'] = wordwrap(trim(substr($log_line, 32)));
					}
					$i++;
					$j++;
				}
			} elseif ($type == "php") {
				// loop through every log
				while ($i < $display_logs) {
					// seperate the date method and message
					$log_line = $log[$j];
					$response['log'][$i]['date'] = trim(substr($log_line, 1, 20));
					// set the net section
					$next_log_line = substr($log_line, 22);
					// determine the next starting point
					$start_pos = strpos($next_log_line, ":");
					$response['log'][$i]['method'] = trim(substr($next_log_line, 0, $start_pos));
					$response['log'][$i]['message'] = wordwrap(trim(substr($next_log_line, $start_pos+1)));
					$i++;
					$j++;
				}			
			}
			// response
			if($log_quantity) {
				return $response;
			} else {
				return array();
			}
		} else {
			// not allowable type
			$this->error[] = "115";
			// response
			return FALSE;
		}
	}
}
?>