<?php
/**
 * $Horde: turba/browse.php,v 1.3.2.14 2003/03/04 16:03:34 chuck 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_once TURBA_BASE . '/lib/List.php';
require TURBA_BASE . '/config/attributes.php';

/* Sort out the sorting values. */
if (($sortby = Horde::getFormData('sortby')) !== null) {
    if ($sortby == 'name') {
        $sortby = 'lastname';
    }
    $prefs->setValue('sortby', $sortby);
    $prefs->store();
}
if (($sortdir = Horde::getFormData('sortdir')) !== null) {
    $prefs->setValue('sortdir', $sortdir);
    $prefs->store();
}

$title = _("Address Book Listing");
$js_onLoad = null;

/* Initialize $actionID to a resonable value if it hasn't already been
 * set. */
$actionID = Horde::getFormData('actionID');

/* Build the directory sources select widget. */
$source = Horde::getFormData('source');
if ($source == null || !isset($cfgSources[$source])) {
    $source_options = '';
    $source_count = 0;
    foreach ($cfgSources as $key => $curSource) {
        if (!empty($curSource['export'])) {
            $source_options .= '<option value="' . $key . '">' . $curSource['title'] . '</option>';
            $source = $key;
            $source_count++;
        }
    }
} else {
    $source_count = 1;
}

if ($source_count == 0) {
    Horde::raiseMessage(_("There are no browseable address books."), HORDE_WARNING);
} elseif ($source_count == 1) {
    $driver = &Turba_Source::singleton($source, $cfgSources[$source]);
    if (PEAR::isError($driver)) {
        Horde::raiseMessage(_("Failed to access the specified address book."), HORDE_ERROR);
        unset($driver);
    }
}

if (isset($driver)) {
    /* Run through the action handlers. */
    switch ($actionID) {
    case TURBA_DELETE:
        /* Remove a contact from a list. */
        $keys = Horde::getFormData('objectkeys');
        if (is_array($keys)) {

            $key = Horde::getFormData('key', false);
            if ($key && $key != "**search") {
                /* We are removing a contact from a list. */
                $list = $driver->getObject($key);
                foreach ($keys as $objectKey) {
                    if (!$list->removeMember($driver->getObject($objectKey))) {
                        Horde::raiseMessage(_("There was an error removing this object."), HORDE_ERROR);
                    } else {
                        Horde::raiseMessage(_("Contact removed from list."), HORDE_SUCCESS);
                    }
                }
            } else {
                /* We are deleting an object. */
                foreach ($keys as $objectKey) {
                    if (!$driver->removeObject($objectKey)) {
                        Horde::raiseMessage(_("There was an error deleting this object."), HORDE_ERROR);
                    }
                }
            }

            /* Remove the objects from search results too */
            if (!empty($_SESSION['turba_search_results'])) {
                require_once TURBA_BASE . '/lib/Object.php';
                $list = Turba_List::unserialize($_SESSION['turba_search_results']);
                foreach ($keys as $objectKey) {
                    $list->remove($objectKey);
                }
                $_SESSION['turba_search_results'] = $list->serialize();
            }
        }
        break;

    case TURBA_ADD:
        /* Add a contact to a list */
        $keys = Horde::getFormData('objectkeys');
        $targetKey = Horde::getFormData('targetList');
        if (empty($targetKey)) {
            break;
        }

        if (!Horde::getFormData('targetNew')) {
            $target = $driver->getObject($targetKey);
        }

        if (!empty($target) && is_object($target) && $target->isGroup()) {
            /* Adding contact to an existing list */
            if (is_array($keys)) {
                foreach ($keys as $objectKey) {
                    $target->addMember($driver->getObject($objectKey));
                }
                $target->store();
            }
        } else {
            /* Adding conect to a new list */
            $newList = array();
            $newList['__owner'] = Auth::getAuth();
            $newList['__type'] = 'Group';
            $newList['name'] = $targetKey;

            $targetKey = $driver->addObject($newList);
            $target = $driver->getObject($targetKey);

            if (!empty($target) && is_object($target) && $target->isGroup()) {
                if (is_array($keys)) {
                    foreach ($keys as $objectKey) {
                        $target->addMember($driver->getObject($objectKey));
                    }
                    $target->store();
                }
            } else {
                Horde::raiseMessage(_("There was an error creating a new list."), HORDE_ERROR);
            }
        }
        break;
    }
}

