<?PHP
#
#   FILE:  iCal.php
#
#   Part of the Collection Workflow Integration System (CWIS)
#   Copyright 2013 Edward Almasy and Internet Scout Research Group
#   http://scout.wisc.edu/cwis/
#

# ----- MAIN -----------------------------------------------------------------

# assume that a generic error will occur
$H_State = "Error";

# get object parameters
$EventId = GetArrayValue($_GET, "EventId");

# if the event ID looks invalid
if (!is_numeric($EventId))
{
    $H_State = "Invalid ID";
    return;
}

$Event = new CalendarEvents_Event($EventId);

# if the event ID actually is invalid
if ($Event->Status() !== 1)
{
    $H_State = "Invalid ID";
    return;
}

$H_Plugin = $GLOBALS["G_PluginManager"]->GetPluginForCurrentPage();

# if the entry is some other type of resource
if (!$H_Plugin->IsEvent($Event))
{
    $H_State = "Not Event";
    return;
}

# if the user can't view the event
if (!$Event->UserCanView($GLOBALS["G_User"]))
{
    $H_State = "Viewing not permitted";
    return;
}

# everything is fine
$H_State = "OK";

# record an iCalendar file download
$H_Plugin->RecordEventiCalDownload($Event);

# construct the iCalendar document
$iCalendar = new iCalendar(
    $Event->Id(),
    $Event->Get("Start Date"),
    $Event->Get("End Date"),
    $Event->Get("All Day"));

# add the fields for the event
$iCalendar->AddCreated($Event->Get("Date of Creation"));
$iCalendar->AddSummary(iCalendar::TransformHTMLToPlainText($Event->Get("Title")));
$iCalendar->AddDescription(iCalendar::TransformHTMLToPlainText($Event->Get("Description")));
$iCalendar->AddURL($Event->GetBestUrl());
$iCalendar->AddLocation($Event->OneLineLocation());
$iCalendar->AddCategories($Event->CategoriesForDisplay());

# set up the headers for printing the iCalendar document
$AF->SuppressHTMLOutput();
header("Content-Type: text/Calendar; charset=".$AF->HtmlCharset(), TRUE);
header("Content-Disposition: inline; filename=\"".$iCalendar->GenerateFileName()."\"");

# output the iCalendar document
print $iCalendar->GenerateDocument();
