<?php

// ical2html - displays current and future events from a (single) published iCal .ics file
// by 31d1 djbidi@gmail.com

// User settings:

$calendar = "http://pathto/cal/Home.ics";
$number_to_display = 10;
$timezone_adjust = "3";

// get local date and time

$time = time();
$time = ($time + ($timezone_adjust * 3600));
$curr_date = date("Y m d", $time);

// get published iCal file with curl

$ch = curl_init();
$timeout = 0; // set to zero for no timeout
curl_setopt ($ch, CURLOPT_URL, "$calendar");
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt ($ch, CURLOPT_USERAGENT, $_ENV['HTTP_USER_AGENT']);
$file = curl_exec($ch);
curl_close($ch);

// get published ical file with file_get_contents
// $file = file_get_contents($calendar);

// parse published ical file

$file = explode("\n", $file);

foreach($file as $line) {
 if (ereg("DTSTART;TZID", $line)) {
  preg_match("/(\d\d\d\d\d\d\d\d)T(\d\d\d\d\d\d)/", $line, $matches);
  $dat = preg_replace("/(\d\d\d\d)(\d\d)(\d\d)/", "$1 $2 $3", $matches[1]);
  $tim = preg_replace("/(\d\d)(\d\d)(\d\d)/", "$1:$2", $matches[2]);
  $toprint[] = "$dat $tim ";
 }
 if (ereg("DTSTART;VALUE=DATE", $line)) {
  preg_match("/(\d\d\d\d\d\d\d\d)/", $line, $matches);
  $dat = preg_replace("/(\d\d\d\d)(\d\d)(\d\d)/", "$1 $2 $3", $matches[1]);
  $toprint[] = "$dat &nbsp&nbsp&nbsp&nbsp&nbsp";
 }
 if (ereg("SUMMARY", $line)) {
  preg_match("/SUMMARY:(.+)/", $line, $matches);
  $toprint[] = "$matches[1]";
 }
}

$toprint = array_chunk($toprint, 2);

foreach($toprint as $item) {
 $item = implode(" ", $item);
 $items[] = $item;
}

sort($items);
$i = 0;

// style

?>

<head>
<title>cal</title>
<style type="text/css"><!--
A:link { text-decoration: none }
A:visited { color: #666666 ; text-decoration: none }
A:hover { text-decoration: underline }
body { font-family: Courier ; Monospace ; font-size: 0.8em; }
}--></style>
</head>

<?php

// print matching items

foreach($items as $item) {
 preg_match("/(\d\d\d\d) (\d\d) (\d\d)/", $item, $matches); 

// display future events

 if ($matches[0] > $curr_date) {
  if ($i < $number_to_display) { 
   $item = ereg_replace("^.....", "", $item);
   print "$item<br />";
   $i++;
  }

// today's events

 } elseif ($matches[0] == $curr_date) {
  if ($i < $number_to_display) { 
   $item = preg_replace("/\d\d\d\d \d\d \d\d/", "TODAY ", $item);
   print "$item<br />";
   $i++;
  }
 } 
}

?>