<?php

class wbError{

	function save($err,$num=0,$checkSize=true){
		global $errorEmail,$rootDir;
		global $maxErrorFileSize;
		
		if( !isset($maxErrorFileSize) || empty($maxErrorFileSize) ){
			$maxErrorFileSize = 100000;
		}
	
		if( $num == 0){
			$top = '<h2 class="underline">';
			if( is_string($num) ){
				$top .= $num.' &nbsp; ';
			}
			$top .= date('l, F j, Y \a\\t H:i:s');
			$top .= '</h2>';
		}else{
			$top = '';
		}
		$err = $top.$err;
		
		
		
		//Save to file or email?
		if( !empty($errorEmail) ){
			
			$headers = "MIME-Version: 1.0\r\n";
			$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
			$headers .= "From: ".$serverName1." Error ".$errno.'('.$num.')'."<noreply@".$serverName1.">\r\n";
			$bool = @error_log($err, 1, $errorEmail, $headers);
			
			//If the error is sent to $errorEmail, don't save it to file
			if( $bool ){
				return;
			}
		}
			
			
		$file = $rootDir.'/userfiles/error.log';
		if( !is_file($file) ){
			return;
		}
		$size = filesize($file);
		if( $checkSize && ($size > $maxErrorFileSize) ){ //Limits the size
			return;
		}
		$err = wbError::encode($err);
		error_log($err, 3, $file);
	}
	
	
	//using the unique key, encode the error text
	function encode($text){
		global $wbUniq;
		$wbUniqLen = strlen($wbUniq);
		$result = '';
		for($i = 0;$i<strlen($text);$i++){
			$wbUniqChar = $wbUniq{($i%$wbUniqLen)};
			$ord = ord($wbUniqChar)+ord($text{$i});
			$result .= str_pad($ord,3,'0',STR_PAD_LEFT);
		}
		return $result."\n";
	}
	
	function decode($text){
		$array = explode("\n",$text);
		$result = '';
		foreach($array as $piece){
			$result .= wbError::decode2($piece);
		}
		return $result;
	}
	function decode2($text){
		global $wbUniq;
		$wbUniqLen = strlen($wbUniq);
		$result = '';
		
		for($i=0;($i*3)<strlen($text);$i++){
			$piece = substr($text,($i*3),3);
			$wbUniqChar = $wbUniq{($i%$wbUniqLen)};
			$ord = ((int)$piece)-ord($wbUniqChar);
			$result .= chr($ord);
		}
		
		return $result;	
	}
}
