<?php
/**
 * Net_IMSP_Utils::
 *
 * $Horde: framework/Net_IMSP/IMSP/Utils.php,v 1.3.10.3 2005/02/27 17:40:23 mrubinsk Exp $
 *
 * Copyright 2003-2005 Michael Rubinsky <mrubinsk@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.
 *
 * @author  Michael Rubinsky <mrubinsk@horde.org>
 * @package Net_IMSP
 */
class Net_IMSP_Utils {

    /**
     * Utility function to retrieve the names of all the addressbooks
     * that the user has access to, along with the acl for those
     * books.  For information about the $serverInfo array see
     * turba/config/sources.php as this is the cfgSources[] entry for
     * the addressbooks.
     *
     * @param array $serverInfo  Information about the server
     *                           and the current user.
     *
     * @return array  Information about all the addressbooks or PEAR_Error.
     */
    function getAllBooks($serverInfo)
    {
        require_once 'Net/IMSP.php';
        $foundDefault = false;
        $results = array();
        $imsp = &Net_IMSP::singleton('Book', $serverInfo['params']);
        $result = $imsp->init();

        if (is_a($result, 'PEAR_Error')) {
            return $result;
        }

        $books = $imsp->getAddressBookList();
        if (is_a($books, 'PEAR_Error')) {
            return $books;
        }

        for ($i = 0; $i < count($books); $i++) {
            if ($books[$i] != $serverInfo['params']['username']) {
                $newBook = $serverInfo;
                $newBook['title'] = 'IMSP_' . $books[$i];
                $newBook['params']['name'] = $books[$i];
                if (strpos($imsp->myRights($books[$i]), 'w') !== false) {
                    $newBook['readonly'] = false;
                } else {
                    $newBook['readonly'] = true;
                }

                $results[] = $newBook;
            } else {
                $foundDefault = true;
            }
        }
        /* For our purposes, no default addressbook means auth must have failed
         * probably due to bad username*/
        if (!$foundDefault) {
            return PEAR::raiseError(IMSP_EXIT_LOGIN_FAILED . ': Default addressbook is missing!');
        }
        return $results;
    }

}
