<?php

require_once KRONOLITH_BASE . '/lib/Driver.php';

define('KRONOLITH_RECUR_NONE',          0);
define('KRONOLITH_RECUR_DAILY',         1);
define('KRONOLITH_RECUR_WEEKLY',        2);
define('KRONOLITH_RECUR_DAY_OF_MONTH',  3);
define('KRONOLITH_RECUR_WEEK_OF_MONTH', 4);
define('KRONOLITH_RECUR_YEARLY',        5);

define('KRONOLITH_STATUS_NONE', 0);
define('KRONOLITH_STATUS_TENTATIVE', 1);
define('KRONOLITH_STATUS_CONFIRMED', 2);
define('KRONOLITH_STATUS_CANCELLED', 3);

define('KRONOLITH_RESPONSE_NONE',      1);
define('KRONOLITH_RESPONSE_ACCEPTED',  2);
define('KRONOLITH_RESPONSE_DECLINED',  3);
define('KRONOLITH_RESPONSE_TENTATIVE', 4);

define('KRONOLITH_PART_REQUIRED', 1);
define('KRONOLITH_PART_OPTIONAL', 2);
define('KRONOLITH_PART_NONE',     3);
define('KRONOLITH_PART_IGNORE',   4);

define('KRONOLITH_ITIP_REQUEST', 1);
define('KRONOLITH_ITIP_CANCEL',  2);

define('KRONOLITH_ERROR_FB_NOT_FOUND', 1);

/**
 * The Kronolith:: class provides functionality common to all of
 * Kronolith.
 *
 * $Horde: kronolith/lib/Kronolith.php,v 1.263.2.3 2005/02/02 13:23:14 jan Exp $
 *
 * @author  Chuck Hagenbuch <chuck@horde.org>
 * @since   Kronolith 0.1
 * @package Kronolith
 */
class Kronolith {

    /**
     * Returns all the events that happen each day within a time
     * period.
     *
     * @param object $startDate    The start of the time range.
     * @param object $endDate      The end of the time range.
     * @param array  $calendars    The calendars to check for events.
     *
     * @return array  The events happening in this time period.
     */
    function listEventIds($startDate = null, $endDate = null, $calendars = null)
    {
        global $kronolith;

        if (!isset($startDate)) {
            $startDate = &new Horde_Date(time());
        } else {
            $startDate = Util::cloneObject(new Horde_Date($startDate));
        }
        if (!isset($endDate)) {
            $endDate = &new Horde_Date(time());
        } else {
            $endDate = Util::cloneObject(new Horde_Date($endDate));
        }
        if (!isset($calendars)) {
            $calendars = $GLOBALS['display_calendars'];
        }

        $eventIds = array();
        foreach ($calendars as $cal) {
            if ($kronolith->getCalendar() != $cal) {
                $kronolith->close();
                $kronolith->open($cal);
            }
            $eventIds[$cal] = $kronolith->listEvents($startDate, $endDate);
        }

        return $eventIds;
    }

    /**
     * Returns all the alarms active right on $date.
     *
     * @param object $date         The start of the time range.
     * @param array  $calendars    The calendars to check for events.
     *
     * @return array  The alarms active on $date.
     */
    function listAlarms($date, $calendars)
    {
        global $kronolith;

        $alarms = array();
        foreach ($calendars as $cal) {
            if ($kronolith->getCalendar() != $cal) {
                $kronolith->close();
                $kronolith->open($cal);
            }
            $alarms[$cal] = $kronolith->listAlarms($date);
        }

        return $alarms;
    }

    /**
     * Search for events with the given properties
     *
     * @param object $query  The search query
     *
     * @return array  The events
     */
    function search($query)
    {
        global $kronolith;

        if (!isset($query->calendars)) {
            $calendars = $GLOBALS['display_calendars'];
        }

        $events = array();
        foreach ($calendars as $cal) {
            if ($kronolith->getCalendar() != $cal) {
                $kronolith->close();
                $kronolith->open($cal);
            }
            $retevents = $kronolith->search($query);
            foreach ($retevents as $event) {
                $events[] = $event;
            }
        }

        return $events;
    }

