<?php

$format = "json";
if (isset($_REQUEST['format']))
{
	if ($_REQUEST['format'] == 'xml')
	{
		$format = "xml";
	}
	if ($_REQUEST['format'] == 'html')
	{
		$format = "html";
	}
}

$points = [];

//echo 'Searching '.$installfolder.'/addons/status/modules/';
$files = glob($installfolder.'/addons/status/modules/*.php');
$moduleno = 1;
foreach($files as $fl)
{	
	include_once($fl);
	$moduleno++;
}

function cleanup($s)
{
	//echo 'Cleaning '.$s;
	$v = htmlspecialchars($s);

	return $v;
}

function XMLish($s,$lastparent = FALSE)
{
	if (is_numeric($s))
	{
		return XMLish(substr($lastparent,0,strlen($lastparent)-1));
	}
	
	$v = str_replace(" ","_",$s);
	$v = htmlspecialchars($v);
	
	return $v;
}

function ProcessEntries($points)
{
	global $lines;
	$lastbump = count($lines)-1;
	$keys = array_keys($points);
	foreach($keys as $ky)
	{
		if (is_array($points[$ky]))
		{
			//This is a heading...
			$lines[] = '>:'.$ky;			
			ProcessEntries($points[$ky]);
			$lines[] = '<:'.$ky;
		}
		else
		{
			$lines[] = $ky.'='.$points[$ky];
			if ($ky == 'critical')
			{
				$lines[$lastbump] = str_replace(">:","!:",$lines[$lastbump]);
			}
		}
	}
}

$lines = array();
global $lines;
ProcessEntries($points);

//print_r($lines);

if ($format == "json")
{
	header('Content-Type: text/json');	
	echo json_encode($points);
}
if ($format == "xml")
{
	header('Content-Type: text/xml');	
	echo "<status>\r\n";
	$lastparent = array();
	foreach($lines as $k)
	{
		$bits = explode(':',$k);
		
		$lp = FALSE;
		if (count($lastparent) > 0)
		{
			$lp = $lastparent[count($lastparent)-1];
		}
				
		if (($bits[0] == '>') || ($bits[0] == '!'))
		{						
			echo '<'.XMLish($bits[1],$lp).'>';
			
			array_push($lastparent,$bits[1]);
		}
		else
		{
			if ($bits[0] == '<')
			{
				
				$lp = array_pop($lastparent);
				if (count($lastparent) > 0)
				{
					$lp = $lastparent[count($lastparent)-1];
				}
				echo '</'.XMLish($bits[1],$lp).'>';				
			}
			else
			{
				$bits = explode('=',$k);				
				echo '<'.XMLish($bits[0],$lp).'>'.htmlspecialchars($bits[1]).'</'.XMLish($bits[0],$lp).'>';
			}
		}
	}	
	echo "</status>\r\n";
}
if ($format == "html")
{
	//echo '<table>';
	foreach($lines as $k)
	{
		$bits = explode(':',$k);
		if (count($bits) > 1)
		{
			if (is_numeric($bits[1]))
			{
				$bits[1] = "";
			}
		}		
		if ($bits[0] == '>')
		{
			if ($bits[1] != "")
				echo '<h2>'.$bits[1].'</h2>';
			echo '<blockquote>';
		}
		else
		{
			if ($bits[0] == '!')
			{
				if ($bits[1] != "")
					echo '<h2>'.$bits[1].'</h2>';
				echo '<blockquote style="color: red;">';
			}
			else
			{
				if ($bits[0] == '<')
				{
					echo '</blockquote>';
				}
				else
				{
					$bits = explode('=',$k);
					if ($bits[0] != "critical")
					{
						echo '<label style="font-weight: bold;">'.strtoupper($bits[0]).'</label>: '.$bits[1].'<br/>';
					}
				}
			}
		}
	}	
	//echo '</table>';
}
?>