<?php
/**
 * $Horde: moment/meeting.php,v 1.23 2003/09/01 22:56:38 jan Exp $
 *
 * Copyright 2003 Mike Cochrane <mike@graftonhall.co.nz>
 *
 * See the enclosed file LICENSE for license information.
 */

@define('MOMENT_BASE', dirname(__FILE__));
require_once MOMENT_BASE . '/lib/base.php';
require_once MOMENT_BASE . '/lib/View.php';

$view = Horde::getFormData('view', 'details');
$actionID = Horde::getFormData('actionID');
$meetingID = Horde::getFormData('meetingID');

// Setup session cache and new meetings.
if (!array_key_exists('moment', $_SESSION)) {
    $_SESSION['moment'] = array();
}

if (!array_key_exists('meeting', $_SESSION['moment'])) {
    // No existing meeting, create one.
    $_SESSION['moment']['meeting'] = array('title' => '',
                                           'description' => '',
                                           'location' => '',
                                           'start' => time(),
                                           'end' => time() + 3600,
                                           'attendees' => array(),
                                           'status' => '');
} elseif ($actionID == MOMENT_NEW &&
          (!empty($_SESSION['moment']['meeting']['title']) ||
           !empty($_SESSION['moment']['meeting']['description']) ||
           !empty($_SESSION['moment']['meeting']['location']))) {
    // Existing meeting resume?
    require MOMENT_TEMPLATES . '/common-header.inc';
    Moment::menu();
    require MOMENT_TEMPLATES . '/meeting/resume.inc';
    require MOMENT_TEMPLATES . '/common-footer.inc';
    exit;
}

// Merge submitted values.
$meeting = Horde::getFormData('meeting', array());
foreach ($meeting as $key => $value) {
    if (is_array($value)) {
        if (!array_key_exists($key, $_SESSION['moment']['meeting']) ||
            !is_array($_SESSION['moment']['meeting'][$key])) {
            $_SESSION['moment']['meeting'][$key] = array();
        }
        foreach ($value as $key2 => $value2) {
            $_SESSION['moment']['meeting'][$key][$key2] = $value2;
        }
    } else {
        $_SESSION['moment']['meeting'][$key] = $value;
    }
}
$meeting = &$_SESSION['moment']['meeting'];

// Retrieve a specific event.
if (!is_null($meetingID)) {
    /* Create a storage instance. */
    $storage = &Moment_Driver::singleton();
    $storage->retrieve();

    $meeting = $storage->getMeeting($meetingID);
    if (is_a($meeting, 'PEAR_Error')) {
        $notification->push(_("Invalid Meeting ID."), 'horde.error');
        header('Location: ' . Horde::applicationUrl('list.php'));
        exit;
    }
}

if (!array_key_exists('attendees', $meeting)) {
    $meeting['attendees'] = array();
}

if (is_array($meeting['start'])) {
    $meeting['start'] = mktime($meeting['start']['hour'],
                               $meeting['start']['min'], 0,
                               $meeting['start']['month'],
                               $meeting['start']['day'],
                               $meeting['start']['year']);
}

if (is_array($meeting['end'])) {
    $meeting['end'] = mktime($meeting['end']['hour'],
                             $meeting['end']['min'], 0,
                             $meeting['end']['month'],
                             $meeting['end']['day'],
                             $meeting['end']['year']);
}

if (array_key_exists('id', $meeting)) {
    $title = _("Edit Meeting");
} else {
    $title = _("New Meeting");
}

