<?php
/**
 * $Horde: horde/services/portal/syncml.php,v 1.3.2.3 2006/02/10 04:58:26 selsky Exp $
 *
 * Copyright 2005-2006 Karsten Fourmont <karsten@horde.org>
 *
 * See the enclosed file COPYING for license information (LGPL). If you
 * did not receive this file, see http://www.fsf.org/copyleft/lgpl.html.
 */

function loadCategories($device)
{
    global $dt, $categoriesMap, $missingServerCategories;
    $map = $dt->getObject($device
                           . ':categories');
    if (is_a($map, 'PEAR_Error')) {
        return false;
    }

    $categoriesMap = $map->get('map');
    $missingServerCategories = $map->get('missingServerCategories');

    return true;
}

function storeCategories($device)
{
    global $dt, $categoriesMap, $missingServerCategories;

    if (!is_array($categoriesMap)) {
        return; // nothing to do
    }

    $map = &new DataTreeObject($device . ':categories');
    $map->set('map', $categoriesMap);
    $map->set('missingServerCategories', $missingServerCategories);

    $r = $dt->add($map);
    if (is_a($r, 'PEAR_Error')) {
        // Object already exists: update instead.
        $r = $dt->updateData($map);
    }
}

@define('HORDE_BASE', dirname(__FILE__) . '/../..');
require_once HORDE_BASE . '/lib/base.php';
require_once 'Horde/Prefs/UI.php';

if (!Auth::isAuthenticated()) {
    Horde::authenticationFailureRedirect();
}

$driver = $GLOBALS['conf']['datatree']['driver'];
$params = Horde::getDriverConfig('datatree', $driver);
$params = array_merge($params, array( 'group' => 'syncml' ));

$dt = &DataTree::singleton($driver, $params);

/* Username is used as root for syncml datatree.  (For historic
 * reasons.) */
$username = Auth::getAuth();
$group = 'syncml'; // preference group

$actionID = Util::getFormData('actionID');
switch ($actionID) {
case 'deleteanchor':
    $deviceid = Util::getFormData('deviceid');
    $db = Util::getFormData('db');
    $id = $username . ':' . $deviceid . ':summary:' . $db;
    $id = $dt->remove($id,false);
    if (is_a($id, 'PEAR_Error')) {
        $notification->push(sprintf(_("Error deleting sync anchor: %s"), $id->getMessage()),
                            'horde.error');
    } else {
        $notification->push(_("$id Sync anchor for device '$deviceid' database '$db' deleted."),
                            'horde.success');
    }
    break;

case 'deletelog':
    $id = $dt->remove('previousSyncLog', false);
    if (is_a($id, 'PEAR_Error')) {
        $notification->push(sprintf(_("Error deleting sync log: %s"), $id->getMessage()),
                            'horde.error');
    } else {
        $notification->push(_("Sync log deleted"),
                            'horde.success');
    }
    break;

 case 'update_categories':
    $device = Util::getFormData('device');
    loadCategories($device);

    foreach ($_POST as $key => $value) {
        if (substr($key, 0, 9) == 'category:') {
            $category = substr($key,9);
            list(,$category) = explode(':', $key,2);
            $value = Util::getFormData($key);
            $categoriesMap[$category] = $value;
            unset($missingServerCategories[$value]);
        }
    }
    storeCategories($device);
    $notification->push(_("Mappings stored."));

    break;
}

/* Show the header. */
require_once 'Horde/Prefs/UI.php';
require HORDE_BASE . '/config/prefs.php';
$app = 'horde';

Prefs_UI::handleForm($group, $prefs);
Prefs_UI::generateHeader($group);

// @todo: move this to template
?>

<form method="post" name="prefs" action="<?php echo Horde::ApplicationURL('/services/prefs.php') ?>">
<input type="hidden" name="actionID" value="update_prefs" />
<input type="hidden" name="group" value="<?php echo $group ?>" />
<input type="hidden" name="app" value="horde" />
Sorry, no configurable options yet.
See <a href="http://wiki.horde.org/SyncHowTo">Sync HowTo</a> for further information.
<?php /* $helplink=''; $pref='syncml_create_log'; require $registry->get('templates', 'horde') . '/prefs/checkbox.inc' */ ?>

<p class="nowrap">
 <input type="submit" class="button" value="Save Options" />
 <input type="reset" class="button" value="Undo Changes" />
 <input type="button" class="button" value="Return to Options" onclick="document.prefs.actionID.value=0; document.prefs.group.value=''; document.prefs.submit();" />
</p>
</form>
<?php
$id = $dt->getId($username);

$devices = $dt->getById(DATATREE_FORMAT_FLAT, $id, true,
                     DATATREE_ROOT,1);

