<?php
	
// get_chat_status.php
// -------------------------------------------------------------------------------------------------
// Get the status of the chat operators
//
// Project    > dmClubNewYear08:C37
// Copyright  > (C) Digital Mail Limited (2005-2008)
// Author     > Richard Knight (RAK) for DML
// -------------------------------------------------------------------------------------------------

if (!defined('DOCROOT')) define('MOD_PHP', substr(PHP_SAPI, 0, 3) != 'cgi'); // Are we running as mod_php?
define('DOCROOT', 
	isset($_SERVER['DOCUMENT_ROOT']) ? 
		$_SERVER['DOCUMENT_ROOT'] : 
		(
			MOD_PHP && isset($_SERVER['SCRIPT_FILENAME']) ? 
				substr($_SERVER['SCRIPT_FILENAME'], 0, 0-strlen($_SERVER['PHP_SELF'])) : 
				(
					substr(str_repeat('../', count(explode('/', preg_replace('_/+_', '/', $_SERVER['PHP_SELF'])))-2), 0, -1) != '' ?
						substr(str_repeat('../', count(explode('/', preg_replace('_/+_', '/', $_SERVER['PHP_SELF'])))-2), 0, -1) :
						'.'
				)
		)
	);
include_once(DOCROOT . '/dmx/dmx_options.php');
include_once(DOCROOT . '/dmx/dmx_library.php');

// SET RESULTS
if (strpos(__FILE__, $_SERVER['PHP_SELF'])) {
	// This script has been hit directly
	// So return XML, JSON, or a simple status code (depending on the value of the GET param res_type)
	$ops = webchat_get_status($dmx_options['chatserver']);
	switch (isset($_GET['res_type']) ? strtolower($_GET['res_type']) : '') {
		case 'json':
			// Retuen the entire $ops array as a JSON
			$json = new Services_JSON(); // Create a new instance of Services_JSON
			echo 'var dmx_webchat = ' . $json->encode($ops) . ";\n";
			break;
		case 'js':
			// Create a simple variable containing the number of operators online
			echo 'var dmx_webchat = ' . $ops['all']['num'] . ";\n";
			break;
		case 'xml':
			// Create an XML document with nodes corresponding to elements of the $ops array
			$xml = dmx_make_xml('chatstatus', $ops);
			// Output the XML document
			header('Pragma: no-cache'); // for HTTP 1.0
			header('Cache-Control: no-cache, must-revalidate'); // for HTTP 1.1
			header('Content-type: text/xml');
			echo($xml);
			break;
		default:
			// Just echo the number of operators online
			echo $ops['all']['num'];
	}
	exit;
} else {
	// This script has been included in another PHP page, so put webchat operator data in the
	// global variable $dmx_webchat
	$GLOBALS['dmx_options']['webchat'] = webchat_get_status($dmx_options['chatserver']);
}

// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------

function webchat_get_status($chat_server) {
	// Parse the HTML table returned by the Chat Server (listing operators online),
	// collating the data into the array $ops
	//
	// $ops['chatserver'] contains the domain name or IP address of the chat server;
	//
	// $ops['all'] contains data about all departments:
	// $ops['all']['num']   = The total number of chat operators available, eg 2
	// $ops['all']['depts'] = A list of departments online (each preceded and followed by '#') eg '#Technical Support#Sales#'
	// $ops['all']['names'] = A list of operators online   (each preceded and followed by '#') eg '#Rich#Sascha#'
	// 
	// $ops['depts'] contains similar information of a department by department basis, eg:
	// $ops['depts']['technical_support']['num']   = 1;
	// $ops['depts']['technical_support']['names'] = '#Rich#';
	// $ops['depts']['sales']['num']   = 1;
	// $ops['depts']['sales']['names'] = '#Sascha#';
	//
	// $ops['operators'] contains the status of each operator (COMMENTED OUT AT THE MOMENT - BUT WORKS)
	//
	// Note that when used in the depts sub-array, the department name is lowercase,
	// with spaces replaced by underscores, eg: 'Technical Support' => 'technical_support'
	//
	// $chat_server is the chat server address
	//
	$ops = array();
	$ops['chatserver'] = $chat_server;
	$ops['all']['num']   = 0;
	$ops['all']['depts'] = '#';
	$ops['all']['names'] = '#';
	$r = dmx_execute_get($chat_server . '/chat/' . $_SERVER['HTTP_HOST'] . '.htm', array(), 3);
	If ($r['status']) {
		preg_match('/(<tr>.*)<\/table>/is', $r['response'], $m1);
		preg_match_all('/<tr>(.*)<\/tr>/isU', $m1[1], $m2);
		$rows = $m2[1];
		for ($i=0; $i<count($rows); $i++) {
			preg_match('/<td>(.*)<\/td>.*<td>(.*)<\/td>.*<td>(.*)<\/td>/isU', $rows[$i], $t);
			$t[2] = $t[2] ? $t[2] : 'Support'; // 'Support' is the default if this is empty
			$dept = strtolower(str_replace(' ', '_', $t[2]));
			$online = strtolower($t[3]) == 'on-line';
			$ops['all']['num']+=(int) $online;
			if (strpos($ops['all']['depts'], '#' . $t[2] . '#') === FALSE) {
				$ops['all']['depts'] .= $t[2] . '#';
				$ops['depts'][$dept]['num']   = $online ? 1 : 0;
				$ops['depts'][$dept]['names'] = '#';
			} else {
				if ($online) $ops['depts'][$dept]['num']++;
			}
			if ($online) $ops['all']['names']          .= $t[1] . '#';
			if ($online) $ops['depts'][$dept]['names'] .= $t[1] . '#';
			// $ops['operators'][$i+1] = array('name' => $t[1], 'dept' => $t[2], 'status' => $t[3]);
		}
	}
	if ($ops['all']['depts'] == '#') $ops['all']['depts'] = ''; // Just some tidying up
	if ($ops['all']['names'] == '#') $ops['all']['names'] = '';
	return $ops;
}

// -------------------------------------------------------------------------------------------------

function dmx_make_xml($root, $array, $level = 0) {
	// Convert an array into simple XML
	// If an array index is numeric, use <i v="NUMERIC-INDEX">VALUE</i>
	//
	$xml  = $level ? '' : "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
	$indent = str_repeat("\t", $level);
	$xml .= $indent . (is_numeric($root) ? "<i v=\"$root\">\n" : "<$root>\n");
	foreach($array as $key => $value) {
		if (is_array($value)) {
			$xml .= dmx_make_xml($key, $value, $level+1);
		} else {
			if (is_numeric($key)) {
				$xml .= $indent . "\t<i v=\"" . $key . '">' . htmlentities($value) . "</i>\n";
			} else {
				$xml .= $indent . "\t<" . $key . '>' . htmlentities($value) . '</' . $key . ">\n";
			}
		}
	}
	$xml .= $indent . (is_numeric($root) ? "</i>\n" : "</$root>\n");
	return $xml;
}

?>