<?php
header('Cache-Control: no-cache, no-store, must-revalidate');   
header('Expires: 0');
set_time_limit(0);

// error_reporting(E_ALL);
// ini_set('display_errors', 1);

// Return Default mySql Connection
function defaultDbConnection()
{
// get default System Settings from xml file	
	$mSystem = "DEFAULT";
// Get System Definition XML from URL
	$mData = file_get_contents("../../vimsconfig/systemsettings.xml");
// Parse XML to XML Object Array
	$xml = simplexml_load_string($mData, 'SimpleXMLElement', LIBXML_NOCDATA);
// Split-out System Definitions from XML 'fields' Nodes
	$i = 0;

	for ($i = 0; $i <= 150; $i++) 
	{			
		$mSystemId = "";
		$mPath = "";
		$mDbHost = "";
		$mDbUser = "";
		$mDbPwd = "";
		$mDbase = "";
		$mMqServer = "";
		$mCompany = "";
		if (("".$xml->systems->system[$i]->systemid."" == "") || ("".$xml->systems->system[$i]->systemid."" == false) || ("".$xml->systems->system[$i]->systemid."" == false))
			break;
		
		$mSystemId = "".$xml->systems->system[$i]->systemid."";
		if (($mSystemId == "") || ($mSystemId == false))
			break;
		
// Store System Settings from "trandef/systemsettings.xml"		
		if (strToUpper($mSystem) == strToUpper($mSystemId))
		{
			$mPath = "".$xml->systems->system[$i]->path."";
			$mDbHost = "".$xml->systems->system[$i]->dbhost."";
			$mDbUser = "".$xml->systems->system[$i]->dbuser."";
			$mDbPwd = "".$xml->systems->system[$i]->dbpwd."";
			$mDbase = "".$xml->systems->system[$i]->dbase."";
			break;
		}
		if (($mSystemId == "") || ($mSystemId == false))
			break;
	}

	$mConnection = mysqli_connect($mDbHost,$mDbUser,$mDbPwd,$mDbase)or die("FAIL-Failed to connect to Database: " . mysqli_connect_error().":".$mSystem);
	return $mConnection;
}

function getMessage($mMessageCode,$mMessageText=null,$mDbHost=null,$mDbUser=null,$mDbPwd=null,$mDbName=null)
{
	$mReturn = $mMessageCode;
// Strip message prefix ("FAIL-","OK  -",etc..)
	if ((substr($mMessageCode,0,2)=="FA") || (substr($mMessageCode,0,2)=="OK"))
	{
		$mSeverity = substr($mMessageCode,0,5);
		$mMessageCode = substr($mMessageCode,5);
	}
// mysql connection - Use Passed values...
	if (($mDbHost != null) && ($mDbHost != ""))
		$mConnection=mysqli_connect($mDbHost,$mDbUser,$mDbPwd,$mDbName) or
			exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// ... or get defaults from function defaultDbConnection
	else
		$mConnection=defaultDbConnection();	
// Get Message Data
	$mDataQuery = "SELECT id, severity, short_text, long_text, text_file FROM messages WHERE message_code='".$mMessageCode."' LIMIT 1";
// Validate QRY
	if (!mysqli_query($mConnection,$mDataQuery))
		exit("FAIL-".mysqli_error($mConnection).$mDataQuery);
// Run QRY
	$mData = mysqli_query($mConnection,$mDataQuery);
	if (mysqli_num_rows($mData) == 0)
	{
		$mDataQuery = "SELECT id, severity, short_text, long_text, text_file FROM messages WHERE message_code LIKE('%".$mMessageCode."%') LIMIT 1";
		if (!mysqli_query($mConnection,$mDataQuery))
			exit("FAIL-".mysqli_error($mConnection).$mDataQuery);
		$mData = mysqli_query($mConnection,$mDataQuery);
		if (mysqli_num_rows($mdata) == 0)
		{
			$mDataQuery = "SELECT id, severity, short_text, long_text, text_file FROM messages WHERE message_code = LEFT('".$mMessageCode."',CHAR_LENGTH(message_code)) LIMIT 1";
			if (!mysqli_query($mConnection,$mDataQuery))
				exit("FAIL-".mysqli_error($mConnection).$mDataQuery);
			$mData = mysqli_query($mConnection,$mDataQuery);
		}
	}
	$i = 0;
	$mFileText="";
	while($mRow = mysqli_fetch_assoc($mData))
	{
		if (($mRow['text_file']) != "")
		{
			$mFileText = file_get_contents(($mRow['text_file']));
			$mFileText = str_replace(",","",$mFileText);
			$mFileText = str_replace("_"," ",$mFileText);
//			$mJsonObject = json_encode(array_merge($mRow,array("very_long_text"=>$mFileText)), JSON_FORCE_OBJECT);
		}
		else
		{
//			$mJsonObject = json_encode($mRow), JSON_FORCE_OBJECT);
		}
		if ((($mRow['short_text']) == "") || (($mRow['short_text'])== null))
		{
			if (($mMessageText != null) && ($mMessageText != ""))
				$mReturn = "severity:".($mRow['severity']).",short_text:".$mNessageCode." ".$mMessageText.",long_text:".($mRow['long_text'])." ".$mMessageText.",file_text:".$mFileText;
			else
				$mReturn = "severity:".($mRow['severity']).",short_text:".$mMessageCode.",long_text:".($mRow['long_text']).",file_text:".$mFileText;
		}
		else
		{
			if (($mMessageText != null) && ($mMessageText != ""))
				$mReturn = "severity:".($mRow['severity']).",short_text:".($mRow['short_text'])." ".$mMessageText.",long_text:".($mRow['long_text'])." ".$mMessageText.",file_text:".$mFileText;
			else
				$mReturn = "severity:".($mRow['severity']).",short_text:".($mRow['short_text']).",long_text:".($mRow['long_text']).",file_text:".$mFileText;
		}
		$i++;
	}
	if ($i == 0)
	{
		$mMessageCode = str_replace(",","",$mMessageCode);
		$mMessageCode = str_replace("_"," ",$mMessageCode);
		$mMessageCode = str_replace("isn't","is not",$mMessageCode);
		$mMessageCode = str_replace("'"," ",$mMessageCode);
//		if ($mSeverity == "")
//			$mSeverity = "FAIL-";
		if ($mSeverity == "FAIL-")
//			$mReturn = "severity:".$mSeverity.",short_text:".$mMessageCode.",long_text:Error. See displayed message.";
			$mReturn = "severity:".$mSeverity.",short_text:".$mMessageCode.",long_text:".$mMessageCode;
		else
			$mReturn = "severity:".$mSeverity.",short_text:".$mMessageCode.",long_text:".$mMessageCode;
//		$mReturn = "severity:".($mRow['severity']).",short_text:".($mRow['short_text']).",long_text:".($mRow['long_text']).",file_text:".$mFileText;
	}
	if ($mReturn == "")
		$mReturn=$mMessageCode;
	return "MESS-".$mReturn;
}

