<?php
	// Functions
	function dbg($text) {
		//echo "$text\n";
	}

	function checkTag($tag) {
		$tag = strtolower($tag);

		// Check validity
		$re = "/^[_a-z0-9 :]*$/"; 
		preg_match($re, $tag, $matches);
		if (!$matches)
			die ("Meeeeeow!");

		// Convert for file name
		$tag = substr($tag, 0, 40);
		$tag = str_replace(" ", "__", $tag);
		$tag = str_replace(":", "__", $tag);
		return $tag;
	}
?>
<?php
	header('Content-Type: application/rss+xml; charset=UTF-8');

	//if (!isset($_GET['debug']))
	//	die("Nyan~~");

	// Configuration here
	$refreshTime = 3600; // Update every hour
	$postLimit   = 20;   // Max. 100
	$dateFormat  = "D, d M Y H:i:s O";

	// Generate some variables
	if ($_GET['server'] == "danbooru")
		$selectedServer = "danbooru";
	else
		$selectedServer = "konachan";

	$tag      = $_GET['tag'];
	$santag   = checkTag($tag);
	$tempfile = "/tmp/konasub/$selectedServer/$santag.xml";
	$selfUrl  = "https://shimatta.de/konasub/?tag=$tag";
	dbg ("Tag: \"$tag\" ($santag, $tempfile)\n");
	mkdir ("/tmp/konasub/$selectedServer");

	// Configure server urls and meta data
	$svr['konachan']['imgBase']     = "http://konachan.com/post/show/";
	$svr['konachan']['url']         = 'http://konachan.com/post.xml?tags=' . urlencode($tag) . "&limit=$postLimit";
	$svr['konachan']['title']       = "Konachan: " . htmlspecialchars($tag);
	$svr['konachan']['description'] = "Images for " . htmlspecialchars($tag);
	$svr['konachan']['link']        = "http://konachan.com/post?tags=" . urlencode($tag);
	$svr['konachan']['re']          = "/<post.* author=\\\"(?'author'[^\\ ]*)\\\".* created_at=\\\"(?'created_at'[^\\ ]*)\\\".* id=\\\"(?'id'[^\\ ]*)\\\".* jpeg_url=\\\"(?'jpeg_url'[^\\ ]*)\\\".* tags=\\\"(?'tags'[^\\\"]*)\\\"" . " .*\\/>/";

	dbg ("File mtime delta: " . (time() - filemtime($tempfile)) . " (of $refreshTime)");
	if ((time() - filemtime($tempfile)) > $refreshTime) {
		$cacheFile = fopen($tempfile, "w");
		dbg (" -> Retrieving file...");
		$data = file_get_contents($svr[$selectedServer]['url']);
		fwrite($cacheFile, $data);
		flush();
	}
	else {
		$cacheFile = fopen($tempfile, "r");
		dbg (" -> Loading cached file...");
		$data = fread($cacheFile,filesize($tempfile));
	}
	fclose($cacheFile);

	dbg("BEGIN XML:\n");

	// RSS Header
	// TODO: Maybe change pubDate to date of latest image
	echo '<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
<channel>
 <title>' . $svr[$selectedServer]['title'] . '</title>
 <description><![CDATA[' . $svr[$selectedServer]['description'] . ']]></description>
 <link>' . $svr[$selectedServer]['link'] . '</link>
 <lastBuildDate>' . date($dateFormat, time()) . ' </lastBuildDate>
 <pubDate>' . date($dateFormat, time()) . '</pubDate>
 <ttl>' . $refreshTime . '</ttl>
 <atom:link href="' . $selfUrl . '" rel="self" type="application/rss+xml" />
';
	$all = explode("\n", $data);
	// <post.* id=\"(?'id'[^\ ]*)\".* jpeg_url=\"(?'jpeg_url'[^\ ]*)\" .*\/>
	 
	foreach ($all as $line) {
		preg_match($svr[$selectedServer]['re'], $line, $matches);
		if ($matches) {
			dbg ($matches['id'] . ", " . date($dateFormat, intval($matches['created_at'])) . "@" . $matches['jpeg_url'] . "\n");
			dbg ("    " . $matches['tags'] . "\n");
			$imageLink = $svr[$selectedServer]['imgBase'] . intval($matches['id']);
			echo '
 <item>
  <title>' . "$matches[id]: $matches[tags]" . '</title>
  <description><![CDATA[<a href="' . $imageLink . '"><img src="' . $matches['jpeg_url']. '" style="width:100%"></a>]]></description>
  <link>' . $imageLink . '</link>
  <guid isPermaLink="true">' . $imageLink . '</guid>
  <pubDate>' . date($dateFormat, intval($matches['created_at'])) . '</pubDate>
  <dc:creator>' . $matches['author'] . '</dc:creator>
 </item>
			';
			
		}
	}

	echo '
</channel>
</rss>
';

	dbg ("\nEND XML.");
?>