<?php

// RSS feed for myChess
// ````````````````````

require_once 'common.php';
require 'db.php';

header("Content-Type: application/xml");

$rss_title = APP_NAME;
$rss_url = main_url();
$rss = array(
		0 => array(
			'item' => APP_NAME,
			'link' => $rss_url,
			'desc' => '',
			'guid' => 0
		)
	);
$game = array(
	'id'=>0
);

do {
	// Validate request
	if (! isset($_GET['id'])) {
		$rss[0]['desc'] = E_INVREQ;
		break;
	}

	// Validate hash
	$game['auth'] = $_GET['id'];
	list($game['id'], $game['whoami']) = DB\SearchHash($_GET['id']);
	if (! $game['id']) {
		$rss[0]['desc'] = E_INVGAME;
		break;
	}
		
	// Retrieve game parameters
	DB\GetGame();
	
	// Set RSS details
	$rss_title = htmlspecialchars($game['player1']['name'].' v '.$game['player2']['name']);
	$rss_url   = $rss_url . '?p=game&amp;id='.$game['auth'];
	$rss = array();
	
	// Dig up board history
	$history = DB\GetHistory($game['id'], RSS_ITEMCOUNT);
	foreach ($history as $hitem) {
		
		// Determine content parameters
		if ($hitem['type'] == 1) {
			$h_content = 'Action: '.$hitem['val'];
			$h_player = ($hitem['key'] == PLAYER_W) ? PLAYER_B : PLAYER_W;
			if (! strlen($hitem['val'])) $h_player = PLAYER_W;
		} else {
			$h_content = $hitem['val'];
			$h_player = $hitem['key'];
		}
		$h_author = ($h_player == PLAYER_W) ? $game['player1']['name'] : $game['player2']['name'];
		
		// Determine title
		if ($hitem['type'] == 1) {
			$h_title = $h_content;
		} else {
			$h_title = $h_content;
			if (strlen($h_content) > 40) $h_title = substr($h_title, 0, 37).'...';			
			$h_content = nl2br(htmlspecialchars($h_content));
			$h_title   = htmlspecialchars($h_title);
		}
		
		$h_guid = md5(serialize($hitem));
		
		// Store the item
		$rss[] = array(
			'title'   => $h_title,
			'content' => $h_content,
			'player'  => $h_player,
			'guid'    => $h_guid,
			'time'    => $hitem['time'],
			'author'  => RSS_EMAIL . ' ('.$h_author.')'
		);
	}
	
} while (false);

echo '<?xml version="1.0" encoding="UTF-8" ?>';
?> 
<rss version="2.0"> 
	<channel> 
		<title><?php echo $rss_title; ?></title> 
		<link><?php echo $rss_url; ?></link> 
		<description>Powered by <?php echo APP_NAME; ?></description> 
		<language>en-GB</language> 
<?php
	foreach ($rss as $item) {
?> 
		<item>
			<title><?php echo $item['title']; ?></title>
			<link><?php echo $rss_url; ?></link>
			<guid><?php echo $rss_url.'#'.$item['guid'] ?></guid>
			<author><?php echo htmlspecialchars($item['author']); ?></author>
			<pubDate><?php echo date(DATE_RSS, $item['time']); ?></pubDate>
			<description>
				<![CDATA[<?php echo $item['content']; ?>]]>
			</description>
		</item>
<?php
	}
?> 
	</channel>
</rss>
