<?php
/**
 * The Auth_ldap class provides an LDAP implementation of the Horde
 * authentication system.
 *
 * Required parameters:
 * ====================
 *   'basedn'    --  The base DN for the LDAP server.
 *   'hostspec'  --  The hostname of the LDAP server.
 *   'uid'       --  The username search key.
 *
 *
 * $Horde: horde/lib/Auth/ldap.php,v 1.21 2003/08/18 01:57:40 jwm Exp $
 *
 * Copyright 1999-2003 Jon Parise <jon@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  Jon Parise <jon@horde.org>
 * @version $Revision: 1.21 $
 * @since   Horde 1.3
 * @package horde.auth
 */
class Auth_ldap extends Auth {

    /**
     * An array of capabilities, so that the driver can report which
     * operations it supports and which it doesn't.
     *
     * @var array $capabilities
     */
    var $capabilities = array('add'         => true,
                              'update'      => false,
                              'remove'      => false,
                              'list'        => true,
                              'transparent' => false,
                              'loginscreen' => false);

    /**
     * Constructs a new LDAP authentication object.
     *
     * @access public
     *
     * @param optional array $params  A hash containing connection parameters.
     */
    function Auth_ldap($params = array())
    {
        if (!Horde::extensionExists('ldap')) {
            Horde::fatal(PEAR::raiseError(_("Auth_ldap: Required LDAP extension not found."), __FILE__, __LINE__));
        }

        $this->_setParams($params);
    }

    /**
     * Set configuration parameters
     *
     * @access private
     *
     * @param array $params  A hash containing connection parameters.
     */
    function _setParams($params)
    {
        /* Ensure we've been provided with all of the necessary parameters. */
        if (!array_key_exists('hostspec', $params)) {
            Horde::fatal(PEAR::raiseError(_("Required 'hostspec' not specified in authentication configuration.")), __FILE__, __LINE__);
        }
        if (!array_key_exists('basedn', $params)) {
            Horde::fatal(PEAR::raiseError(_("Required 'basedn' not specified in authentication configuration.")), __FILE__, __LINE__);
        }
        if (!array_key_exists('uid', $params)) {
            Horde::fatal(PEAR::raiseError(_("Required 'uid' not specified in authentication configuration.")), __FILE__, __LINE__);
        }

        $this->_params = $params;
    }

    /**
     * Find out if the given set of login credentials are valid.
     *
     * @access private
     *
     * @param string $userID      The userID to check.
     * @param array $credentials  An array of login credentials.
     *
     * @return boolean  True on success or a PEAR_Error object on failure.
     */
    function _authenticate($userID, $credentials)
    {
        if (!array_key_exists('password', $credentials)) {
            Horde::fatal(PEAR::raiseError(_("No password provided for LDAP authentication.")), __FILE__, __LINE__);
        }

        /* Connect to the LDAP server. */
        $ldap = @ldap_connect($this->_params['hostspec']);
        if (!$ldap) {
            $this->_setAuthError(_("Failed to connect to LDAP server."));
            return false;
        }

        /* Search for the user's full DN. */
        $search = @ldap_search($ldap, $this->_params['basedn'],
            $this->_params['uid'] . '=' . $userID, array($this->_params['uid']));
        $result = @ldap_get_entries($ldap, $search);
        if (is_array($result) && (count($result) > 1)) {
            $dn = $result[0]['dn'];
        } else {
            $this->_setAuthError(_("Empty result."));
            return false;
        }

        /* Attempt to bind to the LDAP server as the user. */
        $bind = @ldap_bind($ldap, $dn, $credentials['password']);
        if ($bind != false) {
            @ldap_close($ldap);
            Auth::setAuth($userID, $credentials);
            return true;
        } else {
            @ldap_close($ldap);
            $this->_setAuthError();
            return false;
        }
    }

    /**
     * Add a set of authentication credentials.
     *
     * @access public
     *
     * @param string $userID      The userID to add.
     * @param array $credentials  The credentials to be set.
     *
     * @return mixed  True on success or a PEAR_Error object on failure.
     */
    function addUser($userID, $credentials)
    {
        $ldap = @ldap_connect($this->_params['hostspec']);

        $binddn = $this->_params['uid'] . '=' . $this->_params['username'] . ',' . $this->_params['basedn'];
        $bind = @ldap_bind($ldap, $binddn, $this->_params['password']);

        $dn = $this->_params['uid'] . '=' . $userID . ',' . $this->_params['basedn'];
        $entry['objectClass'][0] = 'top';
        $entry['objectClass'][1] = 'person';
        $entry['cn'] = $userID;
        $entry['sn'] = $userID;
        $entry['userpassword'] = $credentials['password'];
        @ldap_add($ldap, $dn, $entry);

        return true;
    }

    /**
     * List Users
     *
     * @access public
     *
     * @return array  List of Users
     */
    function listUsers()
    {
        $ldap = @ldap_connect($this->_params['hostspec']);

        $dn = $this->_params['uid'] . '=' . $this->_params['username'] . ',' . $this->_params['basedn'];
        $bind = @ldap_bind($ldap, $dn, $this->_params['password']);

        $search = ldap_search($ldap, $this->_params['basedn'],
                              'objectClass=person');
        $entries = ldap_get_entries($ldap, $search);
        $userlist = array();
        for ($i = 0; $i < $entries['count']; $i++) {
            $userlist[$i] = $entries[$i]['cn'][0];
        }

        return $userlist;
    }

}