// Split Keywords from Text
function getKeyword($mMessageText,$mDbHost=null,$mDbUser=null,$mDbPwd=null,$mDbName=null)
{
	$mSeverity = "";
// control words
	$mCommonWords = array('a','an','at','can','do','does','for','her','his','i','is','it','me','my','need','the','you','your');
	$mKeywords = array('alexa','did','explain','how','tell','web','what','where','which','will','would');
	$mCategories = array('alexa','question','sop','instruction','sop','web','sop','direction','sop','sop','question');
	$mKeyword = "";
	$mKeyCategory = "";
		
	$mMessageText = strtolower($mMessageText);
	
// Remove Common Words from the Message Text
	foreach($mCommonWords as $mCommonWord)
	{
		$mMessageText = str_replace(" ".$mCommonWord." "," ",$mMessageText);
	}

// Look for keywords
	for($i = 0; $i < count($mKeywords); $i++)
	{
		if (strpos($mMessageText,$mKeywords[$i]) !== false)
		{
//			if ($mKeyword != "")
//				$mKeyword .= "-";
			$mKeyword = $mKeywords[$i];
			$mKeyCategory = $mCategories[$i];
		}
		$mMessageText = str_replace($mKeywords[$i],"",$mMessageText);
	}
	if ($mKeyword != "")
	{
		if (trim($mKeyword) == "will")
		{
			if (strpos($mMessageText,"pass driving") !== false)
				$mMessageText = "Of course she will!";
			elseif (strpos($mMessageText,"fail driving") !== false)
				$mMessageText = "Of course she wont";
			else
				$mMessageText = "She will pass.";
		}
		elseif (trim($mKeyword) == "did")
		{
			if (strpos($mMessageText,"pass driving") !== false)
				$mMessageText = "no she was robbed!";
			elseif (strpos($mMessageText,"fail driving") !== false)
				$mMessageText = "Yes. She'll pass next time";
			else
				$mMessageText = "She will pass next time.";
		}
		elseif (trim($mKeyword) == "would")
		{
			if (strpos($mMessageText,"coffee") !== false)
				$mMessageText = "Only if Sarah is buying.";
			if (strpos($mMessageText,"mcdonald") !== false)
				$mMessageText = "Only if Sarah is buying.";
			if (strpos($mMessageText,"pie") !== false)
				$mMessageText = "Yum! Yum!";
		}
		elseif (trim($mKeyword) == "what")
		{
			if (strpos($mMessageText,"time") !== false)
			{
				$mRand = rand(0, 10);
				try
				{
					if ($mRand > 4)
						$mTime = "The time is - ".date('l jS \of F Y h i A').".";
					elseif($mRand >2)
						$mTime = "It's five o'clock somewhere.";
					else
						$mTime = "I've got it written on a piece of paper.";
				}
				catch (Exception $e)
				{
					$mTime = "It's five o'clock somewhere.";
				}
				$mMessageText = $mTime;
			}
		}
		elseif (trim($mKeyword) == "tell")
		{
			try
			{
				$mTime = "The time is - ".date('l jS \of F Y h i A').".";
			}
			catch (Exception $e)
			{
				$mTime = "I've got it written on a piece of paper.";
			}
			$mMessageText = $mTime;
		}
		elseif (trim($mKeyword) == "can")
		{
			try
			{
				if ($mRand > 4)
					$mTime = "The time is - ".date('l jS \of F Y h i A').".";
				elseif($mRand >2)
					$mTime = "It's five o'clock somewhere.";
				else
					$mTime = "I've got it written on a piece of paper.";
			}
			catch (Exception $e)
			{
				$mTime = "I've got it written on a piece of paper.";
			}
			$mMessageText = $mTime;
		}
		elseif (trim($mKeyword) == "how")
		{
			if (stristr($mMessageText,"tie"))
			{
				if (stristr($mMessageText,"shoelace"))
					$mMessageText = "Make a loop with one end. Wrap the other end around. Pull a loop through the 'hole' in the middle.";
			}
		}
		elseif (trim($mKeyword) == "web")
		{
			$html = "";
			$html = scrapeWebSiteData("http://www.laughfactory.com/jokes/joke-of-the-day");
			if ($html == "")
				$mMessageText = "FAIL-Web Error";
			else
			{
				$start_point = strpos($html, '<p id="joke_>');
				$end_point = strpos($html, '</p>', $start_point);
				$length = $end_point-$start_point;
				$html = substr($html, $start_point, $length);
				$mMessageText = $html."-".$start_point."-".$length;
			}
			$mSeverity = "OKAL";
		}
		else
		{
			$mMessageText = "Keyword ".$mKeyword.". Category ".$mKeyCategory.". Subject ".$mMessageText;
		}
		$mMessageText = str_replace("  "," ",$mMessageText);
		$mMessageText = str_replace("_"," ",$mMessageText);
//		$mMessageText = "Keyword ".$mKeyword.". Category ".$mKeyCategory.". Subject ".$mMessageText;
	}
	$mReturn = "severity:".$mSeverity.",short_text:".$mMessageText.",long_text:".$mMessageText;
	return "MESS-".$mReturn;
}

