<?php  header('Content-type: text/calendar; charset=utf-8');

	include("/home/www/pyrot/htdocs/scripts/sqlinfo.inc");

	$link = mysql_connect($host, $user, $pass);
	if ($link == false) exit(0);
	mysql_select_db("pyrot");

	#$date = getdate();
	#$mm = $date["mon"]-6;
	#$dd = $date["mday"];
	#$yyyy = $date["year"];
	
	$ymd = date("Ymd", time());

	$res = mysql_query("SELECT col_id, datum+0, plats, rubrik, info, eventlink FROM event where datum >= " . $ymd . " ORDER BY datum");

	echo "BEGIN:VCALENDAR\r\nVERSION:2.0\r\n";
	echo "PRODID:-//Pyrot LTU//PHP Script//EN\r\n";
	echo "CALSCALE:GREGORIAN\r\nMETHOD:PUBLISH\r\n";

	echo "BEGIN:VTIMEZONE\r\nTZID:Europe/Stockholm\r\n";
	echo "BEGIN:DAYLIGHT\r\n";
	echo "DTSTART:20050327T010000\r\n";
	echo "TZOFFSETTO:+0200\r\n";
	echo "TZOFFSETFROM:+0000\r\n";
	echo "TZNAME:CEST\r\n";
	echo "END:DAYLIGHT\r\n";

	echo "BEGIN:STANDARD\r\n";
	echo "DTSTART:20051030T030000\r\n";
	echo "TZOFFSETTO:+0100\r\n";
	echo "TZOFFSETFROM:+0200\r\n";
	echo "TZNAME:CET\r\n";
	echo "END:STANDARD\r\n";
	echo "END:VTIMEZONE\r\n";

	if ($r = mysql_fetch_array($res)) {
		do {
			echo "BEGIN:VEVENT\r\n";
			echo "DTSTART;VALUE=DATE:";
			echo $r["datum+0"] . "\r\n";
			echo "DTEND;VALUE=DATE:";
			echo $r["datum+0"] . "\r\n";
			echo "SUMMARY:" . $r["rubrik"] . "\r\n";
			echo "LOCATION:" . $r["plats"] . "\r\n";
			echo "DESCRIPTION:" . wrap($r["info"]) . "\r\n";
			echo "END:VEVENT\r\n";
		} while ($r = mysql_fetch_array($res));
	}

	echo "END:VCALENDAR\r\n";

	mysql_close($link);

	function wrap($line) {
		$line = myescape($line);
		$len  = strlen($line);
		if ($len > 70) {
			$sstart = 0;
			$wrapped = "";
			while ($len > 70) {
				$wrapped .= substr($line, $sstart, 70) . "\r\n ";
				$sstart   = $sstart + 70;
				$len = $len - 70;
			}

			if ($len > 0) {
				$wrapped .= substr($line, $sstart);
			}

			return $wrapped;
		} else {
			return $line;
		}
	}

	function myescape($line) {
		
		$line = str_replace(",", "\\,",   $line);
		$line = str_replace("\r\n", "\n", $line);
		$line = str_replace("\n", "\\n",  $line);

		return $line;
	}
?>
