#!C:\Program Files (x86)\Plesk\Additional\PleskPHP74\\php.exe
<?php
/**
 * This script imports Open-Xchange preferences into Horde.
 *
 * The first argument must be the API endpoint of an Open-Xchange servers,
 * usually something like http://servername/ajax.
 *
 * If called with three arguments, the further arguments must be the user name
 * (usually "Administrator") and password of an administrator user to import
 * public task lists.
 *
 * If called with two arguments, the second argument must be a file with user
 * names and cleartext passwords separated by spaces.
 *
 * Copyright 2014-2017 Horde LLC (http://www.horde.org/)
 *
 * See the enclosed file COPYING for license information (LGPL-2). If you
 * did not receive this file, see http://www.horde.org/licenses/lgpl.
 *
 * @author   Jan Schneider <jan@horde.org>
 * @category Horde
 * @license  http://www.horde.org/licenses/lgpl LGPL-2
 * @package  Horde
 */

$baseFile = __DIR__ . '/../lib/Application.php';
if (file_exists($baseFile)) {
    require_once $baseFile;
} else {
    require_once 'PEAR/Config.php';
    require_once PEAR_Config::singleton()
        ->get('horde_dir', null, 'pear.horde.org') . '/lib/Application.php';
}
Horde_Registry::appInit('horde', array('cli' => true));

// Read command line parameters.
if ($argc < 3 || $argc > 4) {
    $cli->message('Too many or too few parameters.', 'cli.error');
    $cli->writeln('Usage: horde-import-openxchange-prefs url [ file | user password ]');
    $cli->writeln($cli->indent('url is the URL of an Open-Xchange AJAX endpoint'));
    $cli->writeln($cli->indent('file is a file with space separated user names and passwords to import'));
    $cli->writeln($cli->indent('user preferences.'));
    exit;
}
$admin = $argc == 4;

// Basic objects and variables.
$endpoint = parse_url($argv[1]);
$cli->message('Opening endpoint ' . $argv[1]);
$ox = new Horde_OpenXchange_Tasks(array('endpoint' => $argv[1]));
$users = array();

// Prepare handle on user/password list.
if ($admin) {
    $fp = fopen('php://temp', 'r+');
    fwrite($fp, $argv[2] . ' ' . $argv[3]);
    rewind($fp);
} else {
    if (!is_readable($argv[2]) || !filesize($argv[2])) {
        $cli->message($argv[2] . ' is not readable or empty', 'cli.error');
        exit(1);
    }
    $fp = fopen($argv[2], 'r');
}
if (!$fp) {
    exit(1);
}

$prefsMap = array(
    'horde' => array(
        'language' => 'language',
        'timezone' => 'timezone',
        'modules/mail/addresses' => function($v) {
            global $ox;
            $default = $ox->getConfig('mail/defaultaddress');
            $gui = $ox->getConfig('gui');
            $identities = array();
            $id = 0;
            foreach ($v as $address) {
                if ($address == $default) {
                    $id = count($identities);
                }
                $identities[] = array(
                    'id' => $address,
                    'from_addr' => $address
                );
            }
            return array(
                'identities' => serialize($identities),
                'default_identity' => $id,
                'signature' => empty($gui['mail']['signatures'])
                ? ''
                : $gui['mail']['signatures'][0],
            );
        },
    ),
    'imp' => array(
        'modules/mail/allowhtmlimages' => function($v) {
            return array('image_replacement' => !$v);
        },
        'modules/mail/contactCollectEnabled' => 'save_recipients',
        'modules/mail/deletemail' => function($v) {
            return array('use_trash' => !$v);
        },
        'modules/mail/emoticons' => 'emoticons',
        'modules/mail/defaultFolder/drafts' => function($v) {
            return array('drafts_folder', str_replace('default0/', $v));
        },
        'modules/mail/defaultFolder/sent' => function($v) {
            return array('sent_mail_folder', str_replace('default0/', $v));
        },
        'modules/mail/defaultFolder/spam' => function($v) {
            return array('spam_folder', str_replace('default0/', $v));
        },
        'modules/mail/defaultFolder/trash' => function($v) {
            return array('trash_folder', str_replace('default0/', $v));
        },
        'modules/mail/forwardmessage' => function($v) {
            return array('forward_default' => $v == 'Inline' ? 'body' : 'attach');
        },
        'modules/mail/inlineattachments' => function($v) {
            return array('alternative_display' => $v ? 'html' : 'text');
        },
    ),
    'kronolith' => array(
        'modules/calendar/notifyNewModifiedDeleted' => function($v) {
            return array('event_notification' => $v ? 'show' : '');
        },
    ),
    'nag' => array(
        'modules/tasks/notifyNewModifiedDeleted' => function($v) {
            return array('task_notification' => $v ? 'show' : '');
        },
    ),
    'turba' => array(
        //'contact_id' => 'own_contact',
    ),
);

// Loop through all users.
while ($row = fgetcsv($fp, 0, ' ')) {
    $user = $row[0];
    if (is_null($user)) {
        continue;
    }
    $ox->logout();
    $ox->login($user, $row[1]);

    $registry->setAuth($user, array());
    $cli->message('Importing ' . $user . '\'s preferences');
    $count = 0;

    foreach ($prefsMap as $app => $prefsList) {
        $prefs = $injector->getInstance('Horde_Core_Factory_Prefs')
            ->create($app, array('cache' => false, 'user' => $user));
        foreach ($prefsList as $name => $target) {
            $value = $ox->getConfig($name);
            if (is_null($value)) {
                continue;
            }
            if (is_callable($target)) {
                foreach ($target($value) as $key => $value) {
                    if (is_bool($value)) {
                        $value = (int)$value;
                    }
                    $prefs->setValue($key, $value);
                    $count++;
                }
            } else {
                if (is_bool($value)) {
                    $value = (int)$value;
                }
                $prefs->setValue($target, $ox->getConfig($name));
                $count++;
            }
        }
    }

    $cli->message('  Added ' . $count . ' preferences', 'cli.success');
    $count = 0;
}