function getUserMessage($mMessageCode,$mMessageText=null,$mDbHost=null,$mDbUser=null,$mDbPwd=null,$mDbName=null)
{
	$mReturn = $mMessageCode;
// Strip message prefix ("FAIL-","OK  -",etc..)
	if ((substr($mMessageCode,0,2)=="FA") || (substr($mMessageCode,0,2)=="OK"))
	{
		$mSeverity = substr($mMessageCode,0,5);
		$mMessageCode = substr($mMessageCode,5);
	}
// mysql connection - Use Passed values...
	if (($mDbHost != null) && ($mDbHost != ""))
		$mConnection=mysqli_connect($mDbHost,$mDbUser,$mDbPwd,$mDbName) or
			exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
// ... or get defaults from function defaultDbConnection
	else
		$mConnection=defaultDbConnection();	
// Get Message Data
	$mDataQuery = "SELECT id, severity, short_text, long_text, text_file FROM messages WHERE message_code='".$mMessageCode."' LIMIT 1";
// Validate QRY
	if (!mysqli_query($mConnection,$mDataQuery))
		exit("FAIL-".mysqli_error($mConnection).$mDataQuery);
// Run QRY
	$mData = mysqli_query($mConnection,$mDataQuery);
	if (mysqli_num_rows($mData) == 0)
	{
		$mDataQuery = "SELECT id, severity, short_text, long_text, text_file FROM messages WHERE message_code LIKE('%".$mMessageCode."%') LIMIT 1";
		if (!mysqli_query($mConnection,$mDataQuery))
			exit("FAIL-".mysqli_error($mConnection).$mDataQuery);
		$mData = mysqli_query($mConnection,$mDataQuery);
		if (mysqli_num_rows($mdata) == 0)
		{
			$mDataQuery = "SELECT id, severity, short_text, long_text, text_file FROM messages WHERE message_code = LEFT('".$mMessageCode."',CHAR_LENGTH(message_code)) LIMIT 1";
			if (!mysqli_query($mConnection,$mDataQuery))
				exit("FAIL-".mysqli_error($mConnection).$mDataQuery);
			$mData = mysqli_query($mConnection,$mDataQuery);
		}
	}
	$i = 0;
	$mFileText="";
	while($mRow = mysqli_fetch_assoc($mData))
	{
		if (($mRow['text_file']) != "")
		{
			$mFileText = file_get_contents(($mRow['text_file']));
			$mFileText = str_replace(",","",$mFileText);
			$mFileText = str_replace("_"," ",$mFileText);
//			$mJsonObject = json_encode(array_merge($mRow,array("very_long_text"=>$mFileText)), JSON_FORCE_OBJECT);
		}
		else
		{
//			$mJsonObject = json_encode($mRow), JSON_FORCE_OBJECT);
		}
		if ((($mRow['short_text']) == "") || (($mRow['short_text'])== null))
		{
			if (($mMessageText != null) && ($mMessageText != ""))
				$mReturn = "severity:".($mRow['severity']).",short_text:".$mNessageCode." ".$mMessageText.",long_text:".($mRow['long_text'])." ".$mMessageText.",file_text:".$mFileText;
			else
				$mReturn = "severity:".($mRow['severity']).",short_text:".$mMessageCode.",long_text:".($mRow['long_text']).",file_text:".$mFileText;
		}
		else
		{
			if (($mMessageText != null) && ($mMessageText != ""))
				$mReturn = "severity:".($mRow['severity']).",short_text:".($mRow['short_text'])." ".$mMessageText.",long_text:".($mRow['long_text'])." ".$mMessageText.",file_text:".$mFileText;
			else
				$mReturn = "severity:".($mRow['severity']).",short_text:".($mRow['short_text']).",long_text:".($mRow['long_text']).",file_text:".$mFileText;
		}
		$i++;
	}
	if ($i == 0)
	{
		$mMessageCode = str_replace(",","",$mMessageCode);
		$mMessageCode = str_replace("_"," ",$mMessageCode);
		$mMessageCode = str_replace("isn't","is not",$mMessageCode);
		$mMessageCode = str_replace("'"," ",$mMessageCode);
//		if ($mSeverity == "")
//			$mSeverity = "FAIL-";
		if ($mSeverity == "FAIL-")
//			$mReturn = "severity:".$mSeverity.",short_text:".$mMessageCode.",long_text:Error. See displayed message.";
			$mReturn = "severity:".$mSeverity.",short_text:".$mMessageCode.",long_text:".$mMessageCode;
		else
			$mReturn = "severity:".$mSeverity.",short_text:".$mMessageCode.",long_text:".$mMessageCode;
//		$mReturn = "severity:".($mRow['severity']).",short_text:".($mRow['short_text']).",long_text:".($mRow['long_text']).",file_text:".$mFileText;
	}
	if ($mReturn == "")
		$mReturn=$mMessageCode;
	return "MESS-".$mReturn;
}