switch ($actionID) {
case MOMENT_RESET:
    unset($_SESSION['moment']['meeting']);
    header('Location: ' . Horde::applicationUrl('meeting.php'));
    break;

case MOMENT_CANCEL:
    unset($_SESSION['moment']['meeting']);
    header('Location: ' . Horde::applicationUrl('list.php'));
    break;

case MOMENT_DELETE_ATTENDEE:
    $email = Horde::getFormData('email');
    if (!empty($email)) {
        foreach ($meeting['attendees'] as $key => $attendee) {
            if ($attendee['email'] == $email) {
                unset($meeting['attendees'][$key]);
                // TODO: Prompt send cancel notice
            }
        }
    }
    break;

case MOMENT_ADD_ATTENDEE:
    $email = Horde::getFormData('email');
    $emails = explode(',', $email);
    if (!is_array($emails) || count($emails) < 1) {
        $emails = array($email);
    }
    $notfound = array();
    foreach ($emails as $email) {
        $email = trim($email);
        if (!empty($email)) {
            $meeting['attendees'][] = array('email' => $email,
                                            'attendance' => 'required',
                                            'responce' => 'none');

            if (!Moment::freebusyAvailable($email)) {
                $notification->push(sprintf(_("Free/busy information not available for %s"), $email), 'horde.warning');
                $notfound[] = $email;
            }
        }
    }

    if (count($notfound)) {
        require MOMENT_TEMPLATES . '/common-header.inc';
        Moment::menu();
        $templates = 2;
        require MOMENT_TEMPLATES . '/meeting/header_long.inc';
        require MOMENT_TEMPLATES . '/meeting/send_request.inc';
        require MOMENT_TEMPLATES . '/meeting/footer.inc';
        require MOMENT_TEMPLATES . '/common-footer.inc';
        exit;
    }
    break;

case MOMENT_SEND_REQUEST:
    $addresses = Horde::getFormData('request');

    if (count($addresses)) {
        require_once HORDE_BASE . '/lib/Identity.php';
        require_once HORDE_BASE . '/lib/MIME.php';
        require_once HORDE_BASE . '/lib/MIME/Message.php';
        $vCal = Moment::iCalFreeBusyRequest($meeting);

        // Get the Identity for the organizer.
        $identity = &new Identity(Auth::getAuth());
        $email = $identity->getValue('from_addr');
        $cn = $identity->getValue('fullname');
        if (empty($email)) {
            $notification->push(_("You don't have an email address configured in your preferences. You must set one before sending anything."), 'horde.error');
            break;
        }

        // Create the email
        list($mailbox, $host) = explode('@', $email);
        $from = MIME::rfc822WriteAddress($mailbox, $host, $cn);

        // Add a Received header for the hop from browser to server.
        $remote = (!empty($_SERVER['REMOTE_HOST'])) ? $_SERVER['REMOTE_HOST'] : $_SERVER['REMOTE_ADDR'];
        $headers['Received'] = 'from ' . $remote . ' (';
        if (!empty($_SERVER['REMOTE_IDENT'])) {
            $headers['Received'] .= $_SERVER['REMOTE_IDENT'] . '@' . $remote;
        }
        $headers['Received'] .= ' [' . $remote . '])';
        $headers['Received'] .= "\n\t by " . $conf['server']['name'] . ' with HTTP;';
        $headers['Received'] .= "\n\t" . date('r');

        $headers['Message-ID'] = MIME::generateMessageID();
        $headers['Date'] = date('r');
        $headers['To'] = implode(', ', array_keys($addresses));
        $headers['From'] = $from;
        $headers['Subject'] = sprintf(_("Request for your free/busy information"), $meeting['title']);
        $headers['User-Agent'] = 'Moment Meeting Planner';

        $message = _("This is a request for your free/busy information");
        $message .= "\n" . _("Attached is an iCalendar file containing the request.");

        $mime = &new MIME_Message();
        $body = &new MIME_Part('text/plain', Text::wrap($message, 80, "\n"));

        $ics = &new MIME_Part('text/calendar', $vCal->exportvCalendar());
        $ics->setName('icalendar.ics');
        $ics->setContentTypeParameter('METHOD', 'REQUEST');

        $mime->addPart($body);
        $mime->addPart($ics);
        $headers = $mime->header($headers);
        $status = $mime->send(implode(', ', array_keys($addresses)), $headers);
        if (!is_a($status, 'PEAR_Error')) {
            $notification->push(_("Your requests were successfully sent."), 'horde.success');
        } else {
            $notification->push(sprintf(_("There was an error sending your requests: %s"), $status->getMessage()), 'horde.error');
        }
    }
    break;

case MOMENT_SAVE_MEETING:
    $storage = &Moment_Driver::singleton();
    $storage->retrieve();

    $url = Horde::applicationUrl('sendUpdates.php');
    if (array_key_exists('id', $meeting)) {
        // Update existing event
        foreach ($meeting as $attr => $val) {
            $storage->modifyMeeting($meeting['id'], $attr, $val);
        }
        $storage->modifyMeeting($meeting['id'], 'sequence', ++$meeting['sequence']);
        $url = Horde::addParameter($url, 'meetingID', $meeting['id']);
        $url = Horde::addParameter($url, 'mode', 'update');
    } else {
        $meetingID = $storage->addMeeting($meeting);
        $url = Horde::addParameter($url, 'meetingID', $meetingID);
        $url = Horde::addParameter($url, 'mode', 'new');
    }

    // Write the changes.
    $storage->store();
    $notification->push(_("Meeting Saved"), 'horde.success');

    unset($_SESSION['moment']['meeting']);
    header('Location: ' . $url);
    exit;
    break;

case MOMENT_CANCEL_MEETING:
    $storage = &Moment_Driver::singleton();
    $storage->retrieve();
    $url = Horde::applicationUrl('sendUpdates.php');
    if (array_key_exists('id', $meeting)) {
        $storage->modifyMeeting($meeting['id'], 'status', 'cancelled');
        $storage->modifyMeeting($meeting['id'], 'sequence', ++$meeting['sequence']);
        $url = Horde::addParameter($url, 'meetingID', $meeting['id']);
        $url = Horde::addParameter($url, 'mode', 'cancel');
    }
    // Write the changes.
    $storage->store();

    $notification->push(_("Meeting Cancelled"), 'horde.success');
    header('Location: ' . $url);
    exit;
    break;

case MOMENT_DELETE_MEETING:
    $storage = &Moment_Driver::singleton();
    $storage->retrieve();
    if (array_key_exists('id', $meeting)) {
        $storage->deleteMeeting($meeting['id']);
    }
    // Write the changes.
    $storage->store();

    $notification->push(_("Meeting Deleted"), 'horde.success');
    header('Location: ' . Horde::applicationUrl('list.php'));
    exit;
    break;
}

