<?php
/**
 * $Horde: kronolith/data.php,v 1.49 2003/06/17 23:27:39 slusarz Exp $
 *
 * Copyright 2001-2003 Jan Schneider <jan@horde.org>
 *
 * See the enclosed file COPYING for license information (GPL).  If you
 * did not receive this file, see http://www.fsf.org/copyleft/gpl.html.
 */

function _cleanup()
{
    global $import_step;
    $import_step = 1;
    return IMPORT_FILE;
}

define('KRONOLITH_BASE', dirname(__FILE__));
require_once KRONOLITH_BASE . '/lib/base.php';
require_once HORDE_BASE . '/lib/Data.php';

if (!$conf['menu']['import_export']) {
    header('Location: ' . Horde::applicationUrl('index.php', true));
    exit;
}

/* Allow preferred theme to override settings. */
Horde::getThemeConfig(KRONOLITH_BASE);

/* Importable file types. */
$file_types = array('csv'       => _("Comma separated values"),
                    'pdb'       => _("Palm DateBook"),
                    'icalendar' => _("vCalendar/iCalendar"));

/* Templates for the different import steps. */
$templates = array(
    IMPORT_FILE      => array(KRONOLITH_TEMPLATES . '/data/import.inc', KRONOLITH_TEMPLATES . '/data/export.inc'),
    IMPORT_CSV   => array($registry->getParam('templates', 'horde') . '/data/csvinfo.inc'),
    IMPORT_MAPPED => array($registry->getParam('templates', 'horde') . '/data/csvmap.inc'),
    IMPORT_DATETIME  => array($registry->getParam('templates', 'horde') . '/data/datemap.inc')
);

/* Initial values. */
$import_step   = Horde::getFormData('import_step', 0) + 1;
$actionID      = Horde::getFormData('actionID');
$next_step     = IMPORT_FILE;
$app_fields    = array('title' => _("Title"),
                       'start_date' => _("Start Date"),
                       'start_time' => _("Start Time"),
                       'end_date' => _("End Date"),
                       'end_time' => _("End Time"),
                       'alarm' => _("Alarm Span (minutes)"),
                       'alarm_date' => _("Alarm Date"),
                       'alarm_time' => _("Alarm Time"),
                       'description' => _("Description"),
                       'category' => _("Category"),
                       'location' => _("Location"),
                       'keywords' => _("Keywords"),
                       'recur_type' => _("Recurrence Type"),
                       'recur_end_date' => _("Recurrence End Date"),
                       'recur_interval' => _("Recurrence Interval"),
                       'recur_data' => _("Recurrence Data"));
$time_fields   = array('start_date'     => 'date',
                       'start_time'     => 'time',
                       'end_date'       => 'date',
                       'end_time'       => 'time',
                       'recur_end_date' => 'date');
$param         = array('time_fields' => $time_fields,
                       'file_types'  => $file_types);
$import_format = Horde::getFormData('import_format', '');
$error         = false;

/* Loop through the action handlers. */
switch ($actionID) {
case 'export':
    if (Horde::getFormData('all_events')) {
        $start = null;
        $end = null;
    } else {
        $start->mday = Horde::getFormData('start_day');
        $start->month = Horde::getFormData('start_month');
        $start->year = Horde::getFormData('start_year');
        $end->mday = Horde::getFormData('end_day');
        $end->month = Horde::getFormData('end_month');
        $end->year = Horde::getFormData('end_year');
    }

    $events = array();
    foreach ($display_calendars as $cal) {
        if ($calendar->getCalendar() != $cal) {
            $calendar->close();
            $calendar->open($cal);
        }
        $events[$cal] = $calendar->listEvents($start, $end);
    }

    if (!count($events)) {
        $notification->push(_("There were no events to export."), 'horde.message');
        $error = true;
        break;
    } else {
        $exportID = Horde::getFormData('exportID');
        switch ($exportID) {
        case EXPORT_CSV:
            $data = array();
            foreach ($events as $cal => $calevents) {
                if ($calendar->getCalendar() != $cal) {
                    $calendar->close();
                    $calendar->open($cal);
                }
                foreach ($calevents as $eventId) {
                    $event = &$calendar->getEventObject($eventId);

                    $row = array();
                    $row['title'] = $event->getTitle();
                    $row['category'] = $event->category;
                    $row['location'] = $event->location;
                    $row['description'] = $event->description;
                    $row['keywords'] = implode(',', $event->keywords);
                    $row['start_date'] = sprintf('%d-%02d-%02d', $event->start->year, $event->start->month, $event->start->mday);
                    $row['start_time'] = sprintf('%02d:%02d:%02d', $event->start->hour, $event->start->min, $event->start->sec);
                    $row['end_date'] = sprintf('%d-%02d-%02d', $event->end->year, $event->end->month, $event->end->mday);
                    $row['end_time'] = sprintf('%02d:%02d:%02d', $event->end->hour, $event->end->min, $event->end->sec);
                    $row['alarm'] = $event->alarm;
                    $row['recur_type'] = $event->recurType;
                    if ($event->recurType != KRONOLITH_RECUR_NONE) {
                        $row['recur_end_date'] = sprintf('%d-%02d-%02d', $event->recurEnd->year, $event->recurEnd->month, $event->recurEnd->mday);
                        $row['recur_interval'] = $event->recurInterval;
                        $row['recur_data'] = $event->recurData;
                    } else {
                        $row['recur_end_date'] = null;
                        $row['recur_interval'] = null;
                        $row['recur_data'] = null;
                    }
                    $data[] = $row;
                }
            }

            $csv = &Horde_Data::singleton('csv');
            $csv->exportFile(_("events.csv"), $data, true);
            exit;

        case EXPORT_ICALENDAR:
            $vcs = &Horde_Data::singleton('icalendar');
            require_once HORDE_BASE . '/lib/Identity.php';
            $identity = &new Identity();
            $data = array();
            foreach ($events as $cal => $calevents) {
                if ($calendar->getCalendar() != $cal) {
                    $calendar->close();
                    $calendar->open($cal);
                }
                foreach ($calevents as $id) {
                    $event = &$calendar->getEventObject($id);
                    $data[] = $event->toiCalendar($identity, $vcs);
                }
            }

            $data = $vcs->exportData($data);
            $browser->downloadHeaders('events.ics', 'text/calendar', false, strlen($data));
            echo $data;
            exit;
        }
    }
    break;

case IMPORT_FILE:
    $_SESSION['import_data']['import_cal'] = Horde::getFormData('importCal');
    break;

}