require TURBA_TEMPLATES . '/common-header.inc';
require TURBA_BASE . '/menu.php';
require TURBA_BASE . '/status.php';
if ($source_count > 1) {
    include TURBA_TEMPLATES . '/browse/select.inc';
} elseif (isset($driver)) {
    include TURBA_TEMPLATES . '/browse/javascript.inc';

    /* Read the columns to display from the preferences. */
    $sources = Turba::string2Columns($prefs->getValue('columns'));
    $columns = isset($sources[$source]) ? $sources[$source] : array();
    $width = floor(90 / (count($columns) + 1));

    /* Determine the name of the column to sort by */
    $sortcolumn = ($prefs->getValue('sortby') == 0 ||
                   !isset($columns[$prefs->getValue('sortby') - 1])) ?
        'lastname' : $columns[$prefs->getValue('sortby') - 1];

    /* Create list of lists for Add to. */
    $addToList = array();
    if (!empty($cfgSources[$source]['map']['__type'])) {
        $listList = $driver->search(array('__type' => 'Group'), null, null, 0);
        $listList->reset();
        while ($listObject = $listList->next()) {
            $addToList[] = array('name' => $listObject->getValue('name'), 'key' => $listObject->getValue('__key'));
        }
    }

    if (!empty($_SESSION['turba_search_results']) &&
        Horde::getFormData('key') == '**search') {
        /* We are displaying some search results */
        $results = Turba_List::unserialize($_SESSION['turba_search_results']);
        $results->sort($sortcolumn, null, null, $prefs->getValue('sortdir'));

        include TURBA_TEMPLATES . '/browse/search.inc';

        $title =_("Search Results");
        include TURBA_TEMPLATES . '/browse/header.inc';

        $listType = 'search';
        include TURBA_TEMPLATES . '/browse/actions.inc';
        include TURBA_TEMPLATES . '/browse/column_headers.inc';

        require_once TURBA_BASE . '/lib/ListView.php';
        $display = &new Turba_ListView($results, TURBA_TEMPLATES . '/browse/contactrow.inc');
        $numDisplayed = $display->display();

        include TURBA_TEMPLATES . '/browse/column_footers.inc';

    } else if (Horde::getFormData('key')) {
        /* We are displaying the contents of a list */
        $list = $driver->getObject(Horde::getFormData('key'));
        if (isset($list) && is_object($list) && $list->isGroup()) {
            $title = sprintf(_("Addresses in list: %s"), $list->getValue('name'));
            include TURBA_TEMPLATES . '/browse/header.inc';
            /* Show List Members */
            if (!is_object($results = $list->listMembers($sortcolumn, $prefs->getValue('sortdir')))) {
                Horde::raiseMessage(_("Failed to browse list"), HORDE_ERROR);
                include TURBA_BASE . '/status.php';
            } else {
                $listType = "list";
                include TURBA_TEMPLATES . '/browse/actions.inc';
                include TURBA_TEMPLATES . '/browse/column_headers.inc';

                require_once TURBA_BASE . '/lib/ListView.php';
                $display = &new Turba_ListView($results, TURBA_TEMPLATES . '/browse/contactrow.inc');
                $numDisplayed = $display->display();

                include TURBA_TEMPLATES . '/browse/column_footers.inc';
            }
        } else {
            Horde::raiseMessage(_("There was an error displaying the select List"), HORDE_ERROR);
            include TURBA_BASE . '/status.php';
        }
    } else {
        /* We are displaying the contents of the address book */
        $title = sprintf(_("Contents of %s"), $cfgSources[$source]['title']);
        include TURBA_TEMPLATES . '/browse/header.inc';
        if (Horde::getFormData('show', 'all') == 'contacts') {
            /* Show Contacts */
            $results = $driver->search(array('__type' => 'Object'), $sortcolumn, null, $prefs->getValue('sortdir'));
        } elseif (Horde::getFormData('show', 'all') == 'lists') {
            /* Show Lists */
            $results = $driver->search(array('__type' => 'Group'), $sortcolumn, null, $prefs->getValue('sortdir'));
        } else {
            /* Show All */
            $results = $driver->search(array(), $sortcolumn, null, $prefs->getValue('sortdir'));
        }

        if (!is_object($results)) {
            Horde::raiseMessage(_("Failed to browse the directory"), HORDE_ERROR);
            include TURBA_BASE . '/status.php';
        } else {
            $listType = 'directory';
            include TURBA_TEMPLATES . '/browse/actions.inc';
            include TURBA_TEMPLATES . '/browse/column_headers.inc';

            require_once TURBA_BASE . '/lib/ListView.php';
            $display = &new Turba_ListView($results, TURBA_TEMPLATES . '/browse/contactrow.inc');
            $numDisplayed = $display->display();

            include TURBA_TEMPLATES . '/browse/column_footers.inc';
        }
    }
}

require TURBA_TEMPLATES . '/browse/footer.inc';
$registry->shutdown();
require TURBA_TEMPLATES . '/common-footer.inc';