    /**
     * Fetch a remote calendar into the session and return the data.
     *
     * @param string $url  The location of the remote calendar.
     *
     * @return mixed  Either the calendar data, or an error on failure.
     */
    function getRemoteCalendar($url)
    {
        if (empty($_SESSION['kronolith']['remote'][$url])) {
            $options['method'] = 'GET';
            $options['timeout'] = 5;
            $options['allowRedirects'] = true;

            require_once 'HTTP/Request.php';
            $http = &new HTTP_Request($url, $options);
            @$http->sendRequest();
            if ($http->getResponseCode() != 200) {
                Horde::logMessage(sprintf('Failed to retrieve remote calendar: url = "%s", status = %s',
                                          $url, $http->getResponseCode()), __FILE__, __LINE__, PEAR_LOG_ERR);
                return PEAR::raiseError(sprintf(_("Could not open %s."), $url));
            }
            $_SESSION['kronolith']['remote'][$url] = $http->getResponseBody();

            /* Log fetch at DEBUG level */
            Horde::logMessage(sprintf('Retrieved remote calendar for %s: url = "%s"',
                                      Auth::getAuth(), $url), __FILE__, __LINE__, PEAR_LOG_DEBUG);
        }

        return $_SESSION['kronolith']['remote'][$url];
    }

    /**
     * Returns all the events from a remote calendar.
     *
     * @param string $url  The url of the remote calendar.
     */
    function listRemoteEvents($url)
    {
        global $kronolith;

        $data = Kronolith::getRemoteCalendar($url);
        if (is_a($data, 'PEAR_Error')) {
            return $data;
        }

        require_once 'Horde/iCalendar.php';
        $iCal = &new Horde_iCalendar();
        if (!$iCal->parsevCalendar($data)) {
            return array();
        }

        $components = $iCal->getComponents();
        $events = array();
        $count = count($components);
        for ($i = 0; $i < $count; $i++) {
            $component = $components[$i];
            if ($component->getType() == 'vEvent') {
                $event = &$kronolith->getEvent();
                $event->fromiCalendar($component);
                $event->remoteCal = $url;
                $event->eventIndex = $i;
                $events[] = $event;
            }
        }

        return $events;
    }

    /**
     * Returns an event object for an event on a remote calendar.
     *
     * This is kind of a temorary solution until we can have multiple
     * drivers in use at the same time.
     *
     * @param $url      The url of the remote calendar.
     * @param $eventId  The index of the event on the remote calenar.
     *
     * @return object Kronolith_Event   The event object.
     */
    function getRemoteEventObject($url, $eventId)
    {
        global $kronolith;

        $data = Kronolith::getRemoteCalendar($url);
        if (is_a($data, 'PEAR_Error')) {
            return $data;
        }

        require_once 'Horde/iCalendar.php';
        $iCal = &new Horde_iCalendar();
        if (!$iCal->parsevCalendar($data)) {
            return array();
        }

        $components = $iCal->getComponents();
        if (isset($components[$eventId]) && $components[$eventId]->getType() == 'vEvent') {
            $event = &$kronolith->getEvent();
            $event->fromiCalendar($components[$eventId]);
            $event->remoteCal = $url;
            $event->eventIndex = $eventId;

            return $event;
        }

        return false;
    }