if (is_array($devices) && count($devices) > 1) {
    array_shift($devices);

// @todo: move to template
?>
<div class="header">
 <?php echo Horde::link(Horde::selfURL(), _("Refresh")) . Horde::img('reload.png', _("Reload"), '', $registry->getImageDir('horde')) ?></a>
 Timestamps of successful sync sessions
</div>
<table class="striped" >
 <tr>
  <th>Device</th><th>Database</th><th>Server-TS</th><th>Client-TS</th>
  <th>Delete</th>
 </tr>

<?php
    foreach ($devices as $device) {
        $device_name = array_pop(explode(':', $device));

        $id = $dt->getId($device . ':summary');
        $summaries = $dt->getById(DATATREE_FORMAT_TREE, $id, false,
                                  DATATREE_ROOT, 2);

        if (is_array($summaries[$id])) {
            $o = & $dt->getObjects(array_keys($summaries[$id]));

            foreach ($o as $oo) {
                $t = explode(':', $oo->getName());
                $db = array_pop($t);
                $sa = $oo->get('ServerAnchor');
                $ca = $oo->get("ClientAnchor");

                // @todo: move to template
                echo '<tr><td>' . $device_name . '</td><td>' . $db . '</td><td>' .
                    strftime($prefs->getValue('date_format') . ' %H:%M', array_pop($sa)) .
                    '</td><td>' . array_pop($ca) . '</td><td>' .
                    '<form method="post"><input type="hidden" name="deviceid" value="' .
                    $device_name . '"/>' .
                    '<input type="hidden" name="actionID" value="deleteanchor" />' .
                    '<input type="hidden" name="db" value="' . $db . '"/>' .
                    '<input type="submit" class="button" value="Delete"></form>' .
                    '</td></tr>';
            }
        }
    }
    echo '</table>';
}

// Category handling.
require_once 'Horde/Prefs/CategoryManager.php';
$cManager = &new Prefs_CategoryManager();

foreach ($devices as $device) {
    $device_name = array_pop(explode(':', $device));

    if (!loadCategories($device)) {
        continue;
    }
//var_dump($clien
    $i = 0;
// @todo: move to template
?>
<form method="post" name="prefs" action="<?php echo Horde::selfURL() ?>">
<input type="hidden" name="actionID" value="update_categories" />
<input type="hidden" name="device" value="<?php echo $device ?>" />

<div class="header">
 <?php echo Horde::link(Horde::selfURL(), _("Refresh")) . Horde::img('reload.png', _("Reload"), '', $registry->getImageDir('horde')) ?></a>
 Mapping of Categories for Device <?php echo $device_name ?>
</div>
<table class="striped" >
<tr><th>Device Category</th><th>Horde Category</th>
<th>Summary of last encountered entry</th></tr>
<?php
    foreach ($categoriesMap as $key => $value) {
        echo "<tr class=\"item" . (++$i % 2) . "\"><td>"
        . $key. '</td><td>';
        $v = is_array($value) ? '' : $value;
        echo $cManager->getSelect('category:' . $key, $v);
        echo '</td><td>';
        if (is_array($value)) {
            echo $value[0];
        } else {
            echo "&nbsp;";
        }
        echo '</td></tr>';

    }
    foreach ($missingServerCategories as $key => $value) {
        echo '<tr><td><em>to be defined</em></td><td>' . $key . '</td><td>' . $value . '</td></tr>';
    }

    echo "</table>\n";
    echo '<input type="submit" class="button" value="Update Categories"></form>';
}

/* Display log of previous sync. */
$name = 'previousSyncLog';
$info = &$dt->getObject($name);

if (!is_a($info, 'PEAR_Error') && is_array($log = $info->get('log'))) {
    // @todo move to template
?>
<div class="header">
 <?php echo _("Log of previous sync session") ?>
 <?php echo Horde::link(Horde::selfURL(), _("Refresh")) . Horde::img('reload.png', _("Refresh")) ?></a>
 <form method="post">
  <input type="hidden" name="actionID" value="deletelog" />
  <input type="submit" class="button" value="<?php echo _("Delete Log") ?>" />
 </form>
</div>

<table class="striped" width="100%">
 <tr class="nowrap">
  <th width="5%"><?php echo _("Time") ?></th><th><?php echo _("Level") ?></th><th><?php echo _("File") ?></th><th><?php echo _("Message") ?></th>
 </tr>
<?php foreach ($log as $logentry): ?>
 <tr>
  <td>
   <?php echo strftime($prefs->getValue('date_format') . ' %H:%M:%S', $logentry['ts']) ?>
  </td>
  <td>
   <?php echo htmlspecialchars($logentry['level']) ?>
  </td>
  <td>
  <?php
  if (preg_match('/\/SyncML\.php$/', $logentry['file'])) {
      $file = 'framework/SyncML/SyncML.php';
  } else {
      $file = preg_replace('/^.*\/SyncML\/(.*)$/', 'framework/SyncML/SyncML/$1', $logentry['file']);
  }
  echo Horde::link('http://cvs.horde.org/co.php/'
                   . $file  . '?r=HEAD#' . trim($logentry['line']), '', '', 'cvs')
      . preg_replace('/^.*\/([^\/]*)$/', '$1', $logentry['file'])
      . ':' . trim($logentry['line'])
  ?>
  </td>
  <td>
   <?php echo htmlspecialchars($logentry['message']) ?>
  </td>
 </tr>
<?php endforeach; ?>
</table>

<?php
}

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