<?php
/**
 * $Horde: turba/data.php,v 1.47 2003/06/17 23:28:07 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('TURBA_BASE', dirname(__FILE__));
require_once TURBA_BASE . '/lib/base.php';
require_once TURBA_BASE . '/lib/Source.php';
require_once HORDE_BASE . '/lib/Data.php';
require TURBA_BASE . '/config/attributes.php';

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

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

/* Importable file types. */
$file_types = array('csv'      => _("CSV"),
                    'tsv'      => _("TSV"),
                    'vcard'    => _("vCard"),
                    'mulberry' => _("Mulberry Address Book"),
                    'pine'     => _("Pine Address Book"));

/* Templates for the different import steps. */
$templates = array(
    IMPORT_FILE => array(TURBA_TEMPLATES . '/data/import.inc', TURBA_TEMPLATES . '/data/export.inc'),
    IMPORT_CSV => array($registry->getParam('templates', 'horde') . '/data/csvinfo.inc'),
    IMPORT_TSV => array($registry->getParam('templates', 'horde') . '/data/tsvinfo.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();
$time_fields   = array();
$error         = false;
$param = array('time_fields' => $time_fields,
               'file_types'  => $file_types);
$import_format = Horde::getFormData('import_format', '');
$driver = $import_format;
if ($driver == 'mulberry' || $driver == 'pine') {
    $driver = 'tsv';
}

/* Loop through the action handlers. */
switch ($actionID) {
case 'export':
    $source = Horde::getFormData('source');
    if (!isset($source) && isset($cfgSources) && is_array($cfgSources) && count($cfgSources) > 0) {
        reset($cfgSources);
        $source = key($cfgSources);
    }

    /* Create a Turba storage instance. */
    $storage = &Turba_Source::singleton($source, $cfgSources[$source]);
    if (is_a($storage, 'PEAR_Error')) {
        $notification->push(_("Failed to connect to the specified directory."), 'horde.error');
        $error = true;
    } elseif (get_class($addresses = $storage->search(array())) != 'turba_list') {
        $notification->push(sprintf(_("Failed to search the directory: %s"), $storage->error()), 'horde.error');
        $error = true;
    } else {
        /* Get the full, sorted address list. */
        $params = $storage->driver->getParams();
        $data = array();
        while ($ob = $addresses->next()) {
            $tmp = $ob->getAttributes();
            $row = array();
            foreach ($tmp as $key => $attribute) {
                if (substr($key, 0, 2) != '__' &&
                    array_key_exists($key, $attributes)) {
                    if (isset($params['charset'])) {
                        $attribute = String::convertCharset($attribute, NLS::getCharset(), $params['charset']);
                    }
                    if ($attributes[$key]['type'] == 'date') {
                        $row[$key] = strftime('%Y-%m-%d', $attribute);
                    } elseif ($attributes[$key]['type'] == 'time') {
                        $row[$key] = strftime('%R', $attribute);
                    } elseif ($attributes[$key]['type'] == 'datetime') {
                        $row[$key] = strftime('%Y-%m-%d %R', $attribute);
                    } else {
                        $row[$key] = $attribute;
                    }
                }
            }
            $data[] = $row;
        }
        if (count($data) == 0) {
            $notification->push(_("There were no addresses to export."), 'horde.message');
            $error = true;
        } else {
            $exportID = Horde::getFormData('exportID');
            switch ($exportID) {
            case EXPORT_CSV:
                $csv = &Horde_Data::singleton('csv');
                $csv->exportFile(_("contacts.csv"), $data, true);
                exit;
            case EXPORT_TSV:
                $tsv = &Horde_Data::singleton('tsv');
                $tsv->exportFile(_("contacts.tsv"), $data, true);
                exit;
            }
        }
    }
    break;

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

case IMPORT_MAPPED:
    foreach ($cfgSources[$_SESSION['import_data']['target']]['map'] as $field => $null) {
        if (substr($field, 0, 2) != '__' &&
            ($attributes[$field]['type'] == 'date' ||
             $attributes[$field]['type'] == 'time' ||
             $attributes[$field]['type'] == 'datetime')) {
            $time_fields[$field] = $attributes[$field]['type'];
        }
    }
    $param['time_fields'] = $time_fields;
    break;
}

if (!$error && !empty($driver)) {
    $data = &Horde_Data::singleton($driver);
    if (is_a($data, 'PEAR_Error')) {
        $notification->push(_("This file format is not supported."), 'horde.error');
        $next_step = IMPORT_FILE;
    } 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)) {
    /* Create a Turba storage instance. */
    $dest = $_SESSION['import_data']['target'];
    $storage = &Turba_Source::singleton($dest, $cfgSources[$dest]);
    if (is_a($storage, 'PEAR_Error')) {
        $notification->push(_("Failed to connect to the specified directory."), 'horde.error');
    } else {
        $error = false;
        foreach ($next_step as $row) {
            reset($cfgSources[$dest]['map']);
            $row['__owner'] = Auth::getAuth();
            $success = $storage->addObject($row);
            if (is_a($success, 'PEAR_Error')) {
                $notification->push(sprintf(_("There was an error importing the data: %s"),
                                            $success->getMessage()), '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();
}

switch ($next_step) {

case IMPORT_MAPPED:
case IMPORT_DATETIME:
    foreach ($cfgSources[$_SESSION['import_data']['target']]['map'] as $field => $null) {
        if (substr($field, 0, 2) != '__') {
            $app_fields[$field] = $attributes[$field]['label'];
        }
    }
    break;

}

$title = _("Import/Export Address books");
$js_onLoad = null;
require TURBA_TEMPLATES . '/common-header.inc';
Turba::menu();

$default_source = $prefs->getValue('default_dir');
if ($next_step == IMPORT_FILE) {
    /* Build the directory sources select widget. */
    $source_options = '';
    foreach ($cfgSources as $key => $entry) {
        $selected = ($key == $default_source) ? ' selected="selected"' : '';
        if (!empty($entry['export'])) {
            $source_options .= "<option value=\"$key\"" . $selected . ">";
            $source_options .= $entry['title'] . "</option>\n";
        }
    }

    /* Build the directory destination select widget. */
    $dest_options = '';
    $hasWriteable = false;
    foreach ($cfgSources as $key => $entry) {
        $selected = ($key == $default_source) ? ' selected="selected"' : '';
        if (empty($entry['readonly']) || (isset($entry['admin']) && in_array(Auth::getAuth(), $entry['admin']))) {
            $dest_options .= "<option value=\"$key\" " . $selected . ">";
            $dest_options .= $entry['title'] . "</option>\n";
            $hasWriteable = true;
        }
    }

    if (!$hasWriteable) {
        array_shift($templates[$next_step]);
    }
}

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

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