<?php
/**
 * $Horde: kronolith/data.php,v 1.72.2.1 2005/01/03 12:25:39 jan Exp $
 *
 * Copyright 2001-2005 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/Data.php';

if (!$conf['menu']['import_export']) {
    require KRONOLITH_BASE . '/index.php';
    exit;
}

/* 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->get('templates', 'horde') . '/data/csvinfo.inc'),
    IMPORT_MAPPED => array($registry->get('templates', 'horde') . '/data/csvmap.inc'),
    IMPORT_DATETIME => array($registry->get('templates', 'horde') . '/data/datemap.inc')
);

/* Initial values. */
$import_step   = Util::getFormData('import_step', 0) + 1;
$actionID      = Util::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 = Util::getFormData('import_format', '');
$error         = false;

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

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

    if (!count($events)) {
        $notification->push(_("There were no events to export."), 'horde.message');
        $error = true;
        break;
    } else {
        $exportID = Util::getFormData('exportID');
        switch ($exportID) {
        case EXPORT_CSV:
            $data = array();
            foreach ($events as $cal => $calevents) {
                if ($kronolith->getCalendar() != $cal) {
                    $kronolith->close();
                    $kronolith->open($cal);
                }
                foreach ($calevents as $eventId) {
                    $event = &$kronolith->getEvent($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:
            require_once 'Horde/Identity.php';
            require_once 'Horde/iCalendar.php';
            $iCal = &new Horde_iCalendar();

            foreach ($events as $cal => $calevents) {
                if ($kronolith->getCalendar() != $cal) {
                    $kronolith->close();
                    $kronolith->open($cal);
                }

                $identity = &$kronolith_shares->getIdentityByShare($kronolith_shares->getShare($cal));
                foreach ($calevents as $id) {
                    $event = &$kronolith->getEvent($id);
                    $iCal->addComponent($event->toiCalendar($iCal, $identity));
                }
            }
            $data = $iCal->exportvCalendar();
            $browser->downloadHeaders(_("events.ics"), 'text/calendar', false, strlen($data));
            echo $data;
            exit;
        }
    }
    break;

case IMPORT_FILE:
    $_SESSION['import_data']['import_cal'] = Util::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 = &$kronolith_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();
    $kronolith->open($_SESSION['import_data']['import_cal']);
    $error = false;
    foreach ($next_step as $row) {
        $event = &$kronolith->getEvent();
        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;
        }
        if (is_a($row, 'Horde_iCalendar_vevent')) {
            $event->fromiCalendar($row);
        } elseif (is_a($row, 'Horde_iCalendar')) {
            // Skip other iCalendar components for now.
            continue;
        } else {
            $event->fromHash($row);
        }

        $success = $event->save();
        if (is_a($success, 'PEAR_Error')) {
            $notification->push($success, '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");
require KRONOLITH_TEMPLATES . '/common-header.inc';
require KRONOLITH_TEMPLATES . '/menu.inc';

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

require $registry->get('templates', 'horde') . '/common-footer.inc';
