<?php
/**
 * $Horde: turba/browse.php,v 1.38 2003/07/17 16:29:40 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') {
        if ($prefs->getValue('name_format') == 'first_last') {
            $sortby = 'name';
        } else {
            $sortby = 'lastname';
        }
    }
    $prefs->setValue('sortby', $sortby);
}
if (($sortdir = Horde::getFormData('sortdir')) !== null) {
    $prefs->setValue('sortdir', $sortdir);
}

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

/* Build the directory sources select widget. */
$source = Horde::getFormData('source', $prefs->getValue('default_dir'));
$source_options = '';
$source_count = 0;
foreach ($cfgSources as $key => $curSource) {
    if (!empty($curSource['export'])) {
        $selected = ($key == $source) ? ' selected="selected"' : '';
        $source_options .= '<option value="' . $key . '" ' . $selected;
        $source_options .= '>' . $curSource['title'] . '</option>';
        $source_count++;
        if (empty($source)) {
            $source = $key;
        }
    }
}

if ($source_count == 0) {
    $notification->push(_("There are no browseable address books."), 'horde.warning');
} else {
    $driver = &Turba_Source::singleton($source, $cfgSources[$source]);
    if (is_a($driver, 'PEAR_Error')) {
        $notification->push(_("Failed to access the specified address book."), 'horde.error');
        unset($driver);
    }
}

if (isset($driver)) {
    $actionID = Horde::getFormData('actionID');

    /* Run through the action handlers. */
    switch ($actionID) {
    case '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))) {
                        $notification->push(_("There was an error removing this object."), 'horde.error');
                    } else {
                        $notification->push(_("Contact removed from list."), 'horde.success');
                    }
                }
            } else {
                /* We are deleting an object. */
                foreach ($keys as $objectKey) {
                    if (!$driver->removeObject($objectKey)) {
                        $notification->push(_("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 '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 {
                $notification->push(_("There was an error creating a new list."), 'horde.error');
            }
        }
        break;
    }
}

$templates = array();
if (isset($driver)) {
    $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])) ?
        (($prefs->getValue('name_format') == 'first_last') ? 'name' : '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 (isset($_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, $prefs->getValue('sortdir'));

        $templates[] = '/browse/search.inc';
        $templates[] = '/browse/header.inc';
        $templates[] = '/browse/actions.inc';
        $templates[] = '/browse/column_headers.inc';

        $title =_("Search Results");
        $listType = 'search';

        require_once TURBA_BASE . '/lib/ListView.php';
        $display = &new Turba_ListView($results, TURBA_TEMPLATES . '/browse/contactrow.inc');
    } elseif (Horde::getFormData('key')) {
        /* We are displaying the contents of a list */
        $list = $driver->getObject(Horde::getFormData('key'));
        if (isset($list) && is_object($list) && !is_a($list,'PEAR_Error') && $list->isGroup()) {
            $title = sprintf(_("Addresses in list: %s"), $list->getValue('name'));
            $templates[] = '/browse/header.inc';
            /* Show List Members */
            if (!is_object($results = $list->listMembers($sortcolumn, $prefs->getValue('sortdir')))) {
                $notification->push(_("Failed to browse list"), 'horde.error');
            } else {
                $listType = 'list';
                $templates[] = '/browse/actions.inc';
                $templates[] = '/browse/column_headers.inc';

                require_once TURBA_BASE . '/lib/ListView.php';
                $display = &new Turba_ListView($results, TURBA_TEMPLATES . '/browse/contactrow.inc');
            }
        } else {
            $notification->push(_("There was an error displaying the select List"), 'horde.error');
        }
    } else {
        /* We are displaying the contents of the address book */
        if ($source_count > 1) {
            $templates[] = '/browse/select.inc';
        }
        $title = sprintf(_("Contents of %s"), $cfgSources[$source]['title']);
        $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)) {
            $notification->push(_("Failed to browse the directory"), 'horde.error');
        } else {
            $listType = 'directory';
            $templates[] = '/browse/actions.inc';
            $templates[] = '/browse/column_headers.inc';

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

require TURBA_TEMPLATES . '/common-header.inc';
Turba::menu();

foreach ($templates as $template) {
    require TURBA_TEMPLATES . $template;
}

if (isset($display) && is_object($display)) {
    $numDisplayed = $display->display();
    require TURBA_TEMPLATES . '/browse/column_footers.inc';
}

require TURBA_TEMPLATES . '/browse/footer.inc';
require TURBA_TEMPLATES . '/common-footer.inc';