    /**
     * Returns all the events that happen each day within a time period
     *
     * @param int|Horde_Date $startDate  The start of the time range.
     * @param int|Horde_Date $endDate    The end of the time range.
     * @param array $calendars           The calendars to check for events.
     * @param boolean $showRecurrence    Return every instance of a recurring
     *                                   event? If false, will only return
     *                                   recurring events once inside the
     *                                   $startDate - $endDate range.
     *
     * @return array  The events happening in this time period.
     */
    function listEvents($startDate = null, $endDate = null, $calendars = null, $showRecurrence = true)
    {
        global $kronolith, $prefs, $registry;

        if (!isset($startDate)) {
            $startDate = &new Horde_Date(time());
        } else {
            $startDate = Util::cloneObject(new Horde_Date($startDate));
        }
        if (!isset($endDate)) {
            $endDate = &new Horde_Date(time());
        } else {
            $endDate = Util::cloneObject(new Horde_Date($endDate));
        }
        if (!isset($calendars)) {
            $calendars = $GLOBALS['display_calendars'];
        }

        $eventIds = Kronolith::listEventIds($startDate, $endDate, $calendars);

        $startOfPeriodTimestamp = mktime(0, 0, 0, $startDate->month, $startDate->mday, $startDate->year);
        $endOfPeriodTimestamp = mktime(23, 59, 59, $endDate->month, $endDate->mday, $endDate->year);
        $daysInPeriod = Date_Calc::dateDiff($startDate->mday, $startDate->month, $startDate->year, $endDate->mday, $endDate->month, $endDate->year);

        $results = array();
        foreach ($eventIds as $cal => $events) {
            if ($kronolith->getCalendar() != $cal) {
                $kronolith->close();
                $kronolith->open($cal);
            }
            foreach ($events as $id) {
                // We MUST fetch each event right before getting its
                // recurrences; this is due to the way MCAL
                // works. MCAL's nextRecurrence() function gives you
                // the next recurrence for the event most recently
                // fetched. So if you fetch all events and then loop
                // through them, every recurrence you get will be for
                // the last event that you fetched.
                $event = &$kronolith->getEvent($id);

                Kronolith::_getEvents($results, $event, $startDate, $endDate, $startOfPeriodTimestamp, $endOfPeriodTimestamp, $showRecurrence);
            }
        }

        /* Nag Tasks. */
        if ($prefs->getValue('show_tasks') && $registry->hasMethod('tasks/listTasks')) {
            $taskList = $registry->call('tasks/listTasks');
            if (!is_a($taskList, 'PEAR_Error')) {
                $kronolith->open(Kronolith::getDefaultCalendar(PERMS_SHOW));
                $dueEndStamp = mktime(0, 0, 0, $endDate->month, $endDate->mday + 1, $endDate->year);
                foreach ($taskList as $task) {
                    if ($task['due'] >= $startOfPeriodTimestamp && $task['due'] < $dueEndStamp && empty($task['completed'])) {
                        $event = &$kronolith->getEvent();
                        $event->setTitle(sprintf(_("Due: %s"), $task['name']));
                        $event->taskID = $task['task_id'];
                        $event->tasklistID = $task['tasklist_id'];
                        if ($prefs->getValue('show_task_colors') && isset($task['category'])) {
                            $event->category = isset($task['category']) ? $task['category'] : null;
                        }
                        $event->start = &new Horde_Date($task['due']);
                        $event->end = &new Horde_Date($task['due'] + 1);
                        $dayStamp = mktime(0, 0, 0,
                                           date('n', $task['due']),
                                           date('j', $task['due']),
                                           date('Y', $task['due']));
                        $results[$dayStamp]['_task' . $task['task_id']] = $event;
                    }
                }
            }
        }

        /* Remote Calendars. */
        foreach ($GLOBALS['display_remote_calendars'] as $url) {
            $events = Kronolith::listRemoteEvents($url);
            if (!is_a($events, 'PEAR_Error')) {
                $kronolith->open(Kronolith::getDefaultCalendar(PERMS_SHOW));
                foreach ($events as $event) {
                    Kronolith::_getEvents($results, $event, $startDate, $endDate, $startOfPeriodTimestamp, $endOfPeriodTimestamp, $showRecurrence);
                }
            }
        }

        foreach ($results as $day => $devents) {
            if (count($devents)) {
                uasort($devents, array('Kronolith', '_sortEventStartTime'));
                $results[$day] = $devents;
            }
        }

        return $results;
    }

    /**
     * Returns recurrences of an event during a certain period.
     *
     * @access private
     *
     * @return array  The list of recurrences.
     */
    function &_getEvents(&$results, &$event, $startDate, $endDate,
                         $startOfPeriodTimestamp, $endOfPeriodTimestamp,
                         $showRecurrence)
    {
        global $kronolith;

        if (!$event->hasRecurType(KRONOLITH_RECUR_NONE) && $showRecurrence) {
            /* Recurring Event */

            if ($event->start->timestamp() < $startOfPeriodTimestamp) {
                // The first time the event happens was before the
                // period started. Start searching for recurrences
                // from the start of the period.
                $next = array('year' => $startDate->year, 'month' => $startDate->month, 'mday' => $startDate->mday);
            } else {
                // The first time the event happens is in the
                // range; unless there is an exception for
                // this ocurrence, add it.
                if (!$event->hasException($event->start->year,
                                          $event->start->month,
                                          $event->start->mday)) {
                    $results[mktime(0, 0, 0, $event->start->month, $event->start->mday, $event->start->year)][$event->getID()] = $event;
                }

                // Start searching for recurrences from the
                // day after it starts.
                $next = Util::cloneObject($event->start);
                $next->mday++;
                $next->correct();
            }

            // Add all recurrences of the event.
            $next = $event->nextRecurrence($next);
            while ($next !== false && $next->compareDate($endDate) <= 0) {
                if (!$event->hasException($next->year, $next->month, $next->mday)) {
                    $results[$next->datestamp()][$event->getID()] = $event;
                }
                $next = $event->nextRecurrence(array('year' => $next->year,
                                                     'month' => $next->month,
                                                     'mday' => $next->mday + 1,
                                                     'hour' => $next->hour,
                                                     'min' => $next->min,
                                                     'sec' => $next->sec));
            }
        } else {
            /* Event only occurs once. */

            // Work out what day it starts on.
            if ($event->start->timestamp() < $startOfPeriodTimestamp) {
                // It started before the beginning of the period.
                $eventStartStamp = $startOfPeriodTimestamp;
            } else {
                $eventStartStamp = $event->start->timestamp();
            }

            // Work out what day it ends on.
            if ($event->end->timestamp() >= $endOfPeriodTimestamp) {
                // Ends after the end of the period.
                $eventEndStamp = $endOfPeriodTimestamp;
            } else {
                // If the event doesn't end at 12am set the
                // end date to the current end date. If it
                // ends at 12am and does not end at the same
                // time that it starts (0 duration), set the
                // end date to the previous day's end date.
                if ($event->end->hour != 0 ||
                    $event->end->min != 0 ||
                    $event->start->timestamp() == $event->end->timestamp()) {
                    $eventEndStamp = $event->end->timestamp();
                } else {
                    $eventEndStamp = mktime(23, 59, 59,
                                            $event->end->month,
                                            $event->end->mday - 1,
                                            $event->end->year);
                }
            }

            // Add the event to all the days it covers.
            $i = date('j', $eventStartStamp);
            $loopStamp = mktime(0, 0, 0,
                                date('n', $eventStartStamp),
                                $i,
                                date('Y', $eventStartStamp));
            while ($loopStamp <= $eventEndStamp) {
                if (!($event->isAllDay() && $loopStamp == $eventEndStamp)) {
                    $results[$loopStamp][$event->getID()] = $event;
                }
                $loopStamp = mktime(0, 0, 0,
                                    date('n', $eventStartStamp),
                                    ++$i,
                                    date('Y', $eventStartStamp));
            }
        }
    }

