#!/app/apache/modules/1.3/php/5.0.3/bin/php -q
<?php
	include("/home/pyrot/.html/scripts/sqlinfo.inc");
	//$host = "www.apple.se";
	$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("Y-m-d", mktime(0,0,0,$mm,$dd,$yyyy));

	$res = mysql_query("SELECT col_id, datum+0, plats, rubrik, info, eventlink FROM event where datum >= \"$ymd\" ORDER BY datum");
	$file = fopen("/home/pyrot/.html/htdocs/ical/events.ics", "w");

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

	fwrite($file, $line);

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

	fwrite($file, $line);

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

	fwrite($file, $line);

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

			fwrite($file, $line);
		} while ($r = mysql_fetch_array($res));
	}

	fwrite($file, "END:VCALENDAR\r\n");

	fflush($file);
	fclose($file);

	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;
	}
?>
