Create a calendar from del.icio.us bookmarks

Given a del.icio.us username, this PHP script fetches the RSS feed for that user's items tagged with 'cal', detects any tags that are in datetime format (eg 2007-06-21, or 2007-06-21T12:00) and converts those bookmarks into iCal events.

Put this script somewhere on your server and subscribe to it in your calendar application for an instant bookmark→calendar experience.

If anyone wants to recreate this in Python and stick it on Google App Engine for anyone to use, that would be ideal.

<?php
$username = 'hublicious'; # edit this
$timezone = 'Europe/London'; # edit this
$rss = simplexml_load_file("http://feeds.delicious.com/rss/{$username}/cal");
$rss->registerXPathNamespace('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#');
$rss->registerXPathNamespace('taxo', 'http://purl.org/rss/1.0/modules/taxonomy/');
$now = time();
$items = array();
foreach ($rss->item as $item){
  $tags = $item->xpath('taxo:topics/rdf:Bag/rdf:li/@resource');
  if (empty($tags)) continue;
  
  $start = NULL;
  foreach ($tags as $tag)
    if (preg_match('/^http:\/\/del\.icio\.us\/tag\/(\d{4}-\d{2}-\d{2})(.*)$/', $tag, $matches))
      $start = strtotime($matches[1] . $matches[2]);
  
  if (!$start || $start < $now) continue;
  
  if ($matches[2]){
    $prefix = NULL;
    $format = 'Ymd\THis';
  }
  else{ // all day
    $prefix = ';VALUE=DATE';
    $format = 'Ymd';
  }
    
  $items[] = sprintf(
    "BEGIN:VEVENT\nDTSTART%s:%s\nDTEND%s:%s\nSUMMARY:%s\nDESCRIPTION:%s\nURL;VALUE=URI:%s\nEND:VEVENT",
    $prefix,
    date($format, $start),
    $prefix,
    date($format, $start + 3600 * ($prefix ? 24 : 1)), // 24hr if all-day, else 1hr
    saniCal($item->title),
    saniCal($item->description),
    saniCal($item->link)
    );   
}
function saniCal($text){
  return str_replace(array("\n", ',', ';'), array('\\n', '\,', '\;'), $text);
}
header('Content-Type: text/calendar;charset=utf-8');
header('Content-Disposition: attachment;filename="delical.ics"');
printf("BEGIN:VCALENDAR\nVERSION:2.0\nX-WR-CALNAME:del.icio.us\nX-WR-TIMEZONE:%s\n%s\nEND:VCALENDAR\n", $timezone, implode("\n", $items));