#!/usr/local/bin/php
<?php
/**
 * $Horde: turba/scripts/upgrades/2004-10-26_create_default_histories.php,v 1.5.4.3 2005/06/27 10:04:46 jan Exp $
 *
 * Copyright 1999-2005 Charles J. Hagenbuch <chuck@horde.org>
 *
 * See the enclosed file LICENSE for license information (ASL).  If you
 * did not receive this file, see http://www.horde.org/licenses/asl.php.
 */

@define('AUTH_HANDLER', true);
@define('HORDE_BASE', dirname(__FILE__) . '/../../..');

// Do CLI checks and environment setup first.
require_once HORDE_BASE . '/lib/core.php';
require_once 'Horde/CLI.php';

// Make sure no one runs this from the web.
if (!Horde_CLI::runningFromCLI()) {
    exit("Must be run from the command line\n");
}

// Load the CLI environment - make sure there's no time limit, init
// some variables, etc.
Horde_CLI::init();

@define('TURBA_BASE', dirname(__FILE__) . '/../..');
require_once TURBA_BASE . '/lib/base.php';
require_once 'Horde/History.php';

$history = &Horde_History::singleton();

// Run through every contact source.
foreach ($cfgSources as $key => $curSource) {
    if (empty($curSource['export']) || !empty($curSource['readonly'])) {
        continue;
    }

    $driver = &Turba_Driver::singleton($key, $curSource);
    if (is_a($driver, 'PEAR_Error')) {
        var_dump($driver);
        exit;
    }

    echo "Creating default histories for $key ...\n";

    // List all contacts.
    $results = $driver->search(array(), 'name', 'AND', 0);
    while ($object = $results->next()) {
        /* Get the contact's history. */
        $log = $history->getHistory('turba:' . $object->getValue('__uid'));
        $created = false;
        foreach ($log->getData() as $entry) {
            if ($entry['action'] == 'add') {
                $created = true;
                break;
            }
        }

        // If there isn't an add entry, add one at the current time.
        if (!$created) {
            $result = $history->log('turba:' . $object->getValue('__uid'), array('action' => 'add'), true);
            if (is_a($result, 'PEAR_Error')) {
                var_dump($result);
                exit;
            }
        }
    }
}

echo "\n** Default histories successfully created ***\n";