    /**
     * Maps a Kronolith recurrence value to a translated string
     * suitable for display.
     *
     * @param integer $type   The recurrence value; one of the
     *                        KRONOLITH_RECUR_XXX constants.
     *
     * @return string   The translated displayable recurrence value string.
     */
    function recurToString($type)
    {
        switch ($type) {
        case KRONOLITH_RECUR_NONE:
            return _("Does not recur");

        case KRONOLITH_RECUR_DAILY:
            return _("Recurs daily");

        case KRONOLITH_RECUR_WEEKLY:
            return _("Recurs weekly");

        case KRONOLITH_RECUR_DAY_OF_MONTH:
        case KRONOLITH_RECUR_WEEK_OF_MONTH:
            return _("Recurs monthly");

        case KRONOLITH_RECUR_YEARLY:
            return _("Recurs yearly");
        }
    }

    /**
     * Maps a Kronolith meeting status string to a translated string
     * suitable for display.
     *
     * @param integer $status   The meeting status; one of the
     *                          KRONOLITH_STATUS_XXX constants.
     *
     * @return string   The translated displayable meeting status string.
     */
    function statusToString($status)
    {
        switch ($status) {
        case KRONOLITH_STATUS_CONFIRMED:
            return _("Confirmed");

        case KRONOLITH_STATUS_CANCELLED:
            return _("Cancelled");

        case KRONOLITH_STATUS_TENTATIVE:
        default:
            return _("Tentative");
        }
    }

    /**
     * Maps a Kronolith attendee response string to a translated
     * string suitable for display.
     *
     * @param integer $response  The attendee response; one of the
     *                           KRONOLITH_RESPONSE_XXX constants.
     *
     * @return string   The translated displayable attendee response string.
     */
    function responseToString($response)
    {
        switch ($response) {
        case KRONOLITH_RESPONSE_ACCEPTED:
            return _("Accepted");

        case KRONOLITH_RESPONSE_DECLINED:
            return _("Declined");

        case KRONOLITH_RESPONSE_TENTATIVE:
            return _("Tentative");

        case KRONOLITH_RESPONSE_NONE:
        default:
            return _("None");
        }
    }

    /**
     * Maps a Kronolith attendee participation string to a translated
     * string suitable for display.
     *
     * @param integer $part     The attendee participation; one of the
     *                          KRONOLITH_PART_XXX constants.
     *
     * @return string   The translated displayable attendee participation string.
     */
    function partToString($part)
    {
        switch ($part) {
        case KRONOLITH_PART_OPTIONAL:
            return _("Optional");

        case KRONOLITH_PART_NONE:
            return _("None");

        case KRONOLITH_PART_REQUIRED:
        default:
            return _("Required");
        }
    }