if (!$error) {
    $data = &Horde_Data::singleton($import_format);
    if (is_a($data, 'PEAR_Error')) {
        $notification->push(_("This file format is not supported."), 'horde.error');
        $next_step = IMPORT_FILE;
    } else {
         if ($actionID == IMPORT_FILE) {
            if (!array_key_exists($_SESSION['import_data']['import_cal'], Kronolith::listCalendars())) {
                $notification->push(_("You have specified an invalid calendar."), 'horde.error');
                $next_step = $data->cleanup();
            } else {
                $share = &$shares->getShare($_SESSION['import_data']['import_cal']);
                if (!$share->hasPermission(Auth::getAuth(), _PERMS_EDIT)) {
                    $notification->push(_("You do not have permission to add events to the selected calendar."), 'horde.error');
                    $next_step = $data->cleanup();
                } else {
                    $next_step = $data->nextStep($actionID, $param);
                    if (is_a($next_step, 'PEAR_Error')) {
                        $notification->push($next_step->getMessage(), 'horde.error');
                        $next_step = $data->cleanup();
                    }
                }
            }
        } else {
            $next_step = $data->nextStep($actionID, $param);
            if (is_a($next_step, 'PEAR_Error')) {
                $notification->push($next_step->getMessage(), 'horde.error');
                $next_step = $data->cleanup();
            }
        }
    }
}

/* We have a final result set. */
if (is_array($next_step)) {
    $events = array();
    $calendar->open($_SESSION['import_data']['import_cal']);
    $error = false;
    foreach ($next_step as $row) {
        $event = &$calendar->getEventObject();
        if (!$event || is_a($event, 'PEAR_Error')) {
            $msg = _("Can't create a new event.");
            if (is_a($event, 'PEAR_Error')) {
                $msg .= ' ' . sprintf(_("This is what the server said: %s"), $event->getMessage());
            }
            $notification->push($msg, 'horde.error');
            $error = true;
            break;
        }
        $event->fromHash($row);

        $event->createEvent();
        $success = $event->save();
        if (!$success || is_a($success, 'PEAR_Error')) {
            $msg = _("There was an error importing the data.");
            if (is_a($success, 'PEAR_Error')) {
                $msg .= ' ' . sprintf(_("This is what the server said: %s"), $success->getMessage());
            }
            $notification->push($msg, 'horde.error');
            $error = true;
            break;
        }
    }
    if (!$error) {
        $notification->push(sprintf(_("%s file successfully imported"),
                                    $file_types[$_SESSION['import_data']['format']]), 'horde.success');
    }
    $next_step = $data->cleanup();
}



// FIXME: Port PDB import code to new framework.
/*
    } elseif ($importID == IMPORT_PDB) {
        $pdb = &Horde_Data::singleton('pdb');
        $importData = $pdb->importFile($_FILES['import_file']['tmp_name']);

        if (!isset($importData) || !is_array($importData)) {
            $notification->push(_("There was an error importing the uploaded file"), 'horde.error');
            $error = true;
        } else {
            $format = array('start_date' => 'year/month/mday',
                            'end_date'   => 'year/month/mday',
                            'start_time' => '24hr',
                            'end_time'   => '24hr');
            $delimiter = array('start_date' => '-',
                               'end_date'   => '-',
                               'start_time' => ':',
                               'end_time'   => ':');

            $map = array('title'          => 'title',
                         'start_date'     => 'start_date',
                         'start_time'     => 'start_time',
                         'end_date'       => 'end_date',
                         'end_time'       => 'end_time',
                         'alarm'          => 'alarm',
                         'alarm_date'     => 'alarm_date',
                         'alarm_time'     => 'alarm_time',
                         'description'    => 'description',
                         'category'       => 'category',
                         'location'       => 'location',
                         'keywords'       => 'keywords',
                         'recur_type'     => 'recur_type',
                         'recur_end_date' => 'recur_end_date',
                         'recur_interval' => 'recur_interval',
                         'recur_data'     => 'recur_data');
        }
    }
*/

$title = _("Import/Export Calendar");
$js_onLoad = null;
require KRONOLITH_TEMPLATES . '/common-header.inc';
Kronolith::menu();

foreach ($templates[$next_step] as $template) {
    require $template;
}

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