#!/usr/bin/php -q
<?php
/**
 * $Horde: horde/scripts/upgrades/move_history_out_of_datatree.php,v 1.3.2.1 2005/10/18 11:34:01 jan Exp $
 *
 * This is a script to migrate History information out of the datatree
 * tables and into its own database table.
 */

// Find the base file path of Horde.
@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();
$cli = Horde_CLI::singleton();

$cli->writeln($cli->yellow("Beginning migration. This may take a very long time to complete."));
$cli->writeln();

require_once HORDE_BASE . '/lib/base.php';
require_once 'Horde/DataTree.php';

class DataTreeObject_History extends DataTreeObject {

    function _fromAttributes($attributes)
    {
        /* Initialize data array. */
        $this->data = array();

        foreach ($attributes as $attr) {
            if (!isset($this->data[$attr['name']])) {
                $this->data[$attr['name']] = array();
            }
            $this->data[$attr['name']][$attr['key']] = $attr['value'];
        }
    }

}

$datatree = &DataTree::factory('sql', array_merge(Horde::getDriverConfig('datatree', 'sql'),
                                                  array('group' => 'horde.history')));
$db = &$datatree->_db;

$isql = 'INSERT INTO horde_histories (history_id, object_uid, history_action, history_desc, history_who, history_ts, history_extra)' .
        ' VALUES (?, ?, ?, ?, ?, ?, ?)';

$all = $datatree->get(DATATREE_FORMAT_FLAT, DATATREE_ROOT, true);
unset($all[DATATREE_ROOT]);
$ids = array_keys($all);

foreach ($ids as $id) {
    $ob = $datatree->getObjectById($id, 'DataTreeObject_History');
    foreach ($ob->getData() as $row) {
        $values = array($db->nextId('horde_histories'),                  // history_id
                        $ob->getName(),                                  // object_uid
                        isset($row['action']) ? $row['action'] : null,   // history_action
                        isset($row['desc']) ? $row['desc'] : null,       // history_desc
                        isset($row['who']) ? $row['who'] : null,         // history_who
                        isset($row['ts']) ? $row['ts'] : null,           // history_ts
                        );

        unset($row['action']);
        unset($row['desc']);
        unset($row['who']);
        unset($row['ts']);
        if (count($row)) {
            $values[] = serialize($row);                                 // history_extra
        } else {
            $values[] = null;                                            // history_extra
        }

        check($db->query($isql, $values));
    }

    check($db->query('DELETE FROM horde_datatree_attributes WHERE datatree_id = ?', array($id)));
    check($db->query('DELETE FROM horde_datatree WHERE datatree_id = ?', array($id)));
}

$cli->writeln($cli->green("Done. Migrated " . count($ids) . " objects."));

function check($result)
{
    if (is_a($result, 'PEAR_Error')) {
        var_dump($result);
        exit;
    }
}
