<?php
/*
 * $Horde: turba/search.php,v 1.47.2.15 2003/01/03 12:48:58 jan Exp $
 *
 * Turba: Copyright 2000-2003 Charles J. Hagenbuch <chuck@horde.org>
 *
 * You should have received a copy of the GNU Public
 * License along with this package; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

define('TURBA_BASE', dirname(__FILE__));
require_once TURBA_BASE . '/lib/base.php';
require_once TURBA_BASE . '/lib/Source.php';
require TURBA_BASE . '/config/attributes.php';

$title = _("Search");
$js_onLoad = null;

/* Make sure the search session variable is registered in the session,
   and obtain a global-scope reference to it. */
if (!array_key_exists('turba_search_results', $_SESSION)) {
    $_SESSION['turba_search_results'] = null;
} else {
    if (Horde::getFormData('clear')) {
        $_SESSION['turba_search_results'] = null;
    } elseif (!empty($_SESSION['turba_search_results'])) {
        require_once TURBA_BASE . '/lib/List.php';
        require_once TURBA_BASE . '/lib/Object.php';
        $_SESSION['turba_search_results'] = Turba_List::unserialize($_SESSION['turba_search_results']);
    }
}

/* Run search if there is one. */
$source = Horde::getFormData('source');
if (!isset($source) && isset($cfgSources) && is_array($cfgSources) && count($cfgSources) > 0) {
    reset($cfgSources);
    $source = key($cfgSources);
}

$criteria = Horde::getFormData('criteria');
$val = Horde::getFormData('val');
if (isset($criteria) && isset($val)) {
    $driver = &Turba_Source::singleton($source, $cfgSources[$source]);
    if (PEAR::isError($driver)) {
        Horde::raiseMessage(_("Failed to connect to the specified directory."), HORDE_ERROR);
    } else {
        if (is_object($results = $driver->search(array($criteria => $val)))) {
            if (!is_object($_SESSION['turba_search_results'])) {
                $_SESSION['turba_search_results'] = new Turba_List();
            }
            $combinedResults = new Turba_List();
            $combinedResults->merge($_SESSION['turba_search_results'], false);
            $combinedResults->merge($results);
            $_SESSION['turba_search_results'] = $combinedResults->serialize();

            $url = Turba::addParameter('browse.php', 'key=**search');
            $url = Turba::addParameter($url, 'source=' . urlencode($source));

            header('Location: ' . Horde::applicationUrl($url, true));
        } else {
            Horde::raiseMessage(sprintf(_("Failed to search the directory: %s"), ''), HORDE_ERROR);
        }
    }
}

require TURBA_TEMPLATES . '/common-header.inc';
require TURBA_BASE . '/menu.php';
require TURBA_BASE . '/status.php';
require TURBA_TEMPLATES . '/browse/search.inc';
require TURBA_TEMPLATES . '/common-footer.inc';

if (is_object($_SESSION['turba_search_results'])) {
    $_SESSION['turba_search_results'] = $_SESSION['turba_search_results']->serialize();
}
