#!/usr/bin/env php
<?php
/**
 * This script imports SquirrelMail database addressbooks into Turba.
 *
 * The first argument must be a DSN to the database containing the "address"
 * table, e.g.: "mysql://root:password@localhost/squirrelmail".
 *
 * Copyright 2008-2016 Horde LLC (http://www.horde.org/)
 *
 * See the enclosed file LICENSE for license information (ASL).  If you
 * did not receive this file, see http://www.horde.org/licenses/apache.
 *
 * @author Ben Chavet <ben@horde.org>
 * @author Jan Schneider <jan@horde.org>
 */

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

// Read command line parameters.
if ($argc != 2) {
    $cli->message('Too many or too few parameters.', 'cli.error');
    $cli->writeln('Usage: turba-import-squirrelmail-sql-abook DSN');
    $cli->writeln($cli->indent('DSN are json-encoded connection parameters to the database containing the "userprefs" table. Example:'));
    $cli->writeln($cli->indent('{"adapter":"mysql","user":"root","password":"password","host":"localhost","database":"squirrelmail"}'));
    exit;
}

$db = $injector->getInstance('Horde_Db')->createDb(json_decode($argv[1]));
include TURBA_BASE . '/config/backends.php';

// Loop through SquirrelMail address books.
$handle = $db->select('SELECT owner, nickname, firstname, lastname, email, label FROM address ORDER BY owner');
$turba_shares = $GLOBALS['injector']->getInstance('Turba_Shares');
$user = null;
$count = 0;
foreach ($handle as $row) {
    // Set current user
    if ($row['owner'] != $user) {
        if (!is_null($user)) {
            $cli->message('  Added ' . $count . ' contacts', 'cli.success');
            $count = 0;
        }
        $user = $row['owner'];
        $registry->setAuth($user, array());
        $cli->message('Importing ' . $user . '\'s address book');

        // Reset user prefs
        $prefs = $injector->getInstance('Horde_Core_Factory_Prefs')->create('turba', array(
            'cache' => false,
            'user' => $user
        ));

        // Reset $cfgSources for current user.
        unset($cfgSources);
        $hasShares = false;
        foreach ($cfgSources as $key => $cfg) {
            if (!empty($cfg['use_shares'])) {
                $has_share = true;
                break;
            }
        }
        if ($has_share) {
            $cfgSources = Turba::getConfigFromShares($cfgSources);
        }
        $cfgSources = Turba::permissionsFilter($cfgSources);
        if (!count($cfgSources)) {
            $cli->message('No address book available for ' . $user, 'cli.error');
            continue;
        }

        // Get user's default addressbook
        $import_source = $prefs->getValue('default_dir');
        if (empty($import_source)) {
            $import_source = array_keys($cfgSources);
            $import_source = $import_source[0];
        }

        // Check existance of the specified source.
        if (!isset($cfgSources[$import_source])) {
            $cli->message('  ' . sprintf(_("Invalid address book: %s"), $import_source), 'cli.error');
            continue;
        }

        // Initiate driver
        try {
            $driver = $injector->getInstance('Turba_Factory_Driver')->create($import_source);
        } catch (Turba_Exception $e) {
            $cli->message('  ' . sprintf(_("Connection failed: %s"), $e->getMessage()), 'cli.error');
            continue;
        }
    }

    if (!count($cfgSources)) {
        continue;
    }

    $rfc822 = new Horde_Mail_Rfc822();
    $members = $rfc822->parseAddressList($row['email']);
    if (count($members) > 1) {
        // Entry is a list of contacts, import each individually and create a
        // group that contains them.
        $attributes = array('alias' => $row['nickname'],
                            'firstname' => $row['firstname'],
                            'lastname' => $row['lastname'],
                            'notes' => $row['label']);
        $gid = $driver->add($attributes);
        $group = new Turba_Object_Group($driver, array_merge($attributes, array('__key' => $gid)));
        ++$count;
        foreach (array_map('strval', $members) as $member) {
            try {
                $result = $driver->add(array(
                    'firstname' => $member,
                    'email' => $member
                ));
                $group->addMember($result, $import_source);
                ++$count;
            } catch (Turba_Exception $e) {
                $cli->message('  ' . $e->getMessage(), 'cli.error');
            }
        }
        $group->store();
    } else {
        // Entry only contains one contact, import it.
        $contact = array(
            'alias' => $row['nickname'],
            'firstname' => $row['firstname'],
            'lastname' => $row['lastname'],
            'email' => $row['email'],
            'notes' => $row['label']
        );

        try {
            $driver->add($contact);
            ++$count;
        } catch (Turba_Exception $e) {
            $cli->message('  ' . $e->getMessage(), 'cli.error');
        }
    }
}
$cli->message('  Added ' . $count . ' contacts', 'cli.success');