Horde::addScriptFile('dateselect.js');
require MOMENT_TEMPLATES . '/common-header.inc';

switch ($view) {
case 'details':
    Moment::menu();
    $templates = 2;
    require MOMENT_TEMPLATES . '/meeting/header.inc';
    require MOMENT_TEMPLATES . '/meeting/details.inc';
    require MOMENT_TEMPLATES . '/meeting/time.inc';
    require MOMENT_TEMPLATES . '/meeting/footer.inc';
    break;

case 'attendees':
    Moment::menu();
    $templates = 3;
    require MOMENT_TEMPLATES . '/meeting/header_long.inc';
    require MOMENT_TEMPLATES . '/meeting/time.inc';
    require MOMENT_TEMPLATES . '/meeting/attendees.inc';
    require MOMENT_TEMPLATES . '/meeting/footer.inc';
    break;

default:
    $attendee_view = &Moment_View::singleton($view);
    foreach ($meeting['attendees'] as $attendee) {
        if ($attendee['attendance'] == 'required') {
            $vfb = Moment::getFreeBusy($attendee['email']);
            if (!is_a($vfb, 'PEAR_error')) {
                $attendee_view->addRequiredMember($vfb);
            } else {
                $notification->push(sprintf(_("Error retrieving free/busy information for %s: %s"), $attendee['email'], $vfb->getMessage()));
            }
        } else {
            $vfb = Moment::getFreeBusy($attendee['email']);
            if (!is_a($vfb, 'PEAR_error')) {
                $attendee_view->addOptionalMember($vfb);
            } else {
                $notification->push(sprintf(_("Error retrieving free/busy information for %s: %s"), $attendee['email'], $vfb->getMessage()));
            }
        }
    }

    Moment::menu();
    $templates = 2;
    require MOMENT_TEMPLATES . '/meeting/header_long.inc';
    require MOMENT_TEMPLATES . '/meeting/time.inc';
    $view_html = $attendee_view->render(Horde::getFormData('date', time()));
    require MOMENT_TEMPLATES . '/meeting/meeting.inc';
    require MOMENT_TEMPLATES . '/meeting/footer.inc';
}

require MOMENT_TEMPLATES . '/common-footer.inc';
