#!/usr/bin/php
<?php
require_once "/usr/local/minerva/bin/inc/utils.inc";

array_shift($argv);
//
$user = array_shift($argv);
$numdays = array_shift($argv);
$calendars = array_shift($argv);

$numdays = max($numdays,1);

if ($username == "") {
  $username = "public";
}

// Find the ical for this username
$array = @file("/usr/local/minerva/etc/users/$user/external/ical");
for($i=0;$i<count($array)-1;$i+=2) {
  if ($calendars == "" || $calendars == $i/2) {
    print getNextEvents($array[$i], "${user}_".$array[$i], trim($array[$i+1]));
  }
}

function getNextEvents($prefix, $name, $url) {
	global $numdays;
	$contents = getContents($url, "cal_$name", 6000);

	$regex = "/BEGIN:VEVENT.*?DTSTART;[^:]*:([^\s]*).*?SUMMARY:([^\n]*).*?END:VEVENT/is";
	preg_match_all($regex, $contents, $matches, PREG_SET_ORDER);

	$all = "";

	$nowseconds = time();
	$dayofseconds = 60*60*24*$numdays;

	for($i=0;$i<sizeof($matches);++$i) {
		$secs = date('U', strtotime($matches[$i][1]));

		if ($secs < $nowseconds) continue;
		if ($secs > $nowseconds+$dayofseconds) continue;

		$event = trim($prefix)."\n";
		$event .= strftime("%A %d %b %Y\n", strtotime($matches[$i][1]));
		$event .= strftime("%l%P\n", strtotime($matches[$i][1]));
		$event .= $matches[$i][2]."\n";
		$all = $event.$all;
	}

return $all;
}

?>