function scrapeWebsiteData($mWebsite_url)
{
	if (!function_exists('curl_init')) 
	{
		return('cURL is not installed. Please install and try again.');
	}
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $mWebsite_url);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	$mOutput = curl_exec($curl);
	curl_close($curl);
	if ($mOutput == "")
		$mOutput = "No Response ".urlencode($mWebsite_url);
	elseif (!$mOutput)
		$mOutput = "Web Does Not Exist.";
	return $mOutput;
}

/*
// Get Input Parameters from POST or GET
if (!empty($_POST))
{
	$mFilter = "";
	foreach($_POST as $k1=>$v1)
	{
//		print_r("TEST".$k1.":".$v1);
		if ($mFilter != "")
			$mFilter .= "&";
		$mFilter .= $k1."=".$v1;
	}
}
else
{
	$mFilter = $_SERVER['QUERY_STRING'];
}

$mFilter = str_replace("=",":",$mFilter);
$mFilter = str_replace("&",",",$mFilter);

if (strpos($mFilter,"messagecode"))
{
	$mMessageCode = "";
// Explode Input String Into Array - Separated by ,
	$mArray1 = explode(",",$mFilter);
// Create Associative Array by Exploding Array Elements on :
	foreach($mArray1 as $k1=>$v1)
	{
		list($k2, $v2) = explode(":",$mArray1[$k1]);
		if ($k2 == "function")
			$mFunction = $v2;
		elseif ($k2 == "messagecode")
			$mMessageCode = $v2;
	}
	$mReturn = getMessage($mMessageCode);
	if ($mReturn == "")
		$mReturn = "FAIL-";
//	echo "Test2:".$mReturn.":".$mFilter.":".$mMessageCode;
}
*/
?>