    /**
     * Maps an iCalendar attendee response string to the corresponding
     * Kronolith value.
     *
     * @param string $response   The attendee response.
     *
     * @return string   The Kronolith response value.
     */
    function responseFromICal($response)
    {
        switch (String::upper($response)) {
        case 'ACCEPTED':
            return KRONOLITH_RESPONSE_ACCEPTED;

        case 'DECLINED':
            return KRONOLITH_RESPONSE_DECLINED;

        case 'TENTATIVE':
            return KRONOLITH_RESPONSE_TENTATIVE;

        case 'NEEDS-ACTION':
        default:
            return KRONOLITH_RESPONSE_NONE;
        }
    }

    /**
     * Builds the HTML for an event status widget.
     *
     * @param string  $name     The name of the widget.
     * @param string  $current  (optional) The selected status value.
     * @param string  $any      (optional) Whether an 'any' item should be added
     *
     * @return string       The HTML <select> widget.
     */
    function buildStatusWidget($name, $current = KRONOLITH_STATUS_CONFIRMED, $any = false)
    {
        $html = "<select id=\"$name\" name=\"$name\">";

        $statii = array(
            KRONOLITH_STATUS_TENTATIVE,
            KRONOLITH_STATUS_CONFIRMED,
            KRONOLITH_STATUS_CANCELLED
        );

        if (!isset($current)) {
            $current = KRONOLITH_STATUS_NONE;
        }

        if ($any) {
            $html .= "<option value=\"" . KRONOLITH_STATUS_NONE . "\"";
            $html .= ($current == KRONOLITH_STATUS_NONE) ? ' selected="selected">' : '>';
            $html .= _("Any") . "</option>";
        }

        foreach ($statii as $status) {
            $html .= "<option value=\"$status\"";
            $html .= ($status == $current) ? ' selected="selected">' : '>';
            $html .= Kronolith::statusToString($status) . "</option>";
        }
        $html .= '</select>';

        return $html;
    }

    /**
     * List all calendars a user has access to, according to several
     * parameters/permission levels.
     *
     * @param optional boolean $owneronly  Only return calenders that this
     *                                     user owns? Defaults to false.
     * @param optional integer $permission The permission to filter calendars by.
     *
     * @return array  The calendar list.
     */
    function listCalendars($owneronly = false, $permission = PERMS_SHOW)
    {
        $calendars = $GLOBALS['kronolith_shares']->listShares(Auth::getAuth(), $permission, $owneronly ? Auth::getAuth() : null);
        if (is_a($calendars, 'PEAR_Error')) {
            Horde::logMessage($calendars, __FILE__, __LINE__, PEAR_LOG_ERR);
            return array();
        }

        return $calendars;
    }

    /**
     * Get the default calendar for the current user at the specified
     * permissions level.
     */
    function getDefaultCalendar($permission = PERMS_SHOW)
    {
        global $prefs;

        $default_share = $prefs->getValue('default_share');
        $calendars = Kronolith::listCalendars(false, $permission);

        if (isset($calendars[$default_share])) {
            return $default_share;
        } elseif ($prefs->isLocked('default_share')) {
            return '';
        } elseif (count($calendars)) {
            return key($calendars);
        }

        return false;
    }

    /**
     * Calculate the border (darker) version of a color.
     *
     * @param string $color   An HTML color, e.g.: #ffffcc.
     *
     * @return string  A darker html color.
     */
    function borderColor($color)
    {
        return Horde_Image::modifyColor($color, -0x44);
    }

    /**
     * Calculate the highlight (lighter) version of a color.
     *
     * @param string $color   An HTML color, e.g.: #ffffcc.
     *
     * @return string  A lighter html color.
     */
    function highlightColor($color)
    {
        return Horde_Image::modifyColor($color, 0x44);
    }

    /**
     * Generate the free/busy text for $calendar. Cache it for at
     * least an hour, as well.
     *
     * @access public
     *
     * @param string | $calendar    The calendar to view free/busy slots for.
     *        array
     * @param integer  $startstamp  The start of the time period to retrieve.
     * @param integer  $endstamp    The end of the time period to retrieve.
     * @param boolean  $returnObj   (optional) Default false. Return a vFreebusy
     *                              object instead of text.
     *
     * @return string  The free/busy text.
     */
    function generateFreeBusy($calendar, $startstamp = null, $endstamp = null, $returnObj = false)
    {
        global $kronolith_shares, $prefs;

        require_once 'Horde/Identity.php';
        require_once 'Horde/iCalendar.php';
        require_once KRONOLITH_BASE . '/lib/version.php';

        if (!is_array($calendar)) {
            $calendar = array($calendar);
        }

        // Fetch the appropriate share and check permissions.
        $share = &$kronolith_shares->getShare($calendar[0]);
        if (is_a($share, 'PEAR_Error')) {
            return '';
        }

        // Default the start date to today.
        if (is_null($startstamp)) {
            $month = date('n');
            $year = date('Y');
            $day = date('j');

            $startstamp = mktime(0, 0, 0, $month, $day, $year);
        }

        // Default the end date to the start date + freebusy_days.
        if (is_null($endstamp) || $endstamp < $startstamp) {
            $month = date('n', $startstamp);
            $year = date('Y', $startstamp);
            $day = date('j', $startstamp);

            $endstamp = mktime(0, 0, 0, $month,
                               $day + $prefs->getValue('freebusy_days'), $year);
        }

        // Get the Identity for the owner of the share.
        $identity = &Identity::singleton('none', $share->get('owner'));
        $email = $identity->getValue('from_addr');
        $cn = $identity->getValue('fullname');

        // Fetch events.
        $startDate = &new Horde_Date($startstamp);
        $endDate = &new Horde_Date($endstamp);
        $busy = Kronolith::listEvents($startDate, $endDate, $calendar);

        // Create the new iCalendar.
        $vCal = &new Horde_iCalendar();
        $vCal->setAttribute('PRODID', '-//The Horde Project//Kronolith ' . KRONOLITH_VERSION . '//EN');
        $vCal->setAttribute('METHOD', 'PUBLISH');

        // Create new vFreebusy.
        $vFb = &Horde_iCalendar::newComponent('vfreebusy', $vCal);
        $params = array();
        if (!empty($cn)) {
            $params['CN'] = $cn;
        }
        if (!empty($email)) {
            $vFb->setAttribute('ORGANIZER', 'MAILTO:' . $email, $params);
        } else {
            $vFb->setAttribute('ORGANIZER', '', $params);
        }

        $vFb->setAttribute('DTSTAMP', time());
        $vFb->setAttribute('DTSTART', $startDate);
        $vFb->setAttribute('DTEND', $endDate);
        $vFb->setAttribute('URL', Horde::applicationUrl('fb.php?c=' . implode('|', $calendar), true, -1));

        // Add all the busy periods.
        foreach ($busy as $day => $events) {
            foreach ($events as $event) {
                $duration = $event->end->timestamp() - $event->start->timestamp();

                // Make sure that we're using the current date for
                // recurring events.
                if (!$event->hasRecurType(KRONOLITH_RECUR_NONE)) {
                    $startThisDay = mktime($event->start->hour,
                                           $event->start->min,
                                           $event->start->sec,
                                           date('n', $day),
                                           date('j', $day),
                                           date('Y', $day));
                } else {
                    $startThisDay = $event->start->timestamp();
                }
                $vFb->addBusyPeriod('BUSY', $startThisDay, null, $duration);
            }
        }

        // Remove the overlaps.
        $vFb->simplify();
        $vCal->addComponent($vFb);

        // Return the vFreebusy object if requested.
        if ($returnObj) {
            return $vFb;
        }

        // Generate the vCal file.
        return $vCal->exportvCalendar();
    }

    /**
     * Retrieves the free/busy information for a given email address,
     * if any information is available.
     *
     * @params String   $email  The email address to look for.
     *
     * @return resource   Horde_iCalendar_vfreebusy on success
     *                    PEAR_Error on failure
     */
    function getFreeBusy($email)
    {
        global $prefs;

        require_once 'Horde/iCalendar.php';
        require_once 'Mail/RFC822.php';
        require_once 'Horde/MIME.php';

        // Properly handle RFC822-compliant email addresses.
        static $rfc822;
        if (is_null($rfc822)) {
            $rfc822 = &new Mail_RFC822();
        }

        $res = $rfc822->parseAddressList($email);
        if (is_a('PEAR_Error', $res)) {
            return $res;
        }
        if (!count($res)) {
            return PEAR::raiseError(_("No valid email address found"));
        }

        $email = MIME::rfc822WriteAddress($res[0]->mailbox, $res[0]->host);

        // Check if we can retrieve a VFB from the Free/Busy URL, if
        // one is set.
        $url = Kronolith::getFreeBusyUrl($email);
        if (is_a($url, 'PEAR_Error')) {
            return $url;
        }
        if (!empty($url)) {
            $data = @file_get_contents($url);
            if ($data) {
                $vCal = &new Horde_iCalendar();
                $vCal->parsevCalendar($data);

                $vFb = &$vCal->findComponent('VFREEBUSY');
                if ($vFb !== false) {
                    return $vFb;
                }
            }
        }

        // Check storage driver.
        global $conf;
        require_once KRONOLITH_BASE . '/lib/Storage.php';
        $storage = &Kronolith_Storage::singleton();

        $res = $storage->search($email);
        if (!is_a($res, 'PEAR_Error') || $res->getCode() == KRONOLITH_ERROR_FB_NOT_FOUND) {
            return $res;
        }

        // Or else return an empty VFB object
        $vCal = &new Horde_iCalendar();
        $vFb = &Horde_iCalendar::newComponent('vfreebusy', $vCal);
        $vFb->setAttribute('ORGANIZER', $email);

        return $vFb;
    }

    /**
     * Search address books for the freebusy URL for a given email
     * address.
     *
     * @params String   $email  The email address to look for.
     *
     * @return Mixed    (string) The url on success
     *                  (boolean) False on failure
     */
    function getFreeBusyUrl($email)
    {
        global $registry, $prefs;

        $result = $registry->call('contacts/getField', array($email, 'freebusyUrl', unserialize($prefs->getValue('search_abook'))));

        return $result;
    }

    /**
     * Sends out iTip event notifications to all attendees of a specific
     * event. Can be used to send event invitations, event updates as well
     * as event cancellations.
     *
     * @params object   $event         The event in question.
     * @params object   $notification  A notification object used to show
     *                                 result status.
     * @params integer  $action        The type of notification to send.
     *                                 One of the KRONOLITH_ITIP_XXX values.
     */
    function sendITipNotifications(&$event, &$notification, $action)
    {
        $attendees = $event->getAttendees();
        /* Exit early. */
        if (!count($attendees)) {
            return;
        }

        require_once 'Horde/Identity.php';
        $ident = &Identity::singleton();

        $myemail = $ident->getValue('from_addr');
        if (empty($myemail)) {
            $notification->push(sprintf(_("You do not have an email address configured in your Personal Information Options. You must set one %shere%s before event notifications can be sent."), Horde::link(Util::addParameter(Horde::url($GLOBALS['registry']->get('webroot', 'horde') . '/services/prefs.php'), array('app' => 'horde', 'group' => 'identities'))), '</a>'), 'horde.error', array('content.raw'));
            return;
        }

        require_once 'Horde/MIME.php';
        require_once 'Horde/MIME/Headers.php';
        require_once 'Horde/MIME/Message.php';

        $myemail = explode('@', $myemail);
        $from = MIME::rfc822WriteAddress($myemail[0], isset($myemail[1]) ? $myemail[1] : '', $ident->getValue('fullname'));

        foreach ($attendees as $email => $status) {
            // Don't bother sending an invitation/update if the recipient
            // does not need to participate, or has declined participating
            if ($status['attendance'] == KRONOLITH_PART_NONE ||
                $status['response'] == KRONOLITH_RESPONSE_DECLINED) continue;

            // Determine all notification-specific strings.
            switch ($action) {
            case KRONOLITH_ITIP_CANCEL:
                // Cancellation
                $method = 'CANCEL';
                $filename = 'event-cancellation.ics';
                $subject = sprintf(_("Cancelled: %s"), $event->getTitle());
                break;

            case KRONOLITH_ITIP_REQUEST:
            default:
                $method = 'REQUEST';
                if ($status['response'] == KRONOLITH_RESPONSE_NONE) {
                    // Invitation.
                    $filename = 'event-invitation.ics';
                    $subject = $event->getTitle();
                } else {
                    // Update.
                    $filename = 'event-update.ics';
                    $subject = sprintf(_("Updated: %s."), $event->getTitle());
                }
                break;
            }

            $message = $subject . "\n\n";

            if ($event->getDescription() != '') {
                $message .= _("The following is a more detailed description of the event:") . "\n\n" . $event->getDescription() . "\n\n";
            }
            $message .= _("Attached is an iCalendar file with more information about the event. If your mail client supports iTip requests you can use this file to easily update your local copy of the event.");

            $mime = &new MIME_Message();
            $body = &new MIME_Part('text/plain', String::wrap($message, 80, "\n"));
            $body->setCharset(NLS::getCharset());

            require_once 'Horde/Data.php';
            require_once 'Horde/iCalendar.php';

            $iCal = &new Horde_iCalendar();
            $iCal->setAttribute('METHOD', $method);
            $iCal->addComponent($event->toiCalendar($iCal, $ident));
            $ics = &new MIME_Part(
                'text/calendar',
                $iCal->exportvCalendar()
            );
            $ics->setName($filename);
            $ics->setContentTypeParameter('METHOD', $method);
            $ics->setCharset(NLS::getCharset());

            $mime->addPart($body);
            $mime->addPart($ics);

            // Build the notification headers.
            $msg_headers = &new MIME_Headers();
            $msg_headers->addReceivedHeader();
            $msg_headers->addMessageIdHeader();
            $msg_headers->addHeader('Date', date('r'));
            $msg_headers->addHeader('From', $from);
            $msg_headers->addHeader('To', $email);
            $msg_headers->addHeader('Subject', $subject);
            $msg_headers->addHeader('User-Agent', 'Kronolith Calendaring System');
            $msg_headers->addMIMEHeaders($mime);

            $status = $mime->send($email, $msg_headers);
            if (!is_a($status, 'PEAR_Error')) {
                $notification->push(
                    sprintf(_("The event notification to %s was successfully sent."), $email),
                    'horde.success'
                );
            } else {
                $notification->push(
                    sprintf(_("There was an error sending an event notification to %s: %s"), $email, $status->getMessage()),
                    'horde.error'
                );
            }
        }
    }

    function currentTimestamp()
    {
        $timestamp = (int)Util::getFormData('timestamp');
        if (!$timestamp) {
            $year = (int)Util::getFormData('year', date('Y'));
            $month = (int)Util::getFormData('month', date('n'));
            $day = (int)Util::getFormData('mday', date('d'));
            if ($week = (int)Util::getFormData('week')) {
                $month = 1;
                $day = Horde_Date::firstDayOfWeek($week, $year);
                if ($GLOBALS['prefs']->getValue('week_start_monday')) {
                    $day++;
                }
            }
            $timestamp = mktime(0, 0, 0, $month, $day, $year);
        }

        return $timestamp;
    }

    function tabs()
    {
        require_once 'Horde/UI/Tabs.php';
        require_once 'Horde/Variables.php';
        $tabs = &new Horde_UI_Tabs('view', Variables::getDefaultVariables());
        $tabs->preserve('timestamp', Kronolith::currentTimestamp());

        $tabs->addTab(_("Day"), Horde::applicationUrl('day.php'), 'day');
        $tabs->addTab(_("Work Week"), Horde::applicationUrl('workweek.php'), 'workweek');
        $tabs->addTab(_("Week"), Horde::applicationUrl('week.php'), 'week');
        $tabs->addTab(_("Month"), Horde::applicationUrl('month.php'), 'month');

        echo $tabs->render(basename($_SERVER['PHP_SELF']) == 'index.php' ? $GLOBALS['prefs']->getValue('defaultview') : str_replace('.php', '', basename($_SERVER['PHP_SELF'])));
    }

    /**
     * Build Kronolith's list of menu items.
     *
     * @access public
     */
    function getMenu($returnType = 'object')
    {
        global $conf, $registry, $browser, $prefs, $print_link;

        if ($browser->hasFeature('dom')) {
            Horde::addScriptFile('goto.inc', 'kronolith');
        }

        // Check here for guest calendars so that we don't get
        // multiple messages after redirects, etc.
        if (!Auth::getAuth() && !count($GLOBALS['all_calendars'])) {
            $notification->push(_("No calendars are available to guests."));
        }

        require_once 'Horde/Menu.php';
        $menu = &new Menu();

        $menu->add(Horde::applicationUrl($prefs->getValue('defaultview') . '.php'), _("_Today"), 'today.png', null, null, null, '__noselection');

        if (Kronolith::getDefaultCalendar(PERMS_EDIT)) {
            $menu->add(Horde::applicationUrl('addevent.php'), _("_New Event"), 'new.png');
        }

        if ($browser->hasFeature('dom')) {
            $menu->add('#', _("_Goto"), 'goto.png', null, '', 'openKGoto(\'' . Kronolith::currentTimestamp() . '\'); return false;');
        }
        $menu->add(Horde::applicationUrl('search.php'), _("_Search"), 'search.png', $registry->getImageDir('horde'));

        if (Auth::getAuth()) {
            $menu->add(Horde::applicationUrl('calendars.php'), _("_My Calendars"), 'calendars.png');
        }

        /* Import/Export. */
        if ($conf['menu']['import_export']) {
            $menu->add(Horde::applicationUrl('data.php'), _("_Import/Export"), 'data.png', $registry->getImageDir('horde'));
        }

        /* Print. */
        if ($conf['menu']['print'] && isset($print_link)) {
            $menu->add('#', _("_Print"), 'print.png', $registry->getImageDir('horde'), '', "popup('$print_link'); return false;");
        }

        if ($returnType == 'object') {
            return $menu;
        } else {
            return $menu->render();
        }
    }

    /**
     * Used with usort() to sort events based on their start times.
     * This function ignores the date component so recuring events can
     * be sorted correctly on a per day basis.
     */
    function _sortEventStartTime($a, $b)
    {
        return (int)date('Gis', $a->start->timestamp()) - (int)date('Gis', $b->start->timestamp());
    }

}
