Horde_Auth binder usage
authorMichael M Slusarz <slusarz@curecanti.org>
Mon, 31 May 2010 23:47:37 +0000 (17:47 -0600)
committerMichael M Slusarz <slusarz@curecanti.org>
Wed, 2 Jun 2010 03:32:14 +0000 (21:32 -0600)
Use Horde_Db and Horde_Ldap where appropriate.

80 files changed:
ansel/perms.php
ansel/scripts/all_images_exif_to_tags.php
ansel/scripts/ansel.php
ansel/scripts/recursive_import.php
ansel/xppublish.php
beatnik/scripts/export_config.php
folks/account/resetpassword.php
folks/account/signup.php
folks/account/tabs.php
folks/edit/password.php
folks/lib/Friends.php
folks/perms.php
folks/rss/activity.php
folks/rss/friends.php
folks/rss/know.php
folks/scripts/mail.php
framework/ActiveSync/lib/Horde/ActiveSync/Driver/Horde.php
framework/Auth/lib/Horde/Auth.php
framework/Auth/lib/Horde/Auth/Application.php
framework/Auth/lib/Horde/Auth/Auto.php
framework/Auth/lib/Horde/Auth/Base.php
framework/Auth/lib/Horde/Auth/Composite.php
framework/Auth/lib/Horde/Auth/Customsql.php
framework/Auth/lib/Horde/Auth/Cyrsql.php
framework/Auth/lib/Horde/Auth/Cyrus.php
framework/Auth/lib/Horde/Auth/Exception.php
framework/Auth/lib/Horde/Auth/Ftp.php
framework/Auth/lib/Horde/Auth/Http.php
framework/Auth/lib/Horde/Auth/Http/Remote.php
framework/Auth/lib/Horde/Auth/Imap.php
framework/Auth/lib/Horde/Auth/Imsp.php
framework/Auth/lib/Horde/Auth/Ipbasic.php
framework/Auth/lib/Horde/Auth/Kolab.php
framework/Auth/lib/Horde/Auth/Ldap.php
framework/Auth/lib/Horde/Auth/Login.php
framework/Auth/lib/Horde/Auth/Msad.php
framework/Auth/lib/Horde/Auth/Pam.php
framework/Auth/lib/Horde/Auth/Passwd.php
framework/Auth/lib/Horde/Auth/Peclsasl.php
framework/Auth/lib/Horde/Auth/Radius.php
framework/Auth/lib/Horde/Auth/Shibboleth.php
framework/Auth/lib/Horde/Auth/Smb.php
framework/Auth/lib/Horde/Auth/Smbclient.php
framework/Auth/lib/Horde/Auth/Sql.php
framework/Auth/package.xml
framework/Core/lib/Horde/Core/Binder/Auth.php [new file with mode: 0644]
framework/Core/lib/Horde/Core/Factory/Auth.php [new file with mode: 0644]
framework/Core/lib/Horde/Core/Perms/Ui.php
framework/Core/lib/Horde/Registry.php
framework/Core/package.xml
framework/Group/Group.php
framework/Kolab_Filter/lib/Horde/Kolab/Resource.php
framework/Rpc/lib/Horde/Rpc.php
framework/Rpc/lib/Horde/Rpc/Webdav.php
framework/SyncML/SyncML/Backend/Horde.php
horde/admin/groups.php
horde/admin/signup_confirm.php
horde/admin/user.php
horde/lib/Prefs/Ui.php
horde/login.php
horde/scripts/cookie_login.php
horde/scripts/get_login.php
horde/scripts/http_login_refer.php
horde/services/changepassword.php
horde/services/resetpassword.php
horde/services/shares/edit.php
horde/signup.php
imp/lib/Application.php
ingo/scripts/ingo-postfix-policyd
koward/lib/Koward.php
koward/lib/Koward/Cli.php
koward/www/horde/config/prefs.php.dist
kronolith/feed/index.php
kronolith/lib/Kronolith.php
kronolith/perms.php
kronolith/templates/chunks/calendar.php
turba/scripts/upgrades/public_to_horde_share.php
whups/lib/Forms/Admin/User.php
whups/lib/Mail.php
wicked/scripts/wicked.php

index 774d1c7..d0a568c 100644 (file)
@@ -21,7 +21,7 @@ Horde_Registry::appInit('ansel');
 require_once 'Horde/Group.php';
 
 $groups = Group::singleton();
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
 
 $form = null;
 $reload = false;
index 3685692..4451d42 100755 (executable)
@@ -56,7 +56,7 @@ Horde_Registry::appInit('ansel', array('authentication' => 'none'));
 
 // Login to horde if username & password are set.
 if (!empty($username) && !empty($password)) {
-    $auth = Horde_Auth::singleton($conf['auth']['driver']);
+    $auth = $injector->getInstance('Horde_Auth')->getOb();
     if (!$auth->authenticate($username, array('password' => $password))) {
         $cli->fatal(_("Username or password is incorrect."));
     } else {
index 2cb26ce..ef065f3 100755 (executable)
@@ -88,7 +88,7 @@ foreach ($opts as $opt) {
 
 // Login to horde if username & password are set.
 if (!empty($username) && !empty($password)) {
-    $auth = Horde_Auth::singleton($conf['auth']['driver']);
+    $auth = $injector->getInstance('Horde_Auth')->getOb();
     if (!$auth->authenticate($username, array('password' => $password))) {
         $error = _("Login is incorrect.");
         Horde::logMessage($error, 'ERR');
index 2e4f739..3e54ed3 100755 (executable)
@@ -61,7 +61,7 @@ foreach ($opts as $opt) {
 
 // Login to horde if username & password are set.
 if (!empty($username) && !empty($password)) {
-    $auth = Horde_Auth::singleton($conf['auth']['driver']);
+    $auth = $injector->getInstance('Horde_Auth')->getOb();
     if (!$auth->authenticate($username, array('password' => $password))) {
         $cli->fatal(_("Username or password is incorrect."));
     } else {
index b3fd9bf..7370651 100644 (file)
@@ -36,7 +36,7 @@ if ($cmd == 'login') {
     $username = Horde_Util::getFormData('username');
     $password = Horde_Util::getFormData('password');
     if ($username && $password) {
-        $auth = Horde_Auth::singleton($conf['auth']['driver']);
+        $auth = $injector->getInstance('Horde_Auth')->getOb();
         if ($auth->authenticate($username,
                                 array('password' => $password))) {
             $cmd = 'list';
index 34f1ac9..b105c5e 100644 (file)
@@ -92,9 +92,8 @@ if (!empty($rpc)) {
 
 // Login to horde if username & password are set and load module.
 } elseif (!empty($username) && !empty($password)) {
-
     require_once HORDE_BASE . '/lib/base.php';
-    $auth = &Horde_Auth::singleton($conf['auth']['driver']);
+    $auth = $injector->getInstance('Horde_Auth')->getOb();
     if (!$auth->authenticate($username, array('password' => $password))) {
         $error = _("Login is incorrect.");
         Horde::logMessage($error, 'ERR');
index 9cb5d14..a0a74e7 100644 (file)
@@ -35,7 +35,7 @@ if (Horde_Auth::isAuthenticated()) {
 }
 
 // Make sure auth backend allows passwords to be reset.
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
 if (!$auth->hasCapability('resetpassword')) {
     $notification->push(_("Cannot reset password automatically, contact your administrator."), 'horde.error');
     Horde_Auth::authenticateFailure('folks');
index 4764ccf..16148c2 100644 (file)
@@ -12,7 +12,7 @@
 
 require_once dirname(__FILE__) . '/tabs.php';
 
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
 
 // Make sure signups are enabled before proceeding
 if ($conf['signup']['allow'] !== true ||
index fb17225..86dae38 100644 (file)
@@ -13,7 +13,7 @@
 $folks_authentication = 'none';
 require_once dirname(__FILE__) . '/../lib/base.php';
 
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
 
 $vars = Horde_Variables::getDefaultVariables();
 $tabs = new Horde_Ui_Tabs('what', $vars);
index e56893e..21ae062 100644 (file)
@@ -16,7 +16,7 @@ require_once 'tabs.php';
 
 /*
 // Make sure auth backend allows passwords to be updated.
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
 if (!$auth->hasCapability('resetpassword')) {
     $notification->push(_("Cannot update password, contact your administrator."), 'horde.error');
     Horde_Auth::authenticateFailure('folks');
index 9144b5c..9657e4a 100644 (file)
@@ -218,7 +218,7 @@ class Folks_Friends {
         }
 
         // Check if users exits
-        $auth = Horde_Auth::singleton($GLOBALS['conf']['auth']['driver']);
+        $auth = $GLOBALS['injector']->getInstance('Horde_Auth')->getOb();
         if (!$auth->exists($user)) {
             return PEAR::raiseError(sprintf(_("User \"%s\" does not exits"), $user));
         }
@@ -287,7 +287,7 @@ class Folks_Friends {
         }
 
         // Check if users exits
-        $auth = Horde_Auth::singleton($GLOBALS['conf']['auth']['driver']);
+        $auth = $GLOBALS['injector']->getInstance('Horde_Auth')->getOb();
         if (!$auth->exists($friend)) {
             return PEAR::raiseError(sprintf(_("User \"%s\" does not exits"), $friend));
         }
index 0d0e1b1..284ca0e 100644 (file)
@@ -14,7 +14,7 @@ require_once 'Horde/Group.php';
 
 $shares = $GLOBALS['injector']->getInstance('Horde_Share')->getScope();
 $groups = &Group::singleton();
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
 
 $reload = false;
 $actionID = Horde_Util::getFormData('actionID', 'edit');
index 045ad35..53a401e 100644 (file)
@@ -14,7 +14,7 @@
 $folks_authentication = 'none';
 require_once dirname(__FILE__) . '/../lib/base.php';
 
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
 if (!Horde_Auth::getAuth() &&
     (!isset($_SERVER['PHP_AUTH_USER']) ||
      !$auth->authenticate($_SERVER['PHP_AUTH_USER'], array('password' => isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : null)))) {
index 9efb607..28b6967 100644 (file)
@@ -14,7 +14,7 @@
 $folks_authentication = 'none';
 require_once dirname(__FILE__) . '/../lib/base.php';
 
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
 if (!Horde_Auth::getAuth() &&
     (!isset($_SERVER['PHP_AUTH_USER']) ||
      !$auth->authenticate($_SERVER['PHP_AUTH_USER'], array('password' => isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : null)))) {
index 859c877..0c0237c 100644 (file)
@@ -14,7 +14,7 @@
 $folks_authentication = 'none';
 require_once dirname(__FILE__) . '/../lib/base.php';
 
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
 if (!Horde_Auth::getAuth() &&
     (!isset($_SERVER['PHP_AUTH_USER']) ||
      !$auth->authenticate($_SERVER['PHP_AUTH_USER'], array('password' => isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : null)))) {
index 81e032b..49a8091 100644 (file)
@@ -62,7 +62,7 @@ foreach ($opts as $opt) {
 
 // Login to horde if username & password are set.
 if (!empty($username) && !empty($password)) {
-    $auth = Horde_Auth::singleton($conf['auth']['driver']);
+    $auth = $injector->getInstance('Horde_Auth')->getOb();
     if (!$auth->authenticate($username, array('password' => $password))) {
         $error = _("Login is incorrect.");
         Horde::logMessage($error, 'ERR');
index d10ed15..9f7cce0 100644 (file)
@@ -67,7 +67,7 @@ class Horde_ActiveSync_Driver_Horde extends Horde_ActiveSync_Driver_Base
     {
         $this->_logger->info('Horde_ActiveSync_Driver_Horde::logon attempt for: ' . $username);
         parent::logon($username, $password, $domain);
-        $auth = Horde_Auth::singleton($GLOBALS['conf']['auth']['driver']);
+        $auth = $GLOBALS['injector']->getInstance('Horde_Auth')->getOb();
 
         return $auth->authenticate($username, array('password' => $password));
     }
index 43b7455..9d394d9 100644 (file)
@@ -28,7 +28,8 @@
  * @author   Chuck Hagenbuch <chuck@horde.org>
  * @author   Michael Slusarz <slusarz@horde.org>
  * @category Horde
- * @package  Horde_Auth
+ * @license  http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package  Auth
  */
 class Horde_Auth
 {
@@ -87,13 +88,6 @@ class Horde_Auth
     static public $dnsResolver;
 
     /**
-     * Singleton instances.
-     *
-     * @var array
-     */
-    static protected $_instances = array();
-
-    /**
      * The logout reason information.
      *
      * @var array
@@ -115,11 +109,8 @@ class Horde_Auth
     static public function factory($driver, $params = null)
     {
         $driver = str_replace(' ', '_' , ucwords(str_replace('_', ' ', basename($driver))));
-        if (empty($params)) {
-            $params = Horde::getDriverConfig('auth', $driver);
-        }
-
         $class = __CLASS__ . '_' . $driver;
+
         if (class_exists($class)) {
             return new $class($params);
         }
@@ -128,33 +119,6 @@ class Horde_Auth
     }
 
     /**
-     * Attempts to return a reference to a concrete instance based on $driver.
-     * It will only create a new instance if no instance with the same
-     * parameters currently exists.
-     *
-     * This method must be invoked as: $var = Horde_Auth::singleton()
-     *
-     * @param mixed $driver  The type of concrete Horde_Auth_Base subclass
-     *                       to return.
-     * @param array $params  A hash containing any additional configuration or
-     *                       connection parameters a subclass might need.
-     *
-     * @return Horde_Auth_Base  The concrete reference.
-     * @throws Horde_Auth_Exception
-     */
-    static public function singleton($driver, $params = array())
-    {
-        ksort($params);
-        $signature = hash('md5', serialize(array($driver, $params)));
-
-        if (!isset(self::$_instances[$signature])) {
-            self::$_instances[$signature] = self::factory($driver, $params);
-        }
-
-        return self::$_instances[$signature];
-    }
-
-    /**
      * Formats a password using the current encryption.
      *
      * @param string $plaintext      The plaintext password to encrypt.
@@ -390,8 +354,8 @@ class Horde_Auth
 
         /* Try transparent authentication. */
         $auth = (empty($options['app']) || ($options['app'] == 'horde'))
-            ? self::singleton($GLOBALS['conf']['auth']['driver'])
-            : self::singleton('application', array('app' => $options['app']));
+            ? $GLOBALS['injector']->getInstance('Horde_Auth')->getOb()
+            : $GLOBALS['injector']->getInstance('Horde_Auth')->getOb('application', array('app' => $options['app']));
 
         return $auth->transparent();
     }
@@ -408,12 +372,9 @@ class Horde_Auth
      */
     static public function requireAuth($app)
     {
-        if ($app == 'horde') {
-            return false;
-        }
-
-        $app_auth = self::singleton('application', array('app' => $app));
-        return $app_auth->requireAuth();
+        return ($app == 'horde')
+            ? false
+            : $GLOBALS['injector']->getInstance('Horde_Auth')->getOb('application', array('app' => $app))->requireAuth();
     }
 
     /**
@@ -437,8 +398,7 @@ class Horde_Auth
             }
         }
 
-        $auth = self::singleton($GLOBALS['conf']['auth']['driver']);
-        return $auth->checkExistingAuth();
+        return $GLOBALS['injector']->getInstance('Horde_Auth')->getOb()->checkExistingAuth();
     }
 
     /**
index 9747f30..84eaa57 100644 (file)
@@ -4,18 +4,15 @@
  * application-provided Horde authentication which fits inside the
  * Horde_Auth:: API.
  *
- * Required parameters:
- * <pre>
- * 'app' - (string) The application which is providing authentication.
- * </pre>
- *
  * Copyright 2002-2010 The Horde Project (http://www.horde.org/)
  *
  * See the enclosed file COPYING for license information (LGPL). If you did
  * not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
  *
- * @author  Chuck Hagenbuch <chuck@horde.org>
- * @package Horde_Auth
+ * @author   Chuck Hagenbuch <chuck@horde.org>
+ * @category Horde
+ * @license  http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package  Auth
  */
 class Horde_Auth_Application extends Horde_Auth_Base
 {
@@ -47,14 +44,21 @@ class Horde_Auth_Application extends Horde_Auth_Base
     /**
      * Constructor.
      *
-     * @param array $params  A hash containing connection parameters.
-     * @throws Horde_Exception
+     * @param array $params  Required parameters:
+     * <pre>
+     * 'app' - (string) The application which is providing authentication.
+     * </pre>
+     *
+     * @throws InvalidArgumentException
      */
-    public function __construct($params = array())
+    public function __construct(array $params = array())
     {
-        Horde::assertDriverConfig($params, 'auth', array('app'), 'authentication application');
+        if (!isset($params['app'])) {
+            throw new InvalidArgumentException('Missing app parameter.');
+        }
 
         $this->_app = $params['app'];
+
         parent::__construct($params);
     }
 
index 6527050..0018664 100644 (file)
@@ -5,24 +5,15 @@
  * This is only for use in testing or behind a firewall; it should NOT be
  * used on a public, production machine.
  *
- * Optional parameters:
- * <pre>
- * 'password' - (string) The password to record in the user's credentials.
- *              DEFAULT: none
- * 'requestuser' - (boolean) If true, allow username to be passed by GET, POST
- *                 or cookie.
- *                DEFAULT: No
- * 'username' - (string) The username to authenticate everyone as.
- *              DEFAULT: 'horde_user'
- * </pre>
- *
  * Copyright 1999-2010 The Horde Project (http://www.horde.org/)
  *
  * See the enclosed file COPYING for license information (LGPL). If you did
  * not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
  *
- * @author  Chuck Hagenbuch <chuck@horde.org>
- * @package Horde_Auth
+ * @author   Chuck Hagenbuch <chuck@horde.org>
+ * @category Horde
+ * @license  http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package  Auth
  */
 class Horde_Auth_Auto extends Horde_Auth_Base
 {
@@ -39,15 +30,26 @@ class Horde_Auth_Auto extends Horde_Auth_Base
     /**
      * Constructor.
      *
-     * @param array $params  A hash containing parameters.
+     * @param array $params  Optional parameters:
+     * <pre>
+     * 'password' - (string) The password to record in the user's credentials.
+     *              DEFAULT: none
+     * 'requestuser' - (boolean) If true, allow username to be passed by GET,
+     *                 POST or cookie.
+     *                 DEFAULT: No
+     * 'username' - (string) The username to authenticate everyone as.
+     *              DEFAULT: 'horde_user'
+     * </pre>
      */
-    public function __construct($params = array())
+    public function __construct(array $params = array())
     {
-        parent::__construct($params);
+        $params = array_merge(array(
+            'password' => '',
+            'requestuser' => false,
+            'username' => 'horde_user'
+        ), $params);
 
-        if (!isset($this->_params['username'])) {
-            $this->_params['username'] = 'horde_user';
-        }
+        parent::__construct($params);
     }
 
     /**
@@ -62,7 +64,7 @@ class Horde_Auth_Auto extends Horde_Auth_Base
      */
     protected function _authenticate($userId, $credentials)
     {
-        throw new Horde_Auth_Exception('unsupported');
+        throw new Horde_Auth_Exception('Unsupported.');
     }
 
     /**
index 020e0ef..39110f4 100644 (file)
@@ -8,9 +8,11 @@
  * See the enclosed file COPYING for license information (LGPL). If you did
  * not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
  *
- * @author  Chuck Hagenbuch <chuck@horde.org>
- * @author  Michael Slusarz <slusarz@horde.org>
- * @package Horde_Auth
+ * @author   Chuck Hagenbuch <chuck@horde.org>
+ * @author   Michael Slusarz <slusarz@horde.org>
+ * @category Horde
+ * @license  http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package  Auth
  */
 abstract class Horde_Auth_Base
 {
@@ -52,17 +54,35 @@ abstract class Horde_Auth_Base
     /**
      * Current application for authentication.
      *
-     * @param string
+     * @var string
      */
     protected $_app = 'horde';
 
     /**
+     * Logger object.
+     *
+     * @var Horde_Log_Logger
+     */
+    protected $_logger;
+
+    /**
      * Constructor.
      *
-     * @param array $params  A hash containing parameters.
+     * @param array $params  Optional parameters:
+     * <pre>
+     * 'logger' - (Horde_Log_Logger) A logger object.
+     * 'notify_expire' - (callback) Callback function to output notification
+     *                   when password is about to expire. Passed one
+     *                   argument: UNIX timestamp of when password expires.
+     * </pre>
      */
-    public function __construct($params = array())
+    public function __construct(array $params = array())
     {
+        if (isset($params['logger'])) {
+            $this->_logger = $params['logger'];
+            unset($params['logger']);
+        }
+
         $this->_params = $params;
     }
 
@@ -152,7 +172,7 @@ abstract class Horde_Auth_Base
      */
     public function addUser($userId, $credentials)
     {
-        throw new Horde_Auth_Exception('unsupported');
+        throw new Horde_Auth_Exception('Unsupported.');
     }
 
     /**
@@ -166,7 +186,7 @@ abstract class Horde_Auth_Base
      */
     public function updateUser($oldID, $newID, $credentials)
     {
-        throw new Horde_Auth_Exception('unsupported');
+        throw new Horde_Auth_Exception('Unsupported.');
     }
 
     /**
@@ -178,7 +198,7 @@ abstract class Horde_Auth_Base
      */
     public function removeUser($userId)
     {
-        throw new Horde_Auth_Exception('unsupported');
+        throw new Horde_Auth_Exception('Unsupported.');
     }
 
     /**
@@ -189,7 +209,7 @@ abstract class Horde_Auth_Base
      */
     public function listUsers()
     {
-        throw new Horde_Auth_Exception('unsupported');
+        throw new Horde_Auth_Exception('Unsupported.');
     }
 
     /**
@@ -267,7 +287,7 @@ abstract class Horde_Auth_Base
      */
     public function resetPassword($userId)
     {
-        throw new Horde_Auth_Exception('unsupported');
+        throw new Horde_Auth_Exception('Unsupported.');
     }
 
     /**
index 87a3e45..f597c76 100644 (file)
@@ -3,30 +3,39 @@
  * The Horde_Auth_Composite class provides a way to combine two separate
  * drivers for admin vs. authentication purposes.
  *
- * Required parameters:
- * <pre>
- * 'admin_driver' - (string) TODO
- * 'admin_driver_config' - (array) TODO
- * 'auth_driver' - (string) TODO
- * 'auth_driver_config' - (string) TODO
- * </pre>
- *
  * Copyright 2002-2010 The Horde Project (http://www.horde.org/)
  *
  * See the enclosed file COPYING for license information (LGPL). If you did
  * not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
  *
- * @author  Chuck Hagenbuch <chuck@horde.org>
- * @package Horde_Auth
+ * @author   Chuck Hagenbuch <chuck@horde.org>
+ * @category Horde
+ * @license  http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package  Auth
  */
 class Horde_Auth_Composite extends Horde_Auth_Base
 {
     /**
-     * Hash containing any instantiated drivers.
+     * Constructor.
+     *
+     * @param array $params  Required parameters:
+     * <pre>
+     * 'admin_driver' - (Horde_Auth_Base) The admin driver.
+     * 'auth_driver' - (Horde_Auth_Base) The auth driver.
+     * </pre>
      *
-     * @var array
+     * @throws InvalidArgumentException
      */
-    protected $_drivers = array();
+    public function __construct(array $params = array())
+    {
+        foreach (array('admin_driver', 'auth_driver') as $val) {
+            if (!isset($params[$val])) {
+                throw new InvalidArgumentException('Missing ' . $val . ' parameter.');
+            }
+        }
+
+        parent::__construct($params);
+    }
 
     /**
      * Find out if a set of login credentials are valid.
@@ -38,8 +47,7 @@ class Horde_Auth_Composite extends Horde_Auth_Base
      */
     protected function _authenticate($userId, $credentials)
     {
-        $driver = $this->_loadDriver('auth');
-        return $driver->authenticate($userId, $credentials, false);
+        return $this->_params['auth_driver']->authenticate($userId, $credentials, false);
     }
 
     /**
@@ -53,8 +61,7 @@ class Horde_Auth_Composite extends Horde_Auth_Base
     public function hasCapability($capability)
     {
         try {
-            $driver = $this->_loadDriver('admin');
-            return $driver->hasCapability($capability);
+            return $this->_params['admin_driver']->hasCapability($capability);
         } catch (Horde_Auth_Exception $e) {
             return false;
         }
@@ -69,8 +76,7 @@ class Horde_Auth_Composite extends Horde_Auth_Base
     protected function _transparent()
     {
         try {
-            $driver = $this->_loadDriver('auth');
-            return $driver->transparent();
+            return $this->_params['auth_driver']->transparent();
         } catch (Horde_Auth_Exception $e) {
             return false;
         }
@@ -86,8 +92,7 @@ class Horde_Auth_Composite extends Horde_Auth_Base
      */
     public function addUser($userId, $credentials)
     {
-        $driver = $this->_loadDriver('admin');
-        $driver->addUser($userId, $credentials);
+        $this->_params['admin_driver']->addUser($userId, $credentials);
     }
 
     /**
@@ -101,8 +106,7 @@ class Horde_Auth_Composite extends Horde_Auth_Base
      */
     public function updateUser($oldID, $newID, $credentials)
     {
-        $driver = $this->_loadDriver('admin');
-        $driver->updateUser($oldID, $newID, $credentials);
+        $this->_params['admin_driver']->updateUser($oldID, $newID, $credentials);
     }
 
     /**
@@ -111,13 +115,12 @@ class Horde_Auth_Composite extends Horde_Auth_Base
      *
      * @param string $userId  The user id for which to reset the password.
      *
-     * @return mixed  The new password on success or a PEAR_Error object on
-     *                failure.
+     * @return string  The new password on success.
+     * @throws Horde_Auth_Exception
      */
     public function resetPassword($userId)
     {
-        $driver = $this->_loadDriver('admin');
-        $driver->resetPassword($userId);
+        return $this->_params['admin_driver']->resetPassword($userId);
     }
 
     /**
@@ -129,8 +132,7 @@ class Horde_Auth_Composite extends Horde_Auth_Base
      */
     public function removeUser($userId)
     {
-        $driver = $this->_loadDriver('admin');
-        $driver->removeUser($userId);
+        $this->_params['admin_driver']->removeUser($userId);
     }
 
     /**
@@ -141,8 +143,7 @@ class Horde_Auth_Composite extends Horde_Auth_Base
      */
     public function listUsers()
     {
-        $driver = $this->_loadDriver('admin');
-        return $driver->listUsers();
+        return $this->_params['admin_driver']->listUsers();
     }
 
     /**
@@ -155,28 +156,10 @@ class Horde_Auth_Composite extends Horde_Auth_Base
     public function exists($userId)
     {
         try {
-            $driver = $this->_loadDriver('admin');
-            return $driver->exists($userId);
+            return $this->_params['admin_driver']->exists($userId);
         } catch (Horde_Auth_Exception $e) {
             return false;
         }
     }
 
-    /**
-     * Loads one of the drivers in our configuration array, if it isn't already
-     * loaded.
-     *
-     * @param string $driver  The name of the driver to load.
-     *
-     * @throws Horde_Auth_Exception
-     */
-    protected function _loadDriver($driver)
-    {
-        if (empty($this->_drivers[$driver])) {
-            $this->_drivers[$driver] = Horde_Auth::singleton($this->_params[$driver . '_driver'], $this->_params[$driver . '_driver_config']);
-        }
-
-        return $this->_drivers[$driver];
-    }
-
 }
index abd66e3..0409121 100644 (file)
@@ -3,40 +3,18 @@
  * The Horde_Auth_Customsql class provides a sql implementation of the Horde
  * authentication system with the possibility to set custom-made queries.
  *
- * Required parameters: See Horde_Auth_Sql driver.
- * <pre>
- * Some special tokens can be used in the sql query. They are replaced
- * at the query stage:
- *
- *   - '\L' will be replaced by the user's login
- *   - '\P' will be replaced by the user's password.
- *   - '\O' will be replaced by the old user's login (required for update)
- *
- *   Eg: "SELECT * FROM users WHERE uid = \L
- *                            AND passwd = \P
- *                            AND billing = 'paid'
- *
- *   'query_auth'    Authenticate the user.       '\L' & '\P'
- *   'query_add'     Add user.                    '\L' & '\P'
- *   'query_getpw'   Get one user's password.     '\L'
- *   'query_update'  Update user.                 '\O', '\L' & '\P'
- *   'query_resetpassword'  Reset password.       '\L', & '\P'
- *   'query_remove'  Remove user.                 '\L'
- *   'query_list'    List user.
- *   'query_exists'  Check for existance of user. '\L'
- * </pre>
- *
- * Optional parameters: See Horde_Auth_Sql driver.
- *
  * Copyright 2002 Ronnie Garcia <ronnie@mk2.net>
+ * Copyright 2002-2010 The Horde Project (http://www.horde.org/)
  *
  * See the enclosed file COPYING for license information (LGPL). If you did
  * not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
  *
- * @author  Ronnie Garcia <ronnie@mk2.net>
- * @author  Chuck Hagenbuch <chuck@horde.org>
- * @author  Joel Vandal <joel@scopserv.com>
- * @package Horde_Auth
+ * @author   Ronnie Garcia <ronnie@mk2.net>
+ * @author   Chuck Hagenbuch <chuck@horde.org>
+ * @author   Joel Vandal <joel@scopserv.com>
+ * @category Horde
+ * @license  http://opensource.org/licenses/lgpl-2.1.php
+ * @package  Auth
  */
 class Horde_Auth_Customsql extends Horde_Auth_Sql
 {
@@ -58,13 +36,39 @@ class Horde_Auth_Customsql extends Horde_Auth_Sql
     /**
      * Constructor.
      *
-     * @param array $params  A hash containing connection parameters.
+     * Some special tokens can be used in the SQL query. They are replaced
+     * at the query stage:
+     *   '\L' will be replaced by the user's login
+     *   '\P' will be replaced by the user's password.
+     *   '\O' will be replaced by the old user's login (required for update)
+     *
+     * Eg: "SELECT * FROM users WHERE uid = \L
+     *                          AND passwd = \P
+     *                          AND billing = 'paid'
+     *
+     * @param array $params  Configuration parameters:
+     * <pre>
+     * 'query_auth' - (string) Authenticate the user. ('\L' & '\P')
+     * 'query_add' - (string) Add user. ('\L' & '\P')
+     * 'query_getpw' - (string) Get one user's password. ('\L')
+     * 'query_update' - (string) Update user. ('\O', '\L' & '\P')
+     * 'query_resetpassword' - (string) Reset password. ('\L', & '\P')
+     * 'query_remove' - (string) Remove user. ('\L')
+     * 'query_list' - (string) List user.
+     * 'query_exists' - (string) Check for existance of user. ('\L')
+     * </pre>
+     *
+     * @throws InvalidArgumentException
      */
-    public function __construct($params = array())
+    public function __construct(array $params = array())
     {
-        Horde::assertDriverConfig($params, 'auth',
-            array('query_auth'),
-            'authentication custom SQL');
+        foreach (array('query_auth', 'query_add', 'query_getpw',
+                       'query_update', 'query_resetpassword', 'query_remove',
+                       'query_list', 'query_exists') as $val) {
+            if (!isset($params[$val])) {
+                throw new InvalidArgumentException('Missing ' . $val . ' parameter.');
+            }
+        }
 
         parent::__construct($params);
     }
@@ -79,36 +83,24 @@ class Horde_Auth_Customsql extends Horde_Auth_Sql
      */
     protected function _authenticate($userId, $credentials)
     {
-        try {
-            $this->_connect();
-        } catch (Horde_Auth_Exception $e) {
-            throw new Horde_Auth_Exception('', Horde_Auth::REASON_FAILED);
-        }
-
         /* Build a custom query, based on the config file. */
-        $query = $this->_params['query_auth'];
-        $query = str_replace('\L', $this->_db->quote($userId), $query);
-        $query = str_replace('\P', $this->_db->quote(Horde_Auth::getCryptedPassword(
-                                                         $credentials['password'],
-                                                         $this->_getPassword($userId),
-                                                         $this->_params['encryption'],
-                                                         $this->_params['show_encryption'])), $query);
+        $query = str_replace(
+            array('\L', '\P'),
+            array(
+                $this->_db->quote($userId),
+                $this->_db->quote(Horde_Auth::getCryptedPassword($credentials['password'], $this->_getPassword($userId), $this->_params['encryption'], $this->_params['show_encryption']))
+            ),
+            $this->_params['query_auth']
+        );
 
-        $result = $this->_db->query($query);
-        if ($result instanceof PEAR_Error) {
+        try {
+            if ($this->_db->selectValue($query)) {
+                return;
+            }
+            throw new Horde_Auth_Exception('', Horde_Auth::REASON_BADLOGIN);
+        } catch (Horde_Db_Exception $e) {
             throw new Horde_Auth_Exception('', Horde_Auth::REASON_FAILED);
         }
-
-        $row = $result->fetchRow(DB_GETMODE_ASSOC);
-
-        /* If we have at least one returned row, then the user is valid. */
-        if (is_array($row)) {
-            $result->free();
-            return;
-        }
-
-        $result->free();
-        throw new Horde_Auth_Exception('', Horde_Auth::REASON_BADLOGIN);
     }
 
     /**
@@ -121,19 +113,20 @@ class Horde_Auth_Customsql extends Horde_Auth_Sql
      */
     public function addUser($userId, $credentials)
     {
-        $this->_connect();
-
         /* Build a custom query, based on the config file. */
-        $query = $this->_params['query_add'];
-        $query = str_replace('\L', $this->_db->quote($userId), $query);
-        $query = str_replace('\P', $this->_db->quote(Horde_Auth::getCryptedPassword(
-                                                         $credentials['password'], '',
-                                                         $this->_params['encryption'],
-                                                         $this->_params['show_encryption'])), $query);
+        $query = str_replace(
+            array('\L', 'P'),
+            array(
+                $this->_db->quote($userId),
+                $this->_db->quote(Horde_Auth::getCryptedPassword($credentials['password'], '', $this->_params['encryption'], $this->_params['show_encryption']))
+            ),
+            $this->_params['query_add']
+        );
 
-        $result = $this->_db->query($query);
-        if ($result instanceof PEAR_Error) {
-            throw new Horde_Auth_Exception($result);
+        try {
+            $this->_db->insert($query);
+        } catch (Horde_Db_Exception $e) {
+            throw new Horde_Auth_Exception($e);
         }
     }
 
@@ -146,23 +139,23 @@ class Horde_Auth_Customsql extends Horde_Auth_Sql
      *
      * @throws Horde_Auth_Exception
      */
-    function updateUser($oldId, $newId, $credentials)
+    public function updateUser($oldId, $newId, $credentials)
     {
-        $this->_connect();
-
         /* Build a custom query, based on the config file. */
-        $query = $this->_params['query_update'];
-        $query = str_replace('\O', $this->_db->quote($oldId), $query);
-        $query = str_replace('\L', $this->_db->quote($newId), $query);
-        $query = str_replace('\P', $this->_db->quote(Horde_Auth::getCryptedPassword(
-                                                         $credentials['password'],
-                                                         $this->_getPassword($oldId),
-                                                         $this->_params['encryption'],
-                                                         $this->_params['show_encryption'])), $query);
+        $query = str_replace(
+            array('\O', '\L', '\P'),
+            array(
+                $this->_db->quote($oldId),
+                $this->_db->quote($newId),
+                $this->_db->quote(Horde_Auth::getCryptedPassword($credentials['password'], $this->_getPassword($oldId), $this->_params['encryption'], $this->_params['show_encryption']))
+            ),
+            $this->_params['query_update']
+        );
 
-        $result = $this->_db->query($query);
-        if ($result instanceof PEAR_Error) {
-            throw new Horde_Auth_Exception($result);
+        try {
+            $this->_db->update($query);
+        } catch (Horde_Db_Exception $e) {
+            throw new Horde_Auth_Exception($e);
         }
     }
 
@@ -177,22 +170,23 @@ class Horde_Auth_Customsql extends Horde_Auth_Sql
      */
     public function resetPassword($userId)
     {
-        $this->_connect();
-
         /* Get a new random password. */
         $password = Horde_Auth::genRandomPassword();
 
         /* Build the SQL query. */
-        $query = $this->_params['query_resetpassword'];
-        $query = str_replace('\L', $this->_db->quote($userId), $query);
-        $query = str_replace('\P', $this->_db->quote(Horde_Auth::getCryptedPassword($password,
-                                                                               '',
-                                                                               $this->_params['encryption'],
-                                                                               $this->_params['show_encryption'])), $query);
+        $query = str_replace(
+            array('\L', '\P'),
+            array(
+                $this->_db->quote($userId),
+                $this->_db->quote(Horde_Auth::getCryptedPassword($password, '', $this->_params['encryption'], $this->_params['show_encryption']))
+            ),
+            $this->_params['query_resetpassword']
+        );
 
-        $result = $this->_db->query($query);
-        if ($result instanceof PEAR_Error) {
-            throw new Horde_Auth_Exception($result);
+        try {
+            $this->_db->update($query);
+        } catch (Horde_Db_Exception $e) {
+            throw new Horde_Auth_Exception($e);
         }
 
         return $password;
@@ -207,18 +201,20 @@ class Horde_Auth_Customsql extends Horde_Auth_Sql
      */
     public function removeUser($userId)
     {
-        $this->_connect();
-
         /* Build a custom query, based on the config file. */
-        $query = $this->_params['query_remove'];
-        $query = str_replace('\L', $this->_db->quote($userId), $query);
+        $query = str_replace(
+            '\L',
+            $this->_db->quote($userId),
+            $this->_params['query_remove']
+        );
 
-        $result = $this->_db->query($query);
-        if ($result instanceof PEAR_Error) {
-            throw new Horde_Auth_Exception($result);
+        try {
+            $this->_db->delete($query);
+        } catch (Horde_Db_Exception $e) {
+            throw new Horde_Auth_Exception($e);
         }
 
-        $this->removeUserData($userId);
+        Horde_Auth::removeUserData($userId);
     }
 
     /**
@@ -229,15 +225,17 @@ class Horde_Auth_Customsql extends Horde_Auth_Sql
      */
     public function listUsers()
     {
-        $this->_connect();
-
         /* Build a custom query, based on the config file. */
-        $query = $this->_params['query_list'];
-        $query = str_replace('\L', $this->_db->quote(Horde_Auth::getAuth()), $query);
+        $query = str_replace(
+            '\L',
+            $this->_db->quote(Horde_Auth::getAuth()),
+            $this->_params['query_list']
+        );
 
-        $result = $this->_db->getAll($query, null, DB_FETCHMODE_ORDERED);
-        if ($result instanceof PEAR_Error) {
-            throw new Horde_Auth_Exception($result);
+        try {
+            $result = $this->_db->selectAll($query);
+        } catch (Horde_Db_Exception $e) {
+            throw new Horde_Auth_Exception($e);
         }
 
         /* Loop through and build return array. */
@@ -256,43 +254,42 @@ class Horde_Auth_Customsql extends Horde_Auth_Sql
      */
     public function exists($userId)
     {
+        /* Build a custom query, based on the config file. */
+        $query = str_replace(
+            '\L',
+            $this->_db->quote($userId),
+            $this->_params['query_exists']
+        );
+
         try {
-            $this->_connect();
-        } catch (Horde_Auth_Exception $e) {
+            return (bool)$this->_db->selectValue($query);
+        } catch (Horde_Db_Exception $e) {
             return false;
         }
-
-        /* Build a custom query, based on the config file. */
-        $query = $this->_params['query_exists'];
-        $query = str_replace('\L', $this->_db->quote($userId), $query);
-
-        $result = $this->_db->getOne($query);
-
-        return ($result instanceof PEAR_Error)
-            ? false
-            : (bool)$result;
     }
 
     /**
      * Fetch $userId's current password - needed for the salt with some
      * encryption schemes when doing authentication or updates.
      *
-     * @param string $userId  TODO
+     * @param string $userId  The userId to query.
      *
      * @return string  $userId's current password.
      */
     protected function _getPassword($userId)
     {
         /* Retrieve the old password in case we need the salt. */
-        $query = $this->_params['query_getpw'];
-        $query = str_replace('\L', $this->_db->quote($userId), $query);
-        $pw = $this->_db->getOne($query);
-        if ($pw instanceof PEAR_Error) {
-            Horde::logMessage($pw, 'ERR');
-            return '';
-        }
+        $query = str_replace(
+            '\L',
+            $this->_db->quote($userId),
+            $this->_params['query_getpw']
+        );
 
-        return $pw;
+        try {
+            return $this->_db->selectValue($query);
+        } catch (Horde_Db_Exception $e) {
+            return null;
+        }
     }
 
 }
index 2537a1a..772202d 100644 (file)
@@ -5,34 +5,6 @@
  * is the same as for the SQL class; only what is different overrides the
  * parent class implementations.
  *
- * Required parameters: See Horde_Auth_Sql driver.
- * <pre>
- * 'cyradmin'  The username of the cyrus administrator.
- * 'cyrpass'   The password for the cyrus administrator.
- * 'hostspec'        The hostname or IP address of the server.
- *                   DEFAULT: 'localhost'
- * 'port'            The server port to which we will connect.
- *                   IMAP is generally 143, while IMAP-SSL is generally 993.
- *                   DEFAULT: Encryption port default
- * 'secure'          The encryption to use.  Either 'none', 'ssl', or 'tls'.
- *                   DEFAULT: 'none'
- * </pre>
- *
- * Optional parameters: See Horde_Auth_Sql driver.
- * <pre>
- * 'domain_field'    If set to anything other than 'none' this is used as
- *                   field name where domain is stored.
- *                   DEFAULT: 'domain_name'
- * 'hidden_accounts' An array of system accounts to hide from the user
- *                   interface.
- * 'folders'         An array of folders to create under username.
- *                   DEFAULT: NONE
- * 'quota'           The quota (in kilobytes) to grant on the mailbox.
- *                   DEFAULT: NONE
- * 'unixhier'        The value of imapd.conf's unixhierarchysep setting.
- *                   Set this to true if the value is true in imapd.conf.
- * </pre>
- *
  * The table structure for the auth system is as follows:
  * <pre>
  * CREATE TABLE accountuser (
  * See the enclosed file COPYING for license information (LGPL). If you did
  * not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
  *
- * @author  Ilya Krel <mail@krel.org>
- * @author  Jan Schneider <jan@horde.org>
- * @package Horde_Auth
+ * @author   Ilya Krel <mail@krel.org>
+ * @author   Jan Schneider <jan@horde.org>
+ * @category Horde
+ * @license  http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package  Auth
  */
 class Horde_Auth_Cyrsql extends Horde_Auth_Sql
 {
@@ -121,7 +95,7 @@ class Horde_Auth_Cyrsql extends Horde_Auth_Sql
      *
      * @var Horde_Imap_Client_Base
      */
-    protected $_ob;
+    protected $_imap;
 
     /**
      * Hierarchy separator to use (e.g., is it user/mailbox or user.mailbox)
@@ -133,23 +107,47 @@ class Horde_Auth_Cyrsql extends Horde_Auth_Sql
     /**
      * Constructor.
      *
-     * @param array $params  A hash containing connection parameters.
+     * @param array $params  Parameters:
+     * <pre>
+     * 'domain_field' - (string) If set to anything other than 'none' this is
+     *                  used as field name where domain is stored.
+     *                  DEFAULT: 'domain_name'
+     * 'folders' - (array) An array of folders to create under username.
+     *             DEFAULT: NONE
+     * 'hidden_accounts' - (array) An array of system accounts to hide from
+     *                     the user interface.
+     *                     DEFAULT: None.
+     * 'imap' - (Horde_Imap_Client_Base) [REQUIRED] An IMAP client object.
+     * 'quota' - (integer) The quota (in kilobytes) to grant on the mailbox.
+     *           DEFAULT: NONE
+     * 'unixhier' - (boolean) The value of imapd.conf's unixhierarchysep
+     *              setting. Set this to true if the value is true in
+     *              imapd.conf.
+     *              DEFAULT: false
+     * </pre>
+     *
+     * @throws InvalidArgumentException
      */
-    public function __construct($params = array())
+    public function __construct(array $params = array())
     {
-        parent::__construct($params);
+        if (!isset($params['imap']) ||
+            !($params['imap'] instanceof Horde_Imap_Client_Base)) {
+            throw new InvalidArgumentException('Missing imap parameter.');
+        }
+        $this->_imap = $params['imap'];
+        unset($params['imap']);
 
-        $admin_params = array(
-            'admin_user' => $params['cyradmin'],
-            'admin_password' => $params['cyrpass'],
-            'dsn' => $params['imap_dsn']
-        );
+        $params = array_merge(array(
+            'domain_field' => 'domain_name',
+            'folders' => array(),
+            'hidden_accounts' => array('cyrus'),
+            'quota' => null
+        ), $params);
 
-        if (!empty($this->_params['unixhier'])) {
-            $admin_params['userhierarchy'] = 'user/';
-        }
+        parent::__construct($params);
 
         if (!empty($this->_params['unixhier'])) {
+            $this->_params['userhierarchy'] = 'user/';
             $this->_separator = '/';
         }
     }
@@ -164,13 +162,6 @@ class Horde_Auth_Cyrsql extends Horde_Auth_Sql
      */
     protected function _authenticate($userId, $credentials)
     {
-        try {
-            $this->_connect();
-        } catch (Horde_Auth_Exception $e) {
-            Horde::logMessage($e, 'ERR');
-            throw new Horde_Auth_Exception('', Horde_Auth::REASON_FAILED);
-        }
-
         if (!empty($this->_params['domain_field']) &&
             ($this->_params['domain_field'] != 'none')) {
             /* Build the SQL query with domain. */
@@ -187,23 +178,14 @@ class Horde_Auth_Cyrsql extends Horde_Auth_Sql
             $values = array($userId);
         }
 
-        Horde::logMessage('SQL Query by Horde_Auth_Cyrsql::_authenticate(): ' . $query, 'DEBUG');
-
-        $result = $this->_db->query($query, $values);
-        if ($result instanceof PEAR_Error) {
-            Horde::logMessage($result, 'ERR');
+        try {
+            $row = $this->_db->selectOne($query, $values);
+        } catch (Horde_Db_Exception $e) {
             throw new Horde_Auth_Exception('', Horde_Auth::REASON_FAILED);
         }
 
-        $row = $result->fetchRow(DB_GETMODE_ASSOC);
-        if (is_array($row)) {
-            $result->free();
-        } else {
-            throw new Horde_Auth_Exception('', Horde_Auth::REASON_BADLOGIN);
-        }
-
-        if (!$this->_comparePasswords($row[$this->_params['password_field']],
-                                      $credentials['password'])) {
+        if (!$row ||
+            !$this->_comparePasswords($row[$this->_params['password_field']], $credentials['password'])) {
             throw new Horde_Auth_Exception('', Horde_Auth::REASON_BADLOGIN);
         }
 
@@ -231,35 +213,32 @@ class Horde_Auth_Cyrsql extends Horde_Auth_Sql
      */
     public function addUser($userId, $credentials)
     {
-        $this->_connect();
-
         if (!empty($this->_params['domain_field']) &&
             ($this->_params['domain_field'] != 'none')) {
             list($name, $domain) = explode('@', $userId);
-            /* Build the SQL query. */
+
             $query = sprintf('INSERT INTO %s (%s, %s, %s) VALUES (?, ?, ?)',
                              $this->_params['table'],
                              $this->_params['username_field'],
                              $this->_params['domain_field'],
                              $this->_params['password_field']);
-            $values = array($name,
-                            $domain,
-                            Horde_Auth::getCryptedPassword($credentials['password'],
-                                                      '',
-                                                      $this->_params['encryption'],
-                                                      $this->_params['show_encryption']));
-
-            Horde::logMessage('SQL Query by Horde_Auth_Cyrsql::addUser(): ' . $query, 'DEBUG');
-
-            $dbresult = $this->_db->query($query, $values);
-            $query = 'INSERT INTO virtual (alias, dest, username, status) VALUES (?, ?, ?, 1)';
-            $values = array($userId, $userId, $name);
-
-            Horde::logMessage('SQL Query by Horde_Auth_Cyrsql::addUser(): ' . $query, 'DEBUG');
+            $values = array(
+                $name,
+                $domain,
+                Horde_Auth::getCryptedPassword($credentials['password'],
+                                               '',
+                                               $this->_params['encryption'],
+                                               $this->_params['show_encryption'])
+            );
+
+            $query2 = 'INSERT INTO virtual (alias, dest, username, status) VALUES (?, ?, ?, 1)';
+            $values2 = array($userId, $userId, $name);
 
-            $dbresult2 = $this->_db->query($query, $values);
-            if ($dbresult2 instanceof PEAR_Error) {
-                throw new Horde_Auth_Exception($dbresult2);
+            try {
+                $this->_db->insert($query, $values);
+                $this->_db->insert($query2, $values2);
+            } catch (Horde_Db_Exception $e) {
+                throw new Horde_Auth_Exception($e);
             }
         } else {
             parent::addUser($userId, $credentials);
@@ -267,8 +246,8 @@ class Horde_Auth_Cyrsql extends Horde_Auth_Sql
 
         try {
             $mailbox = Horde_String::convertCharset($this->_params['userhierarchy'] . $userId, Horde_Nls::getCharset(), 'utf7-imap');
-            $ob->createMailbox($mailbox);
-            $ob->setACL($mailbox, $this->_params['cyradm'], 'lrswipcda');
+            $this->_imap->createMailbox($mailbox);
+            $this->_imap->setACL($mailbox, $this->_params['cyradm'], 'lrswipcda');
         } catch (Horde_Imap_Client_Exception $e) {
             throw new Horde_Auth_Exception($e);
         }
@@ -284,24 +263,18 @@ Horde_String::convertCharset($userName . $this->_separator . $value . '@' . $dom
             }
 
             $tmp = Horde_String::convertCharset($tmp, Horde_Nls::getCharset(), 'utf7-imap');
-            $ob->createMailbox($tmp);
-            $ob->setACL($tmp, $this->_params['cyradm'], 'lrswipcda');
+            $this->_imap->createMailbox($tmp);
+            $this->_oimap>setACL($tmp, $this->_params['cyradm'], 'lrswipcda');
         }
 
         if (isset($this->_params['quota']) &&
             ($this->_params['quota'] >= 0)) {
             try {
-                $this->_ob->setQuota($mailbox, array('storage' => $this->_params['quota']));
+                $this->_imap->setQuota($mailbox, array('storage' => $this->_params['quota']));
             } catch (Horde_Imap_Client_Exception $e) {
                 throw new Horde_Auth_Exception($e);
             }
         }
-
-        if (isset($this->_params['quota']) &&
-            ($this->_params['quota'] >= 0) &&
-            !@imap_set_quota($this->_imapStream, 'user' . $this->_separator . $userId, $this->_params['quota'])) {
-            throw new Horde_Auth_Exception(sprintf(_("IMAP mailbox quota creation failed: %s"), imap_last_error()));
-        }
     }
 
     /**
@@ -311,13 +284,12 @@ Horde_String::convertCharset($userName . $this->_separator . $value . '@' . $dom
      *
      * @throws Horde_Auth_Exception
      */
-    function removeUser($userId)
+    public function removeUser($userId)
     {
-        $this->_connect();
-
         if (!empty($this->_params['domain_field']) &&
             ($this->_params['domain_field'] != 'none')) {
             list($name, $domain) = explode('@', $userId);
+
             /* Build the SQL query. */
             $query = sprintf('DELETE FROM %s WHERE %s = ? and %s = ?',
                              $this->_params['table'],
@@ -325,17 +297,14 @@ Horde_String::convertCharset($userName . $this->_separator . $value . '@' . $dom
                              $this->_params['domain_field']);
             $values = array($name, $domain);
 
-            Horde::logMessage('SQL Query by Horde_Auth_Cyrsql::removeUser(): ' . $query, 'DEBUG');
-
-            $dbresult = $this->_db->query($query, $values);
-            $query = 'DELETE FROM virtual WHERE dest = ?';
-            $values = array($userId);
+            $query2 = 'DELETE FROM virtual WHERE dest = ?';
+            $values2 = array($userId);
 
-            Horde::logMessage('SQL Query by Horde_Auth_Cyrsql::removeUser(): ' . $query, 'DEBUG');
-
-            $dbresult2 = $this->_db->query($query, $values);
-            if ($dbresult2 instanceof PEAR_Error) {
-                return $dbresult2;
+            try {
+                $this->_db->delete($query, $values);
+                $this->_db->delete($query2, $values2);
+            } catch (Horde_Db_Exception $e) {
+                throw new Horde_Auth_Exception($e);
             }
         } else {
             parent::removeUser($userId);
@@ -345,8 +314,8 @@ Horde_String::convertCharset($userName . $this->_separator . $value . '@' . $dom
         list($admin) = explode('@', $this->_params['cyradmin']);
 
         try {
-            $this->_ob->setACL($mailbox, $admin, array('rights' => 'lrswipcda'));
-            $this->_ob->deleteMailbox($mailbox);
+            $this->_imap->setACL($mailbox, $admin, array('rights' => 'lrswipcda'));
+            $this->_imap->deleteMailbox($mailbox);
         } catch (Horde_Imap_Client_Exception $e) {
             throw new Horde_Auth_Exception($e);
         }
@@ -362,8 +331,6 @@ Horde_String::convertCharset($userName . $this->_separator . $value . '@' . $dom
      */
     public function listUsers()
     {
-        $this->_connect();
-
         if (!empty($this->_params['domain_field']) &&
             ($this->_params['domain_field'] != 'none')) {
             /* Build the SQL query with domain. */
@@ -380,17 +347,16 @@ Horde_String::convertCharset($userName . $this->_separator . $value . '@' . $dom
                              $this->_params['username_field']);
         }
 
-        Horde::logMessage('SQL Query by Horde_Auth_Cyrsql::listUsers(): ' . $query, 'DEBUG');
-
-        $result = $this->_db->getAll($query, null, DB_FETCHMODE_ORDERED);
-        if ($result instanceof PEAR_Error) {
-            throw new Horde_Auth_Exception($result);
+        try {
+            $result = $this->_db->selectAll($query);
+        } catch (Horde_Db_Exception $e) {
+            throw new Horde_Auth_Exception($e);
         }
 
         /* Loop through and build return array. */
         $users = array();
-        if (!empty($this->_params['domain_field'])
-            && ($this->_params['domain_field'] != 'none')) {
+        if (!empty($this->_params['domain_field']) &&
+            ($this->_params['domain_field'] != 'none')) {
             foreach ($result as $ar) {
                 if (!in_array($ar[0], $this->_params['hidden_accounts'])) {
                     $users[] = $ar[0] . '@' . $ar[1];
@@ -418,8 +384,6 @@ Horde_String::convertCharset($userName . $this->_separator . $value . '@' . $dom
      */
     public function updateUser($oldID, $newID, $credentials)
     {
-        $this->_connect();
-
         if (!empty($this->_params['domain_field']) &&
             ($this->_params['domain_field'] != 'none')) {
             list($name, $domain) = explode('@', $oldID);
@@ -447,51 +411,11 @@ Horde_String::convertCharset($userName . $this->_separator . $value . '@' . $dom
                             $oldID);
         }
 
-        Horde::logMessage('SQL Query by Horde_Auth_Cyrsql::updateUser(): ' . $query, 'DEBUG');
-
-        $res = $this->_db->query($query, $values);
-        if ($res instanceof PEAR_Error) {
-            throw new Horde_Auth_Exception($res);
-        }
-    }
-
-    /**
-     * Attempts to open connections to the SQL and IMAP servers.
-     *
-     * @throws Horde_Auth_Exception
-     */
-    public function _connect()
-    {
-        if ($this->_connected) {
-            return;
-        }
-
-        parent::_connect();
-
-        if (!isset($this->_params['hidden_accounts'])) {
-            $this->_params['hidden_accounts'] = array('cyrus');
-        }
-
-        // Reset the $_connected flag; we haven't yet successfully
-        // opened everything.
-        $this->_connected = false;
-
-        $imap_config = array(
-            'hostspec' => empty($this->_params['hostspec']) ? null : $this->_params['hostspec'],
-            'password' => $this->_params['cyrpass'],
-            'port' => empty($this->_params['port']) ? null : $this->_params['port'],
-            'secure' => ($this->_params['secure'] == 'none') ? null : $this->_params['secure'],
-            'username' => $this->_params['cyradmin']
-        );
-
         try {
-            $this->_ob = Horde_Imap_Client::factory('Socket', $imap_config);
-            $this->_ob->login();
-        } catch (Horde_Imap_Client_Exception $e) {
+            $this->_db->update($query, $values);
+        } catch (Horde_Db_Exception $e) {
             throw new Horde_Auth_Exception($e);
         }
-
-        $this->_connected = true;
     }
 
 }
index 37195bd..f824305 100644 (file)
@@ -4,66 +4,9 @@
  * administrating a Cyrus mail server authentications against another backend
  * that Horde can update (eg SQL or LDAP).
  *
- * Required parameters:
- * <pre>
- * 'backend'    The complete hash for the Auth_* driver that cyrus
- *              authenticates against (eg SQL, LDAP).
- * 'cyradmin'   The username of the cyrus administrator
- * 'cyrpass'    The password for the cyrus administrator
- * 'hostspec'        The hostname or IP address of the server.
- *                   DEFAULT: 'localhost'
- * 'port'            The server port to which we will connect.
- *                   IMAP is generally 143, while IMAP-SSL is generally 993.
- *                   DEFAULT: Encryption port default
- * 'secure'          The encryption to use.  Either 'none', 'ssl', or 'tls'.
- *                   DEFAULT: 'none'
- * </pre>
- *
  * Optional values:
  * <pre>
- * 'folders'    An array of folders to create under username.
- *              Doesn't create subfolders by default.
- * 'quota'      The quota (in kilobytes) to grant on the mailbox.
- *              Does not establish quota by default.
- * 'separator'  Hierarchy separator to use (e.g., is it user/mailbox or
- *              user.mailbox)
- * 'unixhier'   The value of imapd.conf's unixhierarchysep setting.
- *              Set this to 'true' if the value is true in imapd.conf
- * </pre>
  *
- * Example Usage:
- * <pre>
- * $conf['auth']['driver'] = 'composite';
- * $conf['auth']['params']['admin_driver'] = 'cyrus';
- * $conf['auth']['params']['drivers']['imp'] = array(
- *     'driver' => 'application',
- *     'params' => array('app' => 'imp')
- * );
- * $conf['auth']['params']['drivers']['cyrus'] = array(
- *    'driver' => 'cyrus',
- *    'params' => array(
- *        'cyradmin' => 'cyrus',
- *        'cyrpass' => 'password',
- *        'hostspec' => 'imap.example.com',
- *        'secure' => 'none'
- *        'separator' => '.'
- *    )
- * );
- * $conf['auth']['params']['drivers']['cyrus']['params']['backend'] = array(
- *     'driver' => 'sql',
- *     'params' => array(
- *         'phptype' => 'mysql',
- *         'hostspec' => 'database.example.com',
- *         'protocol' => 'tcp',
- *         'username' => 'username',
- *         'password' => 'password',
- *         'database' => 'mail',
- *         'table' => 'accountuser',
- *         'encryption' => 'md5-hex',
- *         'username_field' => 'username',
- *         'password_field' => 'password'
- *     )
- * );
  * </pre>
  *
  * Copyright 2002-2010 The Horde Project (http://www.horde.org/)
  * See the enclosed file COPYING for license information (LGPL). If you did
  * not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
  *
- * @author  Ilya Krel <mail@krel.org>
- * @author  Mike Cochrane <mike@graftonhall.co.nz>
- * @package Horde_Auth
+ * @author   Ilya Krel <mail@krel.org>
+ * @author   Mike Cochrane <mike@graftonhall.co.nz>
+ * @category Horde
+ * @license  http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package  Auth
  */
 class Horde_Auth_Cyrus extends Horde_Auth_Base
 {
@@ -82,7 +27,7 @@ class Horde_Auth_Cyrus extends Horde_Auth_Base
      *
      * @var Horde_Imap_Client_Base
      */
-    protected $_ob;
+    protected $_imap;
 
     /**
      * Pointer to another backend that Cyrus authenticates against.
@@ -106,31 +51,55 @@ class Horde_Auth_Cyrus extends Horde_Auth_Base
     /**
      * Constructor.
      *
-     * @param array $params  A hash containing connection parameters.
-     *
-     * @throws Horde_Exception
+     * @param array $params  Parameters:
+     * <pre>
+     * TODO
+     * 'backend' - (Horde_Auth_Base) [REQUIRED] The backend object.
+     * 'folders' - (array) An array of folders to create under username.
+     *             DEFAULT: NONE
+     * 'imap' - (Horde_Imap_Client_Base) [REQUIRED] An IMAP client object.
+     * 'quota' - (integer) The quota (in kilobytes) to grant on the mailbox.
+     *           DEFAULT: NONE
+     * 'separator' - (string) Hierarchy separator to use (e.g., is it
+     *               user/mailbox or user.mailbox)
+     *               DEFAULT: '.'
+     * 'unixhier' - (boolean) The value of imapd.conf's unixhierarchysep
+     *              setting. Set this to true if the value is true in
+     *              imapd.conf.
+     *              DEFAULT: false
+     * </pre>
+     *
+     * @throws InvalidArgumentException
+     * @throws Horde_Auth_Exception
      */
-    public function __construct($params = array())
+    public function __construct(array $params = array())
     {
-        parent::__construct($params);
-
-        if (!isset($this->_params['separator'])) {
-            $this->_params['separator'] = '.';
+        foreach (array('backend', 'imap') as $val) {
+            if (!isset($params[$val])) {
+                throw new InvalidArgumentException('Missing ' . $val . ' parameter.');
+            }
         }
 
+        $this->_backend = $params['backend'];
+        $this->_ob = $params['imap'];
+        unset($params['backend']);
+
+        $params = array_merge(array(
+            'separator' => '.',
+        ), $params);
+
+        parent::__construct($params);
+
         if (isset($this->_params['unixhier']) &&
             $this->_params['unixhier'] == true) {
             $this->_params['separator'] = '/';
         }
 
-        // Create backend instance.
-        $this->_backend = Horde_Auth::singleton($this->_params['backend']['driver'], $this->_params['backend']['params']);
-
         // Check the capabilities of the backend.
         if (!$this->_backend->hasCapability('add') ||
             !$this->_backend->hasCapability('update') ||
             !$this->_backend->hasCapability('remove')) {
-            throw new Horde_Exception('Horde_Auth_Cyrus: Backend does not have required capabilites.');
+            throw new Horde_Auth_Exception(__CLASS__ . ': Backend does not have required capabilites.');
         }
 
         $this->_capabilities['list'] = $this->_backend->hasCapability('list');
@@ -148,14 +117,12 @@ class Horde_Auth_Cyrus extends Horde_Auth_Base
      */
     public function addUser($userId, $credentials)
     {
-        $this->_connect();
-
         $this->_backend->addUser($userId, $credentials);
 
         $mailbox = Horde_String::convertCharset('user' . $this->_params['separator'] . $userId, Horde_Nls::getCharset(), 'utf7-imap');
 
         try {
-            $this->_ob->createMailbox($mailbox);
+            $this->_imap->createMailbox($mailbox);
         } catch (Horde_Imap_Client_Exception $e) {
             throw new Horde_Auth_Exception($e);
         }
@@ -164,7 +131,7 @@ class Horde_Auth_Cyrus extends Horde_Auth_Base
             is_array($this->_params['folders'])) {
             foreach ($this->_params['folders'] as $folder) {
                 try {
-                    $this->_ob->createMailbox($mailbox . Horde_String::convertCharset($this->_params['separator'] . $folder, Horde_Nls::getCharset(), 'utf7-imap'));
+                    $this->_imap->createMailbox($mailbox . Horde_String::convertCharset($this->_params['separator'] . $folder, Horde_Nls::getCharset(), 'utf7-imap'));
                 } catch (Horde_Imap_Client_Exception $e) {}
             }
         }
@@ -172,7 +139,7 @@ class Horde_Auth_Cyrus extends Horde_Auth_Base
         if (isset($this->_params['quota']) &&
             ($this->_params['quota'] >= 0)) {
             try {
-                $this->_ob->setQuota($mailbox, array('storage' => $this->_params['quota']));
+                $this->_imap->setQuota($mailbox, array('storage' => $this->_params['quota']));
             } catch (Horde_Imap_Client_Exception $e) {
                 throw new Horde_Auth_Exception($e);
             }
@@ -188,8 +155,6 @@ class Horde_Auth_Cyrus extends Horde_Auth_Base
      */
     public function removeUser($userId)
     {
-        $this->_connect();
-
         $this->_backend->removeUser($userId);
 
         $mailbox = Horde_String::convertCharset('user' . $this->_params['separator'] . $userId, Horde_Nls::getCharset(), 'utf7-imap');
@@ -198,8 +163,8 @@ class Horde_Auth_Cyrus extends Horde_Auth_Base
         list($admin) = explode('@', $this->_params['cyradmin']);
 
         try {
-            $this->_ob->setACL($mailbox, $admin, array('rights' => 'lrswipcda'));
-            $this->_ob->deleteMailbox($mailbox);
+            $this->_imap->setACL($mailbox, $admin, array('rights' => 'lrswipcda'));
+            $this->_imap->deleteMailbox($mailbox);
         } catch (Horde_Imap_Client_Exception $e) {
             throw new Horde_Auth_Exception($e);
         }
@@ -208,33 +173,6 @@ class Horde_Auth_Cyrus extends Horde_Auth_Base
     }
 
     /**
-     * Attempts to open connections to the IMAP servers.
-     *
-     * @throws Horde_Auth_Exception
-     */
-    protected function _connect()
-    {
-        if ($this->_ob) {
-            return;
-        }
-
-        $imap_config = array(
-            'hostspec' => empty($this->_params['hostspec']) ? null : $this->_params['hostspec'],
-            'password' => $pass,
-            'port' => empty($this->_params['port']) ? null : $this->_params['port'],
-            'secure' => ($this->_params['secure'] == 'none') ? null : $this->_params['secure'],
-            'username' => $user
-        );
-
-        try {
-            $this->_ob = Horde_Imap_Client::factory('Socket', $imap_config);
-            $this->_ob->login();
-        } catch (Horde_Imap_Client_Exception $e) {
-            throw new Horde_Auth_Exception($e);
-        }
-    }
-
-    /**
      * List all users in the system.
      *
      * @return array  The array of userIds.
@@ -283,7 +221,7 @@ class Horde_Auth_Cyrus extends Horde_Auth_Base
      */
     protected function _authenticate($userId, $credentials)
     {
-        throw new Horde_Auth_Exception('Not implemented!');
+        throw new Horde_Auth_Exception('Unsupported.');
     }
 
     /**
index cc210d5..1de433e 100644 (file)
@@ -1,15 +1,17 @@
 <?php
 /**
- * Authentication exceptions.
+ * Exceptions class for the horde/Auth package.
  *
- * Copyright 1999-2010 The Horde Project (http://www.horde.org/)
+ * Copyright 2010 The Horde Project (http://www.horde.org/)
  *
  * See the enclosed file COPYING for license information (LGPL). If you did
  * not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
  *
- * @author  Chuck Hagenbuch <chuck@horde.org>
- * @author  Michael Slusarz <slusarz@horde.org>
- * @package Horde_Auth
+ * @author   Chuck Hagenbuch <chuck@horde.org>
+ * @author   Michael Slusarz <slusarz@horde.org>
+ * @category Horde
+ * @license  http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package  Auth
  */
 class Horde_Auth_Exception extends Horde_Exception_Prior
 {
index 95ad654..8603b22 100644 (file)
@@ -3,36 +3,36 @@
  * The Horde_Auth_Ftp class provides an FTP implementation of the Horde
  * authentication system.
  *
- * Optional parameters:
- * <pre>
- * 'hostspec' - (string) The hostname or IP address of the FTP server.
- *              DEFAULT: 'localhost'
- * 'port' - (integer) The server port to connect to.
- *          DEFAULT: 21
- * </pre>
- *
  * Copyright 1999-2010 The Horde Project (http://www.horde.org/)
  *
  * See the enclosed file COPYING for license information (LGPL). If you did
  * not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
  *
- * @author  Chuck Hagenbuch <chuck@horde.org>
- * @author  Max Kalika <max@horde.org>
- * @package Horde_Auth
+ * @author   Chuck Hagenbuch <chuck@horde.org>
+ * @author   Max Kalika <max@horde.org>
+ * @category Horde
+ * @license  http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package  Auth
  */
 class Horde_Auth_Ftp extends Horde_Auth_Base
 {
     /**
      * Constructor.
      *
-     * @param array $params  A hash containing connection parameters.
+     * @param array $params  Optional parameters:
+     * <pre>
+     * 'hostspec' - (string) The hostname or IP address of the FTP server.
+     *              DEFAULT: 'localhost'
+     * 'port' - (integer) The server port to connect to.
+     *          DEFAULT: 21
+     * </pre>
      *
      * @throws Horde_Auth_Exception
      */
-    public function __construct($params = array())
+    public function __construct(array $params = array())
     {
         if (!Horde_Util::extensionExists('ftp')) {
-            throw new Horde_Auth_Exception('Horde_Auth_Ftp: Required FTP extension not found. Compile PHP with the --enable-ftp switch.');
+            throw new Horde_Auth_Exception(__CLASS__ ': Required FTP extension not found. Compile PHP with the --enable-ftp switch.');
         }
 
         $params = array_merge(array(
index 8f25e6d..128e03c 100644 (file)
@@ -3,19 +3,15 @@
  * The Horde_Auth_Http class transparently logs users in to Horde using
  * already present HTTP authentication headers.
  *
- * The 'encryption' parameter specifies what kind of passwords are in
- * the .htpasswd file. The supported options are 'crypt-des' (standard
- * crypted htpasswd entries) and 'aprmd5'. This information is used if
- * you want to directly authenticate users with this driver, instead
- * of relying on transparent auth.
- *
  * Copyright 1999-2010 The Horde Project (http://www.horde.org/)
  *
  * See the enclosed file COPYING for license information (LGPL). If you did
  * not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
  *
- * @author  Chuck Hagenbuch <chuck@horde.org>
- * @package Horde_Auth
+ * @author   Chuck Hagenbuch <chuck@horde.org>
+ * @category Horde
+ * @license  http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package  Auth
  */
 class Horde_Auth_Http extends Horde_Auth_Base
 {
@@ -39,16 +35,23 @@ class Horde_Auth_Http extends Horde_Auth_Base
     /**
      * Constructor.
      *
-     * @param array $params  A hash containing parameters.
+     * @param array $params  Optional parameters:
+     * <pre>
+     * 'encryption' - (string) Kind of passwords in the .htpasswd file.
+     *                Either 'crypt-des' (standard crypted htpasswd entries)
+     *                [DEFAULT] or 'aprmd5'. This information is used if
+     *                you want to directly authenticate users with this
+     *                driver, instead of relying on transparent auth.
+     * 'htpasswd_file' - (string) TODO
+     * </pre>
      */
-    public function __construct($params = array())
+    public function __construct(array $params = array())
     {
-        parent::__construct($params);
+        $params = array_merge(array(
+            'encryption' => 'crypt-des'
+        ), $params);
 
-        // Default to DES passwords.
-        if (empty($this->_params['encryption'])) {
-            $this->_params['encryption'] = 'crypt-des';
-        }
+        parent::__construct($params);
 
         if (!empty($this->_params['htpasswd_file'])) {
             $users = file($this->_params['htpasswd_file']);
index 0ac5b62..795685d 100644 (file)
@@ -8,12 +8,38 @@
  * See the enclosed file COPYING for license information (LGPL). If you did
  * not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
  *
- * @author  Duck <duck@obala.net>
- * @package Horde_Auth
+ * @author   Duck <duck@obala.net>
+ * @category Horde
+ * @license  http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package  Auth
  */
 class Horde_Auth_Http_Remote extends Horde_Auth_Base
 {
     /**
+     * Constructor.
+     *
+     * @param array $params  Configuration parameters:
+     * <pre>
+     * 'proxy' - (array) TODO
+     * 'url' - (string) [REQUIRED] TODO
+     * </pre>
+     *
+     * @throws InvalidArgumentException
+     */
+    public function __construct(array $params = array())
+    {
+        if (!isset($params['url'])) {
+            throw new InvalidArgumentException();
+        }
+
+        $params = array_merge(array(
+            'proxy' => array()
+        ), $params);
+
+        parent::__construct($params);
+    }
+
+    /**
      * Find out if a set of login credentials are valid.
      *
      * @param string $userId       The userId to check.
@@ -23,15 +49,11 @@ class Horde_Auth_Http_Remote extends Horde_Auth_Base
      */
     protected function _authenticate($userId, $credentials)
     {
-        $options = array(
+        $options = array_merge(array(
             'allowRedirects' => true,
             'method' => 'GET',
             'timeout' => 5
-        );
-
-        if (!empty($GLOBALS['conf']['http']['proxy']['proxy_host'])) {
-            $options = array_merge($options, $GLOBALS['conf']['http']['proxy']);
-        }
+        ), $this->_params['proxy']);
 
         $request = new HTTP_Request($this->_params['url'], $options);
         $request->setBasicAuth($userId, $credentials['password']);
index cb73c9b..cc82a0a 100644 (file)
@@ -3,61 +3,56 @@
  * The Horde_Auth_Imap:: class provides an IMAP implementation of the Horde
  * authentication system.
  *
- * Optional parameters:
- * <pre>
- * 'admin_password'  The password of the adminstrator.
- *                   DEFAULT: null
- * 'admin_user'      The name of a user with admin privileges.
- *                   DEFAULT: null
- * 'hostspec'        The hostname or IP address of the server.
- *                   DEFAULT: 'localhost'
- * 'port'            The server port to which we will connect.
- *                   IMAP is generally 143, while IMAP-SSL is generally 993.
- *                   DEFAULT: Encryption port default
- * 'secure'          The encryption to use.  Either 'none', 'ssl', or 'tls'.
- *                   DEFAULT: 'none'
- * 'userhierarchy'   The hierarchy where user mailboxes are stored.
- *                   DEFAULT: 'user.'
- * </pre>
- *
- * If setting up as Horde auth handler in conf.php, this is a sample entry:
- * <pre>
- * $conf['auth']['params']['hostspec'] = 'imap.example.com';
- * $conf['auth']['params']['port'] = 143;
- * $conf['auth']['params']['secure'] = 'none';
- * </pre>
- *
  * Copyright 1999-2010 The Horde Project (http://www.horde.org/)
  *
  * See the enclosed file COPYING for license information (LGPL). If you did
  * not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
  *
- * @author  Chuck Hagenbuch <chuck@horde.org>
- * @author  Gaudenz Steinlin <gaudenz@soziologie.ch>
- * @author  Jan Schneider <jan@horde.org>
- * @package Horde_Auth
+ * @author   Chuck Hagenbuch <chuck@horde.org>
+ * @author   Gaudenz Steinlin <gaudenz@soziologie.ch>
+ * @author   Jan Schneider <jan@horde.org>
+ * @category Horde
+ * @license  http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package  Auth
  */
 class Horde_Auth_Imap extends Horde_Auth_Base
 {
     /**
-     * Cached Horde_Imap_Client_Base object.
+     * Imap client objects.
      *
-     * @var Horde_Imap_Client_Base
+     * @var array()
      */
-    protected $_ob;
+    protected $_imap = array();
 
     /**
      * Constructor.
      *
-     * @param array $params  A hash containing connection parameters.
+     * @param array $params  Optional parameters:
+     * <pre>
+     * 'admin_password' - (string) The password of the adminstrator.
+     *                    DEFAULT: null
+     * 'admin_user' - (string) The name of a user with admin privileges.
+     *                DEFAULT: null
+     * 'hostspec' - (string) The hostname or IP address of the server.
+     *              DEFAULT: 'localhost'
+     * 'port' - (integer) The server port to which we will connect.
+     *          IMAP is generally 143, while IMAP-SSL is generally 993.
+     *          DEFAULT: Encryption port default
+     * 'secure' - (string) The encryption to use.  Either 'none', 'ssl', or
+     *            'tls'.
+     *            DEFAULT: 'none'
+     * 'userhierarchy' - (string) The hierarchy where user mailboxes are
+     *                   stored.
+     *                   DEFAULT: 'user.'
+     * </pre>
      */
-    public function __construct($params = array())
+    public function __construct(array $params = array())
     {
         $params = array_merge(array(
             'admin_password' => null,
             'admin_user' => null,
             'hostspec' => '',
-            'port' => '',
+            'port' => null,
             'secure' => 'none',
             'userhierarchy' => 'user.'
         ), $params);
@@ -65,9 +60,11 @@ class Horde_Auth_Imap extends Horde_Auth_Base
         parent::__construct($params);
 
         if (!empty($this->_params['admin_user'])) {
-            $this->_capabilities['add'] = true;
-            $this->_capabilities['remove'] = true;
-            $this->_capabilities['list'] = true;
+            $this->_capabilities = array_merge($this->_capabilities, array(
+                'add' => true,
+                'list' => true,
+                'remove' => true
+            ));
         }
     }
 
@@ -153,12 +150,17 @@ class Horde_Auth_Imap extends Horde_Auth_Base
     /**
      * Get Horde_Imap_Client object.
      *
+     * @param string $user  Username.
+     * @param string $pass  Password.
+     *
      * @return Horde_Imap_Client_Base  IMAP client object.
      * @throws Horde_Exception
      */
     protected function _getOb($user, $pass)
     {
-        if (!$this->_ob) {
+        $sig = hash('md5', serialize(array($user, $pass)));
+
+        if (!isset($this->_ob[$sig])) {
             $imap_config = array(
                 'hostspec' => empty($this->_params['hostspec']) ? null : $this->_params['hostspec'],
                 'password' => $pass,
@@ -167,10 +169,10 @@ class Horde_Auth_Imap extends Horde_Auth_Base
                 'username' => $user
             );
 
-            $this->_ob = Horde_Imap_Client::factory('Socket', $imap_config);
+            $this->_ob[$sig] = Horde_Imap_Client::factory('Socket', $imap_config);
         }
 
-        return $this->_ob;
+        return $this->_ob[$sig];
     }
 
 }
index 344a0db..bd73e6b 100644 (file)
  * See the enclosed file COPYING for license information (LGPL). If you did
  * not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
  *
- * @author  Michael Rubinsky <mrubinsk@horde.org>
- * @package Horde_Auth
+ * @author   Michael Rubinsky <mrubinsk@horde.org>
+ * @category Horde
+ * @license  http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package  Auth
  */
-class Horde_Auth_imsp extends Horde_Auth_Base
+class Horde_Auth_Imsp extends Horde_Auth_Base
 {
     /**
      * Private authentication function.
index e312ccc..959e78b 100644 (file)
@@ -5,18 +5,15 @@
  * for times when you want a block of IPs to be able to access a site,
  * and that access is simply on/off - no preferences, etc.
  *
- * Optional Parameters:
- * <pre>
- * 'blocks' - (array) CIDR masks which are allowed access.
- * </pre>
- *
  * Copyright 1999-2010 The Horde Project (http://www.horde.org/)
  *
  * See the enclosed file COPYING for license information (LGPL). If you did
  * not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
  *
- * @author  Chuck Hagenbuch <chuck@horde.org>
- * @package Horde_Auth
+ * @author   Chuck Hagenbuch <chuck@horde.org>
+ * @category Horde
+ * @license  http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package  Auth
  */
 class Horde_Auth_Ipbasic extends Horde_Auth_Base
 {
@@ -33,9 +30,12 @@ class Horde_Auth_Ipbasic extends Horde_Auth_Base
     /**
      * Constructor.
      *
-     * @param array $params  A hash containing parameters.
+     * @param array $params  Optional Parameters:
+     * <pre>
+     * 'blocks' - (array) CIDR masks which are allowed access.
+     * </pre>
      */
-    public function __construct($params = array())
+    public function __construct(array $params = array())
     {
         if (empty($params['blocks'])) {
             $params['blocks'] = array();
@@ -54,14 +54,12 @@ class Horde_Auth_Ipbasic extends Horde_Auth_Base
      */
     protected function _transparent()
     {
-        if (!isset($_SERVER['REMOTE_ADDR'])) {
-            return false;
-        }
-
-        foreach ($this->_params['blocks'] as $cidr) {
-            if ($this->_addressWithinCIDR($_SERVER['REMOTE_ADDR'], $cidr)) {
-                $this->_credentials['userId'] = $cidr;
-                return true;
+        if (isset($_SERVER['REMOTE_ADDR'])) {
+            foreach ($this->_params['blocks'] as $cidr) {
+                if ($this->_addressWithinCIDR($_SERVER['REMOTE_ADDR'], $cidr)) {
+                    $this->_credentials['userId'] = $cidr;
+                    return true;
+                }
             }
         }
 
@@ -82,7 +80,7 @@ class Horde_Auth_Ipbasic extends Horde_Auth_Base
      */
     protected function _authenticate($userId, $credentials)
     {
-        throw new Horde_Auth_Exception('Not implemented!');
+        throw new Horde_Auth_Exception('Unsupported.');
     }
 
     /**
index 5060290..bdaae04 100644 (file)
  * See the enclosed file COPYING for license information (LGPL). If you did
  * not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
  *
- * @author  Stuart Binge <s.binge@codefusion.co.za>
- * @author  Gunnar Wrobel <wrobel@pardus.de>
- * @package Horde_Auth
+ * @author   Stuart Binge <s.binge@codefusion.co.za>
+ * @author   Gunnar Wrobel <wrobel@pardus.de>
+ * @category Horde
+ * @package  Auth
  */
 class Horde_Auth_Kolab extends Horde_Auth_Base
 {
@@ -23,15 +24,29 @@ class Horde_Auth_Kolab extends Horde_Auth_Base
      * @var array
      */
     protected $_capabilities = array(
-        'authenticate'  => true,
-        'list'          => true,
-        /** @todo These would only work if we allow manager login */
-        'add'           => false,
-        'remove'        => false,
-        'update'        => false
+        'authenticate'  => true
     );
 
     /**
+     * Constructor.
+     *
+     * @params array $params  Parameters:
+     * <pre>
+     * 'kolab' - (Horde_Kolab_Session) [REQUIRED] TODO
+     * </pre>
+     *
+     * @throws InvalidArgumentException
+     */
+    public function __construct(array $params = array())
+    {
+        if (!isset($params['kolab'])) {
+            throw new InvalidArgumentException('Missing ' . $params . ' parameter.');
+        }
+
+        parent::__construct($params);
+    }
+
+    /**
      * Find out if a set of login credentials are valid.
      *
      * For Kolab this requires to identify the IMAP server the user should
@@ -48,129 +63,19 @@ class Horde_Auth_Kolab extends Horde_Auth_Base
     protected function _authenticate($userId, $credentials)
     {
         try {
-            $session = $GLOBALS['injector']->getInstance('Horde_Kolab_Session');
-            $session->connect($userId, $credentials);
+            $this->_params['kolab']->connect($userId, $credentials);
         } catch (Horde_Kolab_Session_Exception_Badlogin $e) {
             throw new Horde_Auth_Exception('', Horde_Auth::REASON_BADLOGIN);
         } catch (Horde_Kolab_Session_Exception $e) {
-            Horde::logMessage($e, 'ERR');
+            if ($this->_logger) {
+                $this->_logger->log($e, 'ERR');
+            }
             throw new Horde_Auth_Exception('', Horde_Auth::REASON_FAILED);
         }
 
-        $this->_credentials['userId'] = $session->getMail();
+        $this->_credentials['userId'] = $this->_params['kolab']->getMail();
 
         return true;
-
-/*         if (!isset($conf['auth']['params']) || */
-/*             $conf['auth']['params']['login_block'] != 1) { */
-/*             // Return if feature is disabled. */
-/*             return $session->auth; */
-/*         } */
-
-/*         if ($session->auth !== true && */
-/*             class_exists('Horde_History')) { */
-/*             $history = $GLOBALS['injector']->getInstance('Horde_History'); */
-
-/*             $history_identifier = "$userId@logins.kolab"; */
-/*             $history_log = $history->getHistory($history_identifier); */
-/*             $history_list = array(); */
-
-/*             // Extract history list from log. */
-/*             if ($history_log && !($history_log instanceof PEAR_Error)) { */
-/*                 $data = $history_log->getData(); */
-/*                 if (!empty($data)) { */
-/*                     $entry = array_shift($data); */
-/*                     $history_list = $entry['history_list']; */
-/*                 } */
-/*             } */
-
-/*             // Calculate the time range. */
-/*             $start_time = (time() - $conf['auth']['params']['login_block_time'] * 60); */
-
-/*             $new_history_list = array(); */
-/*             $count = 0; */
-
-/*             // Copy and count all relevant timestamps. */
-/*             foreach ($history_list as $entry) { */
-/*                 $timestamp = $entry[ 'timestamp' ]; */
-
-/*                 if ($timestamp > $start_time) { */
-/*                     $new_history_list[] = $entry; */
-/*                     $count++; */
-/*                 } */
-/*             } */
-
-/*             $max_count = $conf['auth']['params']['login_block_count']; */
-
-/*             if ($count > $max_count) { */
-/*                 // Add entry for current failed login. */
-/*                 $entry = array(); */
-/*                 $entry[ 'timestamp' ] = time(); */
-/*                 $new_history_list[] = $entry; */
-
-/*                 // Write back history. */
-/*                 $history->log($history_identifier, */
-/*                               array('action' => 'add', 'who' => $userId, */
-/*                                     'history_list' => $new_history_list), true); */
-
-/*                 if ($count > $max_count) { */
-/*                     throw new Horde_Auth_Exception(_("Too many invalid logins during the last minutes.")); */
-/*                 } */
-
-/*                 throw new Horde_Auth_Exception('', Horde_Auth::REASON_BADLOGIN); */
-/*             } */
-/*         } */
-
-/*         return ($session->auth === true); */
     }
 
-/*     /\** */
-/*      * List Users */
-/*      * */
-/*      * @return array  List of Users */
-/*      * @throws Horde_Auth_Exception */
-/*      *\/ */
-/*     public function listUsers() */
-/*     { */
-/*         $session = Horde_Kolab_Session_Singleton::singleton(); */
-/*         $server = $session->getServer(); */
-/*         if ($server instanceof PEAR_Error) { */
-/*             return $server; */
-/*         } */
-/*         $users = $server->listObjects(KOLAB_OBJECT_USER); */
-/*         $mails = array(); */
-/*         foreach ($users as $user) { */
-/*             $mails[] = $user->get(KOLAB_ATTR_MAIL); */
-/*         } */
-
-/*         return $mails; */
-/*     } */
-
-/*     /\** */
-/*      * Add a set of authentication credentials. */
-/*      * */
-/*      * @param string $userId      The userId to add. */
-/*      * @param array $credentials  The credentials to be set. */
-/*      * */
-/*      * @throws Horde_Auth_Exception */
-/*      *\/ */
-/*     public function addUser($userId, $credentials) */
-/*     { */
-/*         $session = Horde_Kolab_Session::singleton(); */
-/*         $server = $session->getServer(); */
-/*         if ($server instanceof PEAR_Error) { */
-/*             return $server; */
-/*         } */
-
-/*         $result = $server->store(KOLAB_OBJECT_USER, $userId, $credentials); */
-
-/*         if (is_a($result, KOLAB_OBJECT_USER)) { */
-/*             return true; */
-/*         } else if ($result instanceof PEAR_Error) { */
-/*             return $result; */
-/*         } */
-
-/*         throw new Horde_Auth_Exception(sprintf('The new Kolab object is a %s rather than a ' . KOLAB_OBJECT_USER, get_class($result))); */
-/*     } */
-
 }
index 355e92f..6e11b96 100644 (file)
@@ -3,25 +3,6 @@
  * The Horde_Auth_Ldap class provides an LDAP implementation of the Horde
  * authentication system.
  *
- * Required parameters:
- * <pre>
- * 'basedn'       The base DN for the LDAP server.
- * 'hostspec'     The hostname of the LDAP server.
- * 'uid'          The username search key.
- * 'filter'       The LDAP formatted search filter to search for users. This
- *                setting overrides the 'objectclass' method below.
- * 'objectclass'  The objectclass filter used to search for users. Can be a
- *                single objectclass or an array.
- * </pre>
- *
- * Optional parameters:
- * <pre>
- * 'binddn'       The DN used to bind to the LDAP server
- * 'password'     The password used to bind to the LDAP server
- * 'version'      The version of the LDAP protocol to use.
- *                DEFAULT: NONE (system default will be used)
- * </pre>
- *
  * 'preauthenticate' hook should return LDAP connection information in the
  * 'ldap' credentials key.
  *
  * See the enclosed file COPYING for license information (LGPL). If you did
  * not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
  *
- * @author  Jon Parise <jon@horde.org>
- * @package Horde_Auth
+ * @author   Jon Parise <jon@horde.org>
+ * @category Horde
+ * @license  http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package  Auth
  */
 class Horde_Auth_Ldap extends Horde_Auth_Base
 {
@@ -50,95 +33,50 @@ class Horde_Auth_Ldap extends Horde_Auth_Base
     );
 
     /**
-     * LDAP connection handle.
+     * LDAP object
      *
-     * @var resource
+     * @var Horde_Ldap
      */
-    protected $_ds;
+    protected $_ldap;
 
     /**
-     * Construct.
+     * Constructor.
      *
-     * @param array $params  A hash containing connection parameters.
+     * @param array $params  Required parameters:
+     * <pre>
+     * 'basedn' - (string) The base DN for the LDAP server.
+     * 'filter' - (string) The LDAP formatted search filter to search for
+     *            users. This setting overrides the 'objectclass' method
+     *            below.
+     * 'ldap' - (Horde_Ldap) Horde LDAP object.
+     * 'objectclass' - (mixed) The objectclass filter used to search for
+     *                 users. Can be a single objectclass or an array.
+     * 'uid' - (string) The username search key.
+     * </pre>
      *
      * @throws Horde_Auth_Exception
+     * @throws InvalidArgumentException
      */
-    public function __construct($params = array())
+    public function __construct(array $params = array())
     {
-        if (!Horde_Util::extensionExists('ldap')) {
-            throw new Horde_Auth_Exception(_("Horde_Auth_Ldap: Required LDAP extension not found."));
-        }
-
-        /* Ensure we've been provided with all of the necessary parameters. */
-        Horde::assertDriverConfig($params, 'auth',
-                                  array('hostspec', 'basedn', 'uid'),
-                                  'authentication LDAP');
-
-        parent::__construct($params);
-    }
-
-    /**
-     * Does an ldap connect and binds as the guest user or as the optional dn.
-     *
-     * @throws Horde_Auth_Exception
-     */
-    protected function _connect()
-    {
-        /* Connect to the LDAP server. */
-        $this->_ds = @ldap_connect($this->_params['hostspec']);
-        if (!$this->_ds) {
-            throw new Horde_Auth_Exception(_("Failed to connect to LDAP server."));
-        }
-
-        if (isset($this->_params['version'])) {
-            if (!ldap_set_option($this->_ds, LDAP_OPT_PROTOCOL_VERSION,
-                                 $this->_params['version'])) {
-                Horde::logMessage(
-                    sprintf('Set LDAP protocol version to %d failed: [%d] %s',
-                            $this->_params['version'],
-                            @ldap_errno($this->_ds),
-                            @ldap_error($this->_ds)),
-                    'ERR');
-            }
-        }
-
-        /* Start TLS if we're using it. */
-        if (!empty($this->_params['tls'])) {
-            if (!@ldap_start_tls($this->_ds)) {
-                Horde::logMessage(
-                    sprintf('STARTTLS failed: [%d] %s',
-                            @ldap_errno($this->_ds),
-                            @ldap_error($this->_ds)),
-                    'ERR');
-            }
-        }
-
-        /* Work around Active Directory quirk. */
-        if (!empty($this->_params['ad'])) {
-            if (!ldap_set_option($this->_ds, LDAP_OPT_REFERRALS, false)) {
-                Horde::logMessage(
-                    sprintf('Unable to disable directory referrals on this connection to Active Directory: [%d] %s',
-                            @ldap_errno($this->_ds),
-                            @ldap_error($this->_ds)),
-                    'ERR');
+        foreach (array('basedn', 'filter', 'ldap', 'objectclass', 'uid') as $val) {
+            if (!isset($params[$val])) {
+                throw new InvalidArgumentException(__CLASS__ . ': Missing ' . $val . ' parameter.');
             }
         }
 
-        $bind = isset($this->_params['binddn'])
-            ? @ldap_bind($this->_ds, $this->_params['binddn'], $this->_params['password'])
-            : @ldap_bind($this->_ds);
+        $this->_ldap = $params['ldap'];
+        unset($params['ldap']);
 
-        if (!$bind) {
-            throw new Horde_Auth_Exception(_("Could not bind to LDAP server."));
-        }
+        parent::__construct($params);
     }
 
     /**
-     * Find the user dn
+     * Find the user dn.
      *
      * @param string $userId  The userId to find.
      *
-     * @return string  The users full DN
+     * @return string  The user's full DN
      * @throws Horde_Auth_Exception
      */
     protected function _findDN($userId)
@@ -148,25 +86,17 @@ class Horde_Auth_Ldap extends Horde_Auth_Base
         $filter = '(&(' . $this->_params['uid'] . '=' . $userId . ')' .
                   $filter . ')';
 
-        $func = ($this->_params['scope'] == 'one')
-            ? 'ldap_list'
-            : 'ldap_search';
-
-        $search = @$func($this->_ds, $this->_params['basedn'], $filter,
-                         array($this->_params['uid']));
-        if (!$search) {
-            Horde::logMessage(ldap_error($this->_ds), 'ERR');
-            throw new Horde_Auth_Exception(_("Could not search the LDAP server."));
+        try {
+            $search = $this->_ldap->search(null, $filter, array('attributes' => array($this->_params['uid'])));
+        } catch (Horde_Ldap_Exception $e) {
+            throw new Horde_Auth_Exception('Could not search the LDAP server.');
         }
 
-        $result = @ldap_get_entries($this->_ds, $search);
-        if (is_array($result) && (count($result) > 1)) {
-            $dn = $result[0]['dn'];
-        } else {
-            throw new Horde_Auth_Exception(_("Empty result."));
+        if (!$search->count()) {
+            throw new Horde_Auth_Exception('Empty result.');
         }
 
-        return $dn;
+        return $search[0]['dn'];
     }
 
     /**
@@ -197,64 +127,75 @@ class Horde_Auth_Ldap extends Horde_Auth_Base
          *    pwdlastset: Active Directory
          *    shadow*: shadowUser schema
          *    passwordexpirationtime: Sun and Fedora Directory Server */
-        $result = @ldap_read($this->_ds, $dn, '(objectClass=*)',
-                             array('pwdlastset', 'shadowmax', 'shadowmin',
-                                   'shadowlastchange', 'shadowwarning',
-                                   'passwordexpirationtime'));
-        if ($result) {
-            $information = @ldap_get_entries($this->_ds, $result);
-
-            if ($this->_params['ad']) {
-                if (isset($information[0]['pwdlastset'][0])) {
-                    /* Active Directory handles timestamps a bit differently.
-                     * Convert the timestamp to a UNIX timestamp. */
-                    $lookupshadow['shadowlastchange'] = floor((($information[0]['pwdlastset'][0] / 10000000) - 11644406783) / 86400) - 1;
-
-                    /* Password expiry attributes are in a policy. We cannot
-                     * read them so use the Horde config. */
-                    $lookupshadow['shadowwarning'] = $this->_params['warnage'];
-                    $lookupshadow['shadowmin'] = $this->_params['minage'];
-                    $lookupshadow['shadowmax'] = $this->_params['maxage'];
-                }
-            } elseif (isset($information[0]['passwordexpirationtime'][0])) {
-                /* Sun/Fedora Directory Server uses a special attribute
-                 * passwordexpirationtime.  It has precedence over shadow*
-                 * because it actually locks the expired password at the LDAP
-                 * server level.  The correct way to check expiration should
-                 * be using LDAP controls, unfortunately PHP doesn't support
-                 * controls on bind() responses. */
-                $ldaptimepattern = "/([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})Z/";
-                if (preg_match($ldaptimepattern, $information[0]['passwordexpirationtime'][0], $regs)) {
-                    /* Sun/Fedora Directory Server return expiration time, not
-                     * last change time. We emulate the behaviour taking it
-                     * back to maxage. */
-                    $lookupshadow['shadowlastchange'] = floor(mktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]) / 86400) - $this->_params['maxage'];
-
-                    /* Password expiry attributes are in not accessible policy
-                     * entry. */
-                    $lookupshadow['shadowwarning'] = $this->_params['warnage'];
-                    $lookupshadow['shadowmin']     = $this->_params['minage'];
-                    $lookupshadow['shadowmax']     = $this->_params['maxage'];
-                } else {
-                    Horde::logMessage('Wrong time format: ' . $information[0]['passwordexpirationtime'][0], 'ERR');
-                }
-            } else {
-                if (isset($information[0]['shadowmax'][0])) {
-                    $lookupshadow['shadowmax'] =
-                        $information[0]['shadowmax'][0];
-                }
-                if (isset($information[0]['shadowmin'][0])) {
-                    $lookupshadow['shadowmin'] =
-                        $information[0]['shadowmin'][0];
-                }
-                if (isset($information[0]['shadowlastchange'][0])) {
-                    $lookupshadow['shadowlastchange'] =
-                        $information[0]['shadowlastchange'][0];
-                }
-                if (isset($information[0]['shadowwarning'][0])) {
-                    $lookupshadow['shadowwarning'] =
-                        $information[0]['shadowwarning'][0];
-                }
+        try {
+            $result = $this->_ldap->search(null, '(objectClass=*)', array(
+                'attributes' => array(
+                    'pwdlastset',
+                    'shadowmax',
+                    'shadowmin',
+                    'shadowlastchange',
+                    'shadowwarning',
+                    'passwordexpirationtime'
+                ),
+                'scope' => 'base'
+            ));
+        } catch (Horde_Ldap_Exception $e) {
+            return $lookupshadow;
+        }
+
+        if (!$result) {
+            return $lookupshadow;
+        }
+
+        $info = reset($result);
+
+        // TODO: 'ad'?
+        if ($this->_params['ad']) {
+            if (isset($info['pwdlastset'][0])) {
+                /* Active Directory handles timestamps a bit differently.
+                 * Convert the timestamp to a UNIX timestamp. */
+                $lookupshadow['shadowlastchange'] = floor((($info['pwdlastset'][0] / 10000000) - 11644406783) / 86400) - 1;
+
+                /* Password expiry attributes are in a policy. We cannot
+                 * read them so use the Horde config. */
+                $lookupshadow['shadowwarning'] = $this->_params['warnage'];
+                $lookupshadow['shadowmin'] = $this->_params['minage'];
+                $lookupshadow['shadowmax'] = $this->_params['maxage'];
+            }
+        } elseif (isset($info['passwordexpirationtime'][0])) {
+            /* Sun/Fedora Directory Server uses a special attribute
+             * passwordexpirationtime.  It has precedence over shadow*
+             * because it actually locks the expired password at the LDAP
+             * server level.  The correct way to check expiration should
+             * be using LDAP controls, unfortunately PHP doesn't support
+             * controls on bind() responses. */
+            $ldaptimepattern = "/([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})Z/";
+            if (preg_match($ldaptimepattern, $info['passwordexpirationtime'][0], $regs)) {
+                /* Sun/Fedora Directory Server return expiration time, not
+                 * last change time. We emulate the behaviour taking it
+                 * back to maxage. */
+                $lookupshadow['shadowlastchange'] = floor(mktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]) / 86400) - $this->_params['maxage'];
+
+                /* Password expiry attributes are in not accessible policy
+                 * entry. */
+                $lookupshadow['shadowwarning'] = $this->_params['warnage'];
+                $lookupshadow['shadowmin']     = $this->_params['minage'];
+                $lookupshadow['shadowmax']     = $this->_params['maxage'];
+            } elseif ($this->_logger) {
+                $this->_logger->log('Wrong time format: ' . $info['passwordexpirationtime'][0], 'ERR');
+            }
+        } else {
+            if (isset($info['shadowmax'][0])) {
+                $lookupshadow['shadowmax'] = $info['shadowmax'][0];
+            }
+            if (isset($info['shadowmin'][0])) {
+                $lookupshadow['shadowmin'] = $info['shadowmin'][0];
+            }
+            if (isset($info['shadowlastchange'][0])) {
+                $lookupshadow['shadowlastchange'] = $info['shadowlastchange'][0];
+            }
+            if (isset($info['shadowwarning'][0])) {
+                $lookupshadow['shadowwarning'] = $info['shadowwarning'][0];
             }
         }
 
@@ -271,16 +212,16 @@ class Horde_Auth_Ldap extends Horde_Auth_Base
      */
     protected function _authenticate($userId, $credentials)
     {
-        /* Connect to the LDAP server. */
-        $this->_connect();
-
         /* Search for the user's full DN. */
         $dn = $this->_findDN($userId);
 
         /* Attempt to bind to the LDAP server as the user. */
-        $bind = @ldap_bind($this->_ds, $dn, $credentials['password']);
-        if ($bind == false) {
-            @ldap_close($this->_ds);
+        $bind = clone $this->_ldap;
+        try {
+            if (!$bind->bind($dn, $credentials['password'])) {
+                throw new Horde_Auth_Exception('', Horde_Auth::REASON_FAILED);
+            }
+        } catch (Horde_Ldap_Exception $e) {
             throw new Horde_Auth_Exception('', Horde_Auth::REASON_FAILED);
         }
 
@@ -289,13 +230,15 @@ class Horde_Auth_Ldap extends Horde_Auth_Base
             if ($shadow['shadowmax'] && $shadow['shadowlastchange'] &&
                 $shadow['shadowwarning']) {
                 $today = floor(time() / 86400);
-                $warnday = $shadow['shadowlastchange'] +
-                           $shadow['shadowmax'] - $shadow['shadowwarning'];
                 $toexpire = $shadow['shadowlastchange'] +
                             $shadow['shadowmax'] - $today;
 
-                if ($today >= $warnday) {
-                    $GLOBALS['notification']->push(sprintf(ngettext("%d day until your password expires.", "%d days until your password expires.", $toexpire), $toexpire), 'horde.warning');
+                if ($this->_params['notify_expire']) {
+                    $warnday = $shadow['shadowlastchange'] +
+                               $shadow['shadowmax'] - $shadow['shadowwarning'];
+                    if ($today >= $warnday) {
+                        call_user_func($this->_params['notify_expire'], $toexpire);
+                    }
                 }
 
                 if ($toexpire == 0) {
@@ -305,8 +248,6 @@ class Horde_Auth_Ldap extends Horde_Auth_Base
                 }
             }
         }
-
-        @ldap_close($this->_ds);
     }
 
     /**
@@ -320,12 +261,9 @@ class Horde_Auth_Ldap extends Horde_Auth_Base
     public function addUser($userId, $credentials)
     {
         if ($this->_params['ad']) {
-            throw new Horde_Auth_Exception(_("Horde_Auth_Ldap: Adding users is not supported for Active Directory"));
+            throw new Horde_Auth_Exception(__CLASS__ . ': Adding users is not supported for Active Directory.');
         }
 
-        /* Connect to the LDAP server. */
-        $this->_connect();
-
         list($userId, $credentials) = Horde_Auth::runHook($userId, $credentials, $this->_app, 'preauthenticate', 'admin');
         if (isset($credentials['ldap'])) {
             $entry = $credentials['ldap'];
@@ -356,13 +294,11 @@ class Horde_Auth_Ldap extends Horde_Auth_Base
             }
         }
 
-        $result = @ldap_add($this->_ds, $dn, $entry);
-
-        if (!$result) {
-           throw new Horde_Auth_Exception(sprintf(_("Horde_Auth_Ldap: Unable to add user \"%s\". This is what the server said: "), $userId) . @ldap_error($this->_ds));
+        try {
+            $this->_ldap->add(Horde_Ldap_Entry::createFresh($dn, $entry));
+        } catch (Horde_Ldap_Exception $e) {
+           throw new Horde_Auth_Exception(sprintf(__CLASS__ . ': Unable to add user "%s". This is what the server said: ', $userId) . $e->getMessage());
         }
-
-        @ldap_close($this->_ds);
     }
 
     /**
@@ -375,12 +311,9 @@ class Horde_Auth_Ldap extends Horde_Auth_Base
     public function removeUser($userId)
     {
         if ($this->_params['ad']) {
-           throw new Horde_Auth_Exception(_("Horde_Auth_Ldap: Removing users is not supported for Active Directory"));
+           throw new Horde_Auth_Exception(__CLASS__ . ': Removing users is not supported for Active Directory');
         }
 
-        /* Connect to the LDAP server. */
-        $this->_connect();
-
         list($userId, $credentials) = Horde_Auth::runHook($userId, array(), $this->_app, 'preauthenticate', 'admin');
         if (isset($credentials['ldap'])) {
             $dn = $credentials['ldap']['dn'];
@@ -389,13 +322,12 @@ class Horde_Auth_Ldap extends Horde_Auth_Base
             $dn = $this->_findDN($userId);
         }
 
-        $result = @ldap_delete($this->_ds, $dn);
-        if (!$result) {
-           throw new Horde_Auth_Exception(sprintf(_("Auth_ldap: Unable to remove user \"%s\""), $userId));
+        try {
+            $this->_ldap->delete($dn);
+        } catch (Horde_Ldap_Exception $e) {
+           throw new Horde_Auth_Exception(sprintf(__CLASS__ . ': Unable to remove user "%s"', $userId));
         }
 
-        @ldap_close($this->_ds);
-
         Horde_Auth::removeUserData($userId);
     }
 
@@ -411,12 +343,9 @@ class Horde_Auth_Ldap extends Horde_Auth_Base
     public function updateUser($oldID, $newID, $credentials)
     {
         if ($this->_params['ad']) {
-           throw new Horde_Auth_Exception(_("Horde_Auth_Ldap: Updating users is not supported for Active Directory."));
+           throw new Horde_Auth_Exception(__CLASS__ . ': Updating users is not supported for Active Directory.');
         }
 
-        /* Connect to the LDAP server. */
-        $this->_connect();
-
         list($oldID, $old_credentials) = Horde_Auth::runHook($oldID, $credentials, $this->_app, 'preauthenticate', 'admin');
         if (isset($old_credentials['ldap'])) {
             $olddn = $old_credentials['ldap']['dn'];
@@ -436,7 +365,7 @@ class Horde_Auth_Ldap extends Horde_Auth_Base
             if ($shadow['shadowlastchange'] &&
                 $shadow['shadowmin'] &&
                 ($shadow['shadowlastchange'] + $shadow['shadowmin'] > (time() / 86400))) {
-                throw new Horde_Auth_Exception(_("Minimum password age has not yet expired"));
+                throw new Horde_Auth_Exception('Minimum password age has not yet expired');
             }
 
             /* Set the lastchange field */
@@ -451,55 +380,16 @@ class Horde_Auth_Ldap extends Horde_Auth_Base
                 'true');
         }
 
-        if ($oldID != $newID) {
-            if (LDAP_OPT_PROTOCOL_VERSION == 3) {
-                ldap_rename($this->_ds, $olddn, $newdn,
-                            $this->_params['basedn'], true);
-
-                $result = ldap_modify($this->_ds, $newdn, $entry);
+        try {
+            if ($oldID != $newID) {
+                $this->_ldap->move($olddn, $newdn);
+                $this->_ldap->modify($newdn, $entry);
             } else {
-                /* Get the complete old record first */
-                $result = @ldap_read($this->_ds, $olddn, 'objectClass=*');
-
-                if ($result) {
-                    $information = @ldap_get_entries($this->_ds, $result);
-
-                    /* Remove the count elements from the array */
-                    $counter = 0;
-                    $newrecord = array();
-                    while (isset($information[0][$counter])) {
-                        if ($information[0][$information[0][$counter]]['count'] == 1) {
-                            $newrecord[$information[0][$counter]] = $information[0][$information[0][$counter]][0];
-                        } else {
-                            $newrecord[$information[0][$counter]] = $information[0][$information[0][$counter]];
-                            unset($newrecord[$information[0][$counter]]['count']);
-                        }
-                        $counter++;
-                    }
-
-                    /* Adjust the changed parameters */
-                    unset($newrecord['dn']);
-                    $newrecord[$this->_params['uid']] = $newID;
-                    $newrecord['userpassword'] = $entry['userpassword'];
-                    if (isset($entry['shadowlastchange'])) {
-                        $newrecord['shadowlastchange'] = $entry['shadowlastchange'];
-                    }
-
-                    $result = ldap_add($this->_ds, $newdn, $newrecord);
-                    if ($result) {
-                        $result = @ldap_delete($this->_ds, $olddn);
-                    }
-                }
+                $this->_ldap->modify($olddn, $entry);
             }
-        } else {
-            $result = @ldap_modify($this->_ds, $olddn, $entry);
+        } catch (Horde_Ldap_Exception $e) {
+            throw new Horde_Auth_Exception(sprintf(__CLASS__ . ': Unable to update user "%s"', $newID));
         }
-
-        if (!$result) {
-            throw new Horde_Auth_Exception(sprintf(_("Horde_Auth_Ldap: Unable to update user \"%s\""), $newID));
-        }
-
-        @ldap_close($this->_ds);
     }
 
     /**
@@ -510,27 +400,25 @@ class Horde_Auth_Ldap extends Horde_Auth_Base
      */
     public function listUsers()
     {
-        /* Connect to the LDAP server. */
-        $this->_connect();
-
         $filter = $this->_getParamFilter();
 
-        $func = ($this->_params['scope'] == 'one')
-            ? 'ldap_list'
-            : 'ldap_search';
+        $params = array(
+            'attributes' => array($this->_params['uid']),
+            'scope' => $this->_params['scope'],
+            'sizelimit' => isset($this->_params['sizelimit']) ? $this->_params['sizelimit'] : 0
+        );
 
         /* Add a sizelimit, if specified. Default is 0, which means no limit.
          * Note: You cannot override a server-side limit with this. */
-        $sizelimit = isset($this->_params['sizelimit']) ? $this->_params['sizelimit'] : 0;
-        $search = @$func($this->_ds, $this->_params['basedn'], $filter,
-                         array($this->_params['uid']), 0, $sizelimit);
-
-        $entries = @ldap_get_entries($this->_ds, $search);
         $userlist = array();
-        $uid = Horde_String::lower($this->_params['uid']);
-        for ($i = 0; $i < $entries['count']; $i++) {
-            $userlist[$i] = $entries[$i][$uid][0];
-        }
+        try {
+            $search = $this->_ldap->search($this->_params['basedn'], $filter, $params);
+
+            $uid = Horde_String::lower($this->_params['uid']);
+            foreach ($search as $val) {
+                $userlist[] = $val[$uid][0];
+            }
+        } catch (Horde_Ldap_Exception $e) {}
 
         return $userlist;
     }
@@ -560,4 +448,5 @@ class Horde_Auth_Ldap extends Horde_Auth_Base
         }
         return $filter;
     }
+
 }
index 43d5d9a..6e85e97 100644 (file)
@@ -2,22 +2,19 @@
 /**
  * The Horde_Auth_login:: class provides a system login implementation of
  * the Horde authentication system.
+ *
  * This Auth driver is useful if you have a shadow password system
  * where the Horde_Auth_Passwd driver doesn't work.
  *
- * Optional parameters:
- * <pre>
- * 'location' - (string) Location of the su binary.
- *              DEFAULT: /bin/su
- * </pre>
- *
  * Copyright 2004-2010 The Horde Project (http://www.horde.org/)
  *
  * See the enclosed file COPYING for license information (LGPL). If you did
  * not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
  *
- * @author  Jan Schneider <jan@horde.org>
- * @package Horde_Auth
+ * @author   Jan Schneider <jan@horde.org>
+ * @category Horde
+ * @license  http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package  Auth
  */
 class Horde_Auth_Login extends Horde_Auth_Base
 {
@@ -37,9 +34,13 @@ class Horde_Auth_Login extends Horde_Auth_Base
     /**
      * Constructs a new Login authentication object.
      *
-     * @param array $params  A hash containing connection parameters.
+     * @param array $params  Optional parameters:
+     * <pre>
+     * 'location' - (string) Location of the su binary.
+     *              DEFAULT: /bin/su
+     * </pre>
      */
-    public function __construct($params = array())
+    public function __construct(array $params = array())
     {
         if (empty($params['location'])) {
             $params['location'] = '/bin/su';
index 3aebdd9..6ba696a 100644 (file)
@@ -3,17 +3,15 @@
  * The Horde_Auth_Msad class provides an experimental MSAD extension of the
  * LDAP implementation of the Horde authentication system.
  *
- * Required parameters: See Horde_Auth_Ldap.
- *
- * Optional parameters: See Horde_Auth_Ldap.
- *
  * Copyright 2007-2010 The Horde Project (http://www.horde.org/)
  *
  * See the enclosed file COPYING for license information (LGPL). If you did
  * not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
  *
- * @author  Francois Helly <fhelly@bebop-design.net>
- * @package Horde_Auth
+ * @author   Francois Helly <fhelly@bebop-design.net>
+ * @category Horde
+ * @license  http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package  Auth
  */
 class Horde_Auth_Msad extends Horde_Auth_Ldap
 {
@@ -26,10 +24,6 @@ class Horde_Auth_Msad extends Horde_Auth_Ldap
      */
     public function __construct($params = array())
     {
-        if (!Horde_Util::extensionExists('ldap')) {
-            throw new Horde_Auth_Exception(_("Horde_Auth_Ldap: Required LDAP extension not found."));
-        }
-
         $params = array_merge(array(
             'adduser' => true,
             'authId' => 'initials',
@@ -46,10 +40,9 @@ class Horde_Auth_Msad extends Horde_Auth_Ldap
         }
 
         /* Ensure we've been provided with all of the necessary parameters. */
-        Horde::assertDriverConfig($params, 'auth',
-            array('hostspec', 'basedn'), 'authentication MSAD');
+        //Horde::assertDriverConfig($params, 'auth',
+        //    array('hostspec', 'basedn'), 'authentication MSAD');
 
-        $this->_params = $params;
         /* Adjust capabilities: depending on if SSL encryption is
          * enabled or not */
         $this->_capabilities = array(
@@ -114,7 +107,7 @@ class Horde_Auth_Msad extends Horde_Auth_Ldap
         $success = @ldap_add($this->_ds, $dn, $entry);
 
         if (!$success) {
-           throw new Horde_Auth_Exception(sprintf(_("Horde_Auth_Msad: Unable to add user \"%s\". This is what the server said: "), $accountName) . ldap_error($this->_ds));
+           throw new Horde_Auth_Exception(sprintf(__CLASS__ . ': Unable to add user "%s". This is what the server said: ', $accountName) . ldap_error($this->_ds));
         }
 
         @ldap_close($this->_ds);
@@ -141,7 +134,7 @@ class Horde_Auth_Msad extends Horde_Auth_Ldap
         }
 
         if (!@ldap_delete($this->_ds, $dn)) {
-            throw new Horde_Auth_Exception(sprintf(_("Horde_Auth_Msad: Unable to remove user \"%s\""), $accountName));
+            throw new Horde_Auth_Exception(sprintf(__CLASS__ . ': Unable to remove user "%s"', $accountName));
         }
         @ldap_close($this->_ds);
 
@@ -187,7 +180,7 @@ class Horde_Auth_Msad extends Horde_Auth_Ldap
         }
 
         if (!$success) {
-            throw new Horde_Auth_Exception(sprintf(_("Horde_Auth_Msad: Unable to update user \"%s\""), $newID), __FILE__, __LINE__);
+            throw new Horde_Auth_Exception(sprintf(__CLASS__ . ': Unable to update user "%s"', $newID));
         }
 
         @ldap_close($this->_ds);
@@ -207,6 +200,7 @@ class Horde_Auth_Msad extends Horde_Auth_Ldap
         /* Get a new random password. */
         $password = Horde_Auth::genRandomPassword() . '/';
         $this->updateUser($user_id, $user_id, array('userPassword' => $password));
+
         return $password;
     }
 
@@ -221,24 +215,16 @@ class Horde_Auth_Msad extends Horde_Auth_Ldap
         $ssl = ($this->_params['ssl']) ? 'ldaps://' : '';
         $this->_ds = ldap_connect($ssl . $this->_params['hostspec'], $this->_params['port']);
         if (!$this->_ds) {
-            throw new Horde_Auth_Exception(_("Failed to connect to MSAD server."));
+            throw new Horde_Auth_Exception('Failed to connect to MSAD server.');
         }
 
-        if (!ldap_set_option($this->_ds, LDAP_OPT_PROTOCOL_VERSION, 3)) {
-            Horde::logMessage(
-            sprintf('Set MSAD protocol version to %d failed: [%d] %s',
-            3,
-            ldap_errno($conn),
-            ldap_error($conn),
-            __FILE__, __LINE__));
-        }
-        if (!ldap_set_option($this->_ds, LDAP_OPT_REFERRALS, 0)) {
-            Horde::logMessage(
-            sprintf('Set MSAD referrals option to %d failed: [%d] %s',
-            0,
-            ldap_errno($conn),
-            ldap_error($conn),
-            __FILE__, __LINE__));
+        if ($this->_logger) {
+            if (!ldap_set_option($this->_ds, LDAP_OPT_PROTOCOL_VERSION, 3)) {
+                $this->_logger->log(sprintf('Set MSAD protocol version to %d failed: [%d] %s', 3, ldap_errno($conn), ldap_error($conn)));
+            }
+            if (!ldap_set_option($this->_ds, LDAP_OPT_REFERRALS, 0)) {
+                $this->_logger->log(sprintf('Set MSAD referrals option to %d failed: [%d] %s', 0, ldap_errno($conn), ldap_error($conn)));
+            }
         }
 
         if (isset($this->_params['binddn'])) {
@@ -250,10 +236,8 @@ class Horde_Auth_Msad extends Horde_Auth_Ldap
         }
 
         if (!$bind) {
-            throw new Horde_Auth_Exception(_("Could not bind to MSAD server."));
+            throw new Horde_Auth_Exception('Could not bind to MSAD server.');
         }
-
-        return true;
     }
 
     /**
@@ -277,7 +261,7 @@ class Horde_Auth_Msad extends Horde_Auth_Ldap
                                );
             /* Searching the tree is not successful */
             if (!$search) {
-                throw new Horde_Auth_Exception(_("Could not search the MSAD server."));
+                throw new Horde_Auth_Exception('Could not search the MSAD server.');
             }
 
             /* Fetch the search result */
@@ -289,7 +273,7 @@ class Horde_Auth_Msad extends Horde_Auth_Ldap
         }
 
         if (!is_array($result) || (count($result) <= 1)) {
-            throw new Horde_Auth_Exception(_("Empty result."));
+            throw new Horde_Auth_Exception('Empty result.');
         }
 
         /* Be sure the horde userId is the configured one */
index b061b41..d56351f 100644 (file)
  *
  *      http://pecl.php.net/package/PAM
  *
- * Optional parameters:
- * <pre>
- * 'service' - (string) The name of the PAM service to use when
- *             authenticating.
- *             DEFAULT: php
- * </pre>
- *
  * Copyright 2004-2010 The Horde Project (http://www.horde.org/)
  *
  * See the enclosed file COPYING for license information (LGPL). If you did
  * not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
  *
- * @author  Jon Parise <jon@horde.org>
- * @package Horde_Auth
+ * @author   Jon Parise <jon@horde.org>
+ * @category Horde
+ * @license  http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package  Auth
  */
 class Horde_Auth_Pam extends Horde_Auth_Base
 {
     /**
      * Constructor.
      *
-     * @param array $params  A hash containing connection parameters.
+     * @param array $params  Optional parameters:
+     * <pre>
+     * 'service' - (string) The name of the PAM service to use when
+     *             authenticating.
+     *             DEFAULT: php
+     * </pre>
      *
      * @throws Horde_Auth_Exception
      */
-    public function __construct($params = array())
+    public function __construct(array $params = array())
     {
-        if (!Horde_Util::extensionExists('pam_auth') && !Horde_Util::extensionExists('pam')) {
-            throw new Horde_Auth_Exception(_("PAM authentication is not available."));
+        if (!Horde_Util::extensionExists('pam_auth') &&
+            !Horde_Util::extensionExists('pam')) {
+            throw new Horde_Auth_Exception('PAM authentication is not available.');
         }
 
         if (!empty($params['service'])) {
index 78df47a..84d4af4 100644 (file)
@@ -3,35 +3,17 @@
  * The Horde_Auth_Passwd:: class provides a passwd-file implementation of
  * the Horde authentication system.
  *
- * Required parameters:
- * <pre>
- * 'filename' - (string) The passwd file to use.
- * </pre>
- *
- * Optional parameters:
- * <pre>
- * 'encryption'       The encryption to use to store the password in
- *                    the table (e.g. plain, crypt, md5-hex,
- *                    md5-base64, smd5, sha, ssha, aprmd5).
- *                    DEFAULT: 'crypt-des'
- * 'lock'             Should we lock the passwd file? (boolean) The password
- *                    file cannot be changed (add, edit, or delete users)
- *                    unless this is true.
- *                    DEFAULT: false<
- * 'show_encryption'  Whether or not to prepend the encryption in the
- *                    password field.
- *                    DEFAULT: 'false'
- * </pre>
- *
  * Copyright 1997-2007 Rasmus Lerdorf <rasmus@php.net>
  * Copyright 2002-2010 The Horde Project (http://www.horde.org/)
  *
  * See the enclosed file COPYING for license information (LGPL). If you did
  * not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
  *
- * @author  Rasmus Lerdorf <rasmus@php.net>
- * @author  Chuck Hagenbuch <chuck@horde.org>
- * @package Horde_Auth
+ * @author   Rasmus Lerdorf <rasmus@php.net>
+ * @author   Chuck Hagenbuch <chuck@horde.org>
+ * @category Horde
+ * @license  http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package  Auth
  */
 class Horde_Auth_Passwd extends Horde_Auth_Base
 {
@@ -63,7 +45,7 @@ class Horde_Auth_Passwd extends Horde_Auth_Base
     /**
      * Filehandle for lockfile.
      *
-     * @var integer
+     * @var resource
      */
     protected $_fplock;
 
@@ -90,10 +72,30 @@ class Horde_Auth_Passwd extends Horde_Auth_Base
     /**
      * Constructor.
      *
-     * @param array $params  A hash containing connection parameters.
+     * @param array $params  Connection parameters:
+     * <pre>
+     * 'encryption' - (string) The encryption to use to store the password in
+     *                the table (e.g. plain, crypt, md5-hex, md5-base64, smd5,
+     *                sha, ssha, aprmd5).
+     *                DEFAULT: 'crypt-des'
+     * 'filename' - (string) [REQUIRED] The passwd file to use.
+     * 'lock' - (boolean) Should we lock the passwd file? The password file
+     *          cannot be changed (add, edit, or delete users) unless this is
+     *          true.
+     *          DEFAULT: false
+     * 'show_encryption' - (boolean) Whether or not to prepend the encryption
+     *                     in the password field.
+     *                     DEFAULT: false
+     * </pre>
+     *
+     * @throws InvalidArgumentException
      */
-    public function __construct($params = array())
+    public function __construct(array $params = array())
     {
+        if (!isset($params['filename'])) {
+            throw new InvalidArgumentException('Missing filename parameter.');
+        }
+
         $params = array_merge(array(
             'encryption' => 'crypt-des',
             'lock' => false,
@@ -111,11 +113,11 @@ class Horde_Auth_Passwd extends Horde_Auth_Base
     {
         if ($this->_locked) {
             foreach ($this->_users as $user => $pass) {
+                $data = $user . ':' . $pass;
                 if ($this->_users[$user]) {
-                    fputs($this->_fplock, "$user:$pass:" . $this->_users[$user] . "\n");
-                } else {
-                    fputs($this->_fplock, "$user:$pass\n");
+                    $data .= ':' . $this->_users[$user];
                 }
+                fputs($this->_fplock, $data . "\n");
             }
             rename($this->_lockfile, $this->_params['filename']);
             flock($this->_fplock, LOCK_UN);
@@ -253,7 +255,9 @@ class Horde_Auth_Passwd extends Horde_Auth_Base
         try {
             $this->_read();
         } catch (Horde_Auth_Exception $e) {
-            Horde::logMessage($e, 'ERR');
+            if ($this->_logger) {
+                $this->_logger->log($e, 'ERR');
+            }
             throw new Horde_Auth_Exception('', Horde_Auth::REASON_FAILED);
         }
 
@@ -373,6 +377,7 @@ class Horde_Auth_Passwd extends Horde_Auth_Base
         /* Get a new random password. */
         $password = Horde_Auth::genRandomPassword();
         $this->updateUser($userId, $userId, array('password' => $password));
+
         return $password;
     }
 
index 53cede1..489809b 100644 (file)
@@ -8,35 +8,35 @@
  * connection-based protocols.
  *
  * This driver relies on the PECL sasl package:
- *
- *      http://pecl.php.net/package/sasl
- *
- * Optional parameters:
- * <pre>
- * 'app'      The name of the authenticating application.
- *            DEFAULT: horde
- * 'service'  The name of the SASL service to use when authenticating.
- *            DEFAULT: php
- * </pre>
+ *   http://pecl.php.net/package/sasl
  *
  * Copyright 2004-2010 The Horde Project (http://www.horde.org/)
  *
  * See the enclosed file COPYING for license information (LGPL). If you did
  * not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
  *
- * @author  Jon Parise <jon@horde.org>
- * @package Horde_Auth
+ * @author   Jon Parise <jon@horde.org>
+ * @category Horde
+ * @license  http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package  Auth
  */
 class Horde_Auth_Peclsasl extends Horde_Auth_Base
 {
     /**
      * Constructor.
      *
-     * @param array $params  A hash containing connection parameters.
+     * @param array $params  Optional parameters:
+     * <pre>
+     * 'app' - (string) The name of the authenticating application.
+     *         DEFAULT: horde
+     * 'service' - (string) The name of the SASL service to use when
+     *             authenticating.
+     *             DEFAULT: php
+     * </pre>
      *
      * @throws Horde_Auth_Exception
      */
-    public function __construct($params = array())
+    public function __construct(array $params = array())
     {
         if (!Horde_Util::extensionExists('sasl')) {
             throw new Horde_Auth_Exception('Horde_Auth_Peclsasl:: requires the sasl PECL extension to be loaded.');
@@ -68,7 +68,7 @@ class Horde_Auth_Peclsasl extends Horde_Auth_Base
 
         $conn = sasl_server_new($this->_params['service']);
         if (!is_resource($conn)) {
-            throw new Horde_Auth_Exception(_("Failed to create new SASL connection."));
+            throw new Horde_Auth_Exception('Failed to create new SASL connection.');
         }
 
         if (!sasl_checkpass($conn, $userId, $credentials['password'])) {
index 243a6f7..ee4da9b 100644 (file)
  * This class requires the 'radius' PECL extension:
  *   http://pecl.php.net/package/radius
  *
- * On *nix-y machines, this extension can be installed as follows:
- * <pre>
- * pecl install radius
- * </pre>
- *
- * Then, edit your php.ini file and make sure the following line is present:
- * <pre>
- *   For Windows machines:  extension=php_radius.dll
- *   For all others:        extension=radius.so
- * </pre>
- *
- * Required parameters:
- * <pre>
- * 'host' - (string) The RADIUS host to use (IP address or fully qualified
- *          hostname).
- * 'method' - (string) The RADIUS method to use for validating the request.
- *            Either: 'PAP', 'CHAP_MD5', 'MSCHAPv1', or 'MSCHAPv2'.
- *            ** CURRENTLY, only 'PAP' is supported. **
- * 'secret' - (string) The RADIUS shared secret string for the host. The
- *            RADIUS protocol ignores all but the leading 128 bytes
- *            of the shared secret.
- * </pre>
- *
- * Optional parameters:
- * <pre>
- * 'nas' - (string) The RADIUS NAS identifier to use.
- *         DEFAULT: The value of $_SERVER['HTTP_HOST'] or, if not
- *                  defined, then 'localhost'.
- * 'port' - (integer) The port to use on the RADIUS server.
- *          DEFAULT: Whatever the local system identifies as the
- *                   'radius' UDP port
- * 'retries' - (integer) The maximum number of repeated requests to make
- *             before giving up.
- *             DEFAULT: 3
- * 'suffix' - (string) The domain name to add to unqualified user names.
- *             DEFAULT: NONE
- * 'timeout' - (integer) The timeout for receiving replies from the server (in
- *             seconds).
- *             DEFAULT: 3
- * </pre>
- *
  * Copyright 2002-2010 The Horde Project (http://www.horde.org/)
  *
  * See the enclosed file COPYING for license information (LGPL). If you did
  * not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
  *
- * @author  Michael Slusarz <slusarz@horde.org>
- * @package Horde_Auth
+ * @author   Michael Slusarz <slusarz@horde.org>
+ * @category Horde
+ * @license  http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package  Auth
  */
 class Horde_Auth_Radius extends Horde_Auth_Base
 {
     /**
      * Constructor.
      *
-     * @param array $params  A hash containing connection parameters.
+     * @param array $params  Connection parameters.
+     * <pre>
+     * 'host' - (string) [REQUIRED] The RADIUS host to use (IP address or
+     *          fully qualified hostname).
+     * 'method' - (string) [REQUIRED] The RADIUS method to use for validating
+     *            the request.
+     *            Either: 'PAP', 'CHAP_MD5', 'MSCHAPv1', or 'MSCHAPv2'.
+     *            ** CURRENTLY, only 'PAP' is supported. **
+     * 'nas' - (string) The RADIUS NAS identifier to use.
+     *         DEFAULT: The value of $_SERVER['HTTP_HOST'] or, if not
+     *                  defined, then 'localhost'.
+     * 'port' - (integer) The port to use on the RADIUS server.
+     *          DEFAULT: Whatever the local system identifies as the
+     *                   'radius' UDP port
+     * 'retries' - (integer) The maximum number of repeated requests to make
+     *             before giving up.
+     *             DEFAULT: 3
+     * 'secret' - (string) [REQUIRED] The RADIUS shared secret string for the
+     *            host. The RADIUS protocol ignores all but the leading 128
+     *            bytes of the shared secret.
+     * 'suffix' - (string) The domain name to add to unqualified user names.
+     *             DEFAULT: NONE
+     * 'timeout' - (integer) The timeout for receiving replies from the server
+     *             (in seconds).
+     *             DEFAULT: 3
+     * </pre>
      *
-     * @throws Horde_Auth_Exception
+     * @throws InvalidArgumentException
      */
-    public function __construct($params = array())
+    public function __construct(array $params = array())
     {
-        parent::__construct($params);
-
         if (!Horde_Util::extensionExists('radius')) {
-            throw new Horde_Auth_Exception('Horde_Auth_Radius:: requires the radius PECL extension to be loaded.');
-        }
-
-        /* A RADIUS host is required. */
-        if (empty($this->_params['host'])) {
-            throw new Horde_Auth_Exception('Horde_Auth_Radius:: requires a RADIUS host to connect to.');
-        }
-
-        /* A RADIUS secret string is required. */
-        if (empty($this->_params['secret'])) {
-            throw new Horde_Auth_Exception('Horde_Auth_Radius:: requires a RADIUS secret string.');
-        }
-
-        /* A RADIUS authentication method is required. */
-        if (empty($this->_params['method'])) {
-            throw new Horde_Auth_Exception('Horde_Auth_Radius:: requires a RADIUS authentication method.');
-        }
-
-        /* RADIUS NAS Identifier. */
-        if (empty($this->_params['nas'])) {
-            $this->_params['nas'] = isset($_SERVER['HTTP_HOST'])
-                ? $_SERVER['HTTP_HOST']
-                : 'localhost';
+            throw new Horde_Auth_Exception(__CLASS__ . ': requires the radius PECL extension to be loaded.');
         }
 
-        /* Suffix to add to unqualified user names. */
-        if (empty($this->_params['suffix'])) {
-            $this->_params['suffix'] = '';
+        foreach (array('host', 'secret', 'method') as $val) {
+            if (!isset($params[$val])) {
+                throw new InvalidArgumentException('Missing ' . $val . ' parameter.');
+            }
         }
 
-        /* The RADIUS port to use. */
-        if (empty($this->_params['port'])) {
-            $this->_params['port'] = 0;
-        }
-
-        /* Maximum number of retries. */
-        if (empty($this->_params['retries'])) {
-            $this->_params['retries'] = 3;
-        }
+        $params = array_merge(array(
+            'nas' => (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost'),
+            'port' => 0,
+            'retries' => 3,
+            'suffix' => '',
+            'timeout' => 3
+        ), $params);
 
-        /* RADIUS timeout. */
-        if (empty($this->_params['timeout'])) {
-            $this->_params['timeout'] = 3;
-        }
+        parent::__construct($params);
     }
 
     /**
@@ -129,7 +87,7 @@ class Horde_Auth_Radius extends Horde_Auth_Base
     {
         /* Password is required. */
         if (!isset($credentials['password'])) {
-            throw new Horde_Auth_Exception(_("Password required for RADIUS authentication."));
+            throw new Horde_Auth_Exception('Password required for RADIUS authentication.');
         }
 
         $res = radius_auth_open();
@@ -153,7 +111,7 @@ class Horde_Auth_Radius extends Horde_Auth_Base
             break;
 
         case RADIUS_ACCESS_REJECT:
-            throw new Horde_Auth_Exception(_("Authentication rejected by RADIUS server."));
+            throw new Horde_Auth_Exception('Authentication rejected by RADIUS server.');
 
         default:
             throw new Horde_Auth_Exception(radius_strerror($res));
index 7b0e2b7..2032b10 100644 (file)
@@ -5,28 +5,15 @@
  * not provide any actual SP functionality, it just takes the username
  * from the HTTP headers that should be set by the Shibboleth SP.
  *
- * Required Parameters:
- * <pre>
- * 'username_header' - (string) Name of the header holding the username of the
- *                     logged in user.
- * </pre>
- *
- * Optional Parameters:
- * <pre>
- * 'password_header' - (string) Name of the header holding the password of the
- *                     logged in user.
- * 'password_holder' - (string) Where the hordeauth password is stored.
- * 'password_preference' - (string) Name of the Horde preference holding the
- *                         password of the logged in user.
- * </pre>
- *
  * Copyright 9Star Research, Inc. 2006 http://www.protectnetwork.org/
  *
  * See the enclosed file COPYING for license information (LGPL). If you did
  * not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
  *
- * @author  Cassio Nishiguchi <cassio@protectnetwork.org>
- * @package Horde_Auth
+ * @author   Cassio Nishiguchi <cassio@protectnetwork.org>
+ * @category Horde
+ * @license  http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package  Auth
  */
 class Horde_Auth_Shibboleth extends Horde_Auth_Base
 {
@@ -43,11 +30,24 @@ class Horde_Auth_Shibboleth extends Horde_Auth_Base
     /**
      * Constructor.
      *
-     * @param array $params  A hash containing parameters.
+     * @param array $params  Parameters:
+     * <pre>
+     * 'password_header' - (string) Name of the header holding the password of
+     *                     the logged in user.
+     * 'password_holder' - (string) Where the hordeauth password is stored.
+     * 'password_preference' - (string) Name of the Horde preference holding
+     *                         the password of the logged in user.
+     * 'username_header' - (string) [REQUIRED] Name of the header holding the
+     *                     username of the logged in user.
+     * </pre>
+     *
+     * @throws InvalidArgumentException
      */
-    public function __construct($params = array())
+    public function __construct(array $params = array())
     {
-        Horde::assertDriverConfig($params, 'auth', array('username_header'), 'authentication Shibboleth');
+        if (!isset($params['username_header'])) {
+            throw new InvalidArgumentException('Missing username_header parameter.');
+        }
 
         $params = array_merge(array(
             'password_header' => '',
@@ -72,7 +72,7 @@ class Horde_Auth_Shibboleth extends Horde_Auth_Base
      */
     protected function _authenticate($userId, $credentials)
     {
-        throw new Horde_Auth_Exception('Not implemented!');
+        throw new Horde_Auth_Exception('Unsupported.');
     }
 
     /**
@@ -130,10 +130,10 @@ class Horde_Auth_Shibboleth extends Horde_Auth_Base
     protected function _removeScope($username)
     {
         $pos = strrpos($username, '@');
-        if ($pos !== false) {
-            $username = substr($username, 0, $pos);
-        }
-        return $username;
+
+        return ($pos !== false)
+            ? substr($username, 0, $pos)
+            : $username;
     }
 
 }
index 0a199a2..281d9c9 100644 (file)
  * and not equal to each other. In other words, to use this module you must
  * have a domain with at least one PDC and one BDC.
  *
- * Required parameters:
- * <pre>
- * 'hostspec' - IP, DNS Name, or NetBios Name of the SMB server to
- *              authenticate with.
- * 'domain' - The domain name to authenticate with.
- * </pre>
- *
- * Optional parameters:
- * <pre>
- * 'group' - Group name that the user must be a member of. Will be
- *           ignored if the value passed is a zero length string.
- * </pre>
- *
  * Copyright 1999-2010 The Horde Project (http://www.horde.org/)
  *
  * See the enclosed file COPYING for license information (LGPL). If you did
  * not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
  *
- * @author  Jon Parise <jon@horde.org>
- * @author  Marcus I. Ryan <marcus@riboflavin.net>
- * @package Horde_Auth
+ * @author   Jon Parise <jon@horde.org>
+ * @author   Marcus I. Ryan <marcus@riboflavin.net>
+ * @category Horde
+ * @license  http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package  Auth
  */
 class Horde_Auth_Smb extends Horde_Auth_Base
 {
     /**
      * Constructor.
      *
-     * @param array $params  A hash containing connection parameters.
+     * @param array $params  Parameters:
+     * <pre>
+     * 'domain' - (string) [REQUIRED] The domain name to authenticate with.
+     * 'group' - Group name that the user must be a member of.
+     *           DEFAULT: none
+     * 'hostspec' - (string) [REQUIRED] IP, DNS Name, or NetBios name of the
+     *              SMB server to authenticate with.
+     * </pre>
      *
      * @throws Horde_Auth_Exception
+     * @throws InvalidArgumentException
      */
-    public function __construct($params = array())
+    public function __construct(array $params = array())
     {
         if (!Horde_Util::extensionExists('smbauth')) {
-            throw new Horde_Auth_Exception(_("Horde_Auth_Smb: Required smbauth extension not found."));
+            throw new Horde_Auth_Exception(__CLASS__ . ': Required smbauth extension not found.');
+        }
+
+        foreach (array('domain', 'hostspec') as $val) {
+            throw new InvalidArgumentException('Missing ' . $val . ' parameter.');
         }
 
-        /* Ensure we've been provided with all of the necessary parameters. */
-        Horde::assertDriverConfig($params, 'auth',
-            array('hostspec', 'domain'),
-            'authentication Samba');
+        $params = array_merge(array(
+            'group' => null
+        ), $params);
 
         parent::__construct($params);
     }
@@ -78,7 +78,7 @@ class Horde_Auth_Smb extends Horde_Auth_Base
                          $credentials['password']);
 
         if ($rval === 1) {
-            throw new Horde_Auth_Exception(_("Failed to connect to SMB server."));
+            throw new Horde_Auth_Exception('Failed to connect to SMB server.');
         } elseif ($rval !== 0) {
             throw new Horde_Auth_Exception(err2str());
         }
index 7a52829..72b978b 100644 (file)
@@ -3,42 +3,40 @@
  * The Horde_Auth_Smbclient class provides an smbclient implementation of
  * the Horde authentication system.
  *
- * Required parameters:
- * <pre>
- * 'domain'          The domain name to authenticate with.
- * 'hostspec'        IP, DNS Name, or NetBios Name of the SMB server to
- *                   authenticate with.
- * 'smbclient_path'  The location of the smbclient(1) utility.
- * </pre>
- *
- * Optional parameters:
- * <pre>
- * 'group' - Group name that the user must be a member of. Will be
- *           ignored if the value passed is a zero length string.
- * </pre>
- *
  * Copyright 1999-2010 The Horde Project (http://www.horde.org/)
  *
  * See the enclosed file COPYING for license information (LGPL). If you did
  * not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
  *
- * @author  Jon Parise <jon@horde.org>
- * @author  Marcus I. Ryan <marcus@riboflavin.net>
- * @package Horde_Auth
+ * @author   Jon Parise <jon@horde.org>
+ * @author   Marcus I. Ryan <marcus@riboflavin.net>
+ * @category Horde
+ * @license  http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package  Auth
  */
 class Horde_Auth_Smbclient extends Horde_Auth_Base
 {
     /**
      * Constructor.
      *
-     * @param array $params  A hash containing connection parameters.
+     * @param array $params  Parameters:
+     * <pre>
+     * 'domain' - (string) [REQUIRED] The domain name to authenticate with.
+     * 'group' - Group name that the user must be a member of.
+     *           DEFAULT: none
+     * 'hostspec' - (string) [REQUIRED] IP, DNS Name, or NetBios name of the
+     *              SMB server to authenticate with.
+     * 'smbclient_path' - (string) [REQUIRED] The location of the smbclient
+     *                    utility.
+     * </pre>
+     *
+     * @throws InvalidArgumentException
      */
-    public function __construct($params = array())
+    public function __construct(array $params = array())
     {
-        /* Ensure we've been provided with all of the necessary parameters. */
-        Horde::assertDriverConfig($params, 'auth',
-            array('hostspec', 'domain', 'smbclient_path'),
-            'authentication smbclient');
+        foreach (array('hostspec', 'domain', 'smbclient_path') as $val) {
+            throw new InvalidArgumentException('Missing ' . $val . ' parameter.');
+        }
 
         parent::__construct($params);
     }
@@ -58,23 +56,25 @@ class Horde_Auth_Smbclient extends Horde_Auth_Base
         }
 
         /* Authenticate. */
-        $cmdline = implode(' ', array($this->_params['smbclient_path'],
-                                      '-L',
-                                      $this->_params['hostspec'],
-                                      '-W',
-                                      $this->_params['domain'],
-                                      '-U',
-                                      $userId));
+        $cmdline = implode(' ', array(
+            $this->_params['smbclient_path'],
+            '-L',
+            $this->_params['hostspec'],
+            '-W',
+            $this->_params['domain'],
+            '-U',
+            $userId
+        ));
 
         $sc = popen($cmdline, 'w');
         if ($sc === false) {
-            throw new Horde_Auth_Exception(_("Unable to execute smbclient."));
+            throw new Horde_Auth_Exception('Unable to execute smbclient.');
         }
 
         fwrite($sc, $credentials['password']);
         $rc = pclose($sc);
 
-        if ((int)($rc & 0xff) != 0) {
+        if (intval($rc & 0xff) != 0) {
             throw new Horde_Auth_Exception('', Horde_Auth::REASON_BADLOGIN);
         }
     }
index d1e743d..a228cc1 100644 (file)
@@ -3,59 +3,6 @@
  * The Horde_Auth_Sql class provides a SQL implementation of the Horde
  * authentication system.
  *
- * Required parameters:
- * <pre>
- * 'phptype' - (string) The database type (ie. 'pgsql', 'mysql', etc.).
- * </pre>
- *
- * Optional parameters:
- * <pre>
- * 'encryption' - (string) The encryption to use to store the password in
- *                the table (e.g. plain, crypt, md5-hex, md5-base64, smd5,
- *                sha, ssha, aprmd5).
- *                DEFAULT: 'md5-hex'
- * 'hard_expiration_field' - (string) The name of the field containing a date
- *                           after which the account is no longer valid and
- *                           the user will not be able to log in at all.
- *                           DEFAULT: none
- * 'password_field' - (string) The name of the password field in the auth
- *                    table.
- *                    DEFAULT: 'user_pass'
- * 'show_encryption' - (boolean) Whether or not to prepend the encryption in
- *                     the password field.
- *                     DEFAULT: false
- * 'soft_expiration_field' - (string) The name of the field containing a date
- *                           after which the system will request the user
- *                           change his or her password.
- *                           DEFAULT: none
- * 'table' - (string) The name of the SQL table to use in 'database'.
- *           DEFAULT: 'horde_users'
- * 'username_field' - (string) The name of the username field in the auth
- *                    table.
- *                    DEFAULT: 'user_uid'
- * </pre>
- *
- * Required by some database implementations:
- * <pre>
- * 'hostspec'     The hostname of the database server.
- * 'protocol'     The communication protocol ('tcp', 'unix', etc.).
- * 'database'     The name of the database.
- * 'username'     The username with which to connect to the database.
- * 'password'     The password associated with 'username'.
- * 'options'      Additional options to pass to the database.
- * 'port'         The port on which to connect to the database.
- * 'tty'          The TTY on which to connect to the database.
- * </pre>
- *
- * Optional values when using separate read and write servers, for example
- * in replication settings:
- * <pre>
- * 'splitread'   Boolean, whether to implement the separation or not.
- * 'read'        Array containing the parameters which are different for
- *               the read database connection, currently supported
- *               only 'hostspec' and 'port' parameters.
- * </pre>
- *
  * The table structure for the Auth system is in
  * horde/scripts/sql/horde_users.sql.
  *
  * See the enclosed file COPYING for license information (LGPL). If you did
  * not receive this file, see http://opensource.org/licenses/lgpl-2.1.php
  *
- * @author  Chuck Hagenbuch <chuck@horde.org>
- * @package Horde_Auth
+ * @author   Chuck Hagenbuch <chuck@horde.org>
+ * @category Horde
+ * @license  http://opensource.org/licenses/lgpl-2.1.php LGPL
+ * @package  Auth
  */
 class Horde_Auth_Sql extends Horde_Auth_Base
 {
@@ -87,24 +36,65 @@ class Horde_Auth_Sql extends Horde_Auth_Base
     /**
      * Handle for the current database connection.
      *
-     * @var DB
+     * @var Horde_Db_Adapter_Base
      */
     protected $_db;
 
     /**
-     * Handle for the current database connection, used for writing. Defaults
-     * to the same handle as $_db if a separate write database is not required.
+     * Constructor
      *
-     * @var DB
-     */
-    protected $_write_db;
-
-    /**
-     * Boolean indicating whether or not we're connected to the SQL server.
+     * @param array $params  Parameters:
+     * 'db' - (Horde_Db_Adapter_Base) [REQUIRED] Database object.
+     * <pre>
+     * 'encryption' - (string) The encryption to use to store the password in
+     *                the table (e.g. plain, crypt, md5-hex, md5-base64, smd5,
+     *                sha, ssha, aprmd5).
+     *                DEFAULT: 'md5-hex'
+     * 'hard_expiration_field' - (string) The name of the field containing a
+     *                           date after which the account is no longer
+     *                           valid and the user will not be able to log in
+     *                           at all.
+     *                           DEFAULT: none
+     * 'password_field' - (string) The name of the password field in the auth
+     *                    table.
+     *                    DEFAULT: 'user_pass'
+     * 'show_encryption' - (boolean) Whether or not to prepend the encryption
+     *                     in the password field.
+     *                     DEFAULT: false
+     * 'soft_expiration_field' - (string) The name of the field containing a
+     *                           date after which the system will request the
+     *                           user change his or her password.
+     *                           DEFAULT: none
+     * 'table' - (string) The name of the SQL table to use in 'database'.
+     *           DEFAULT: 'horde_users'
+     * 'username_field' - (string) The name of the username field in the auth
+     *                    table.
+     *                    DEFAULT: 'user_uid'
+     * </pre>
      *
-     * @var boolean
+     * @throws InvalidArgumentException
      */
-    protected $_connected = false;
+    public function __construct(array $params = array())
+    {
+        if (!isset($params['db'])) {
+            throw new InvalidArgumentException('Missing db parameter.');
+        }
+        $this->_db = $params['db'];
+        unset($params['db']);
+
+        $params = array_merge(array(
+            'encryption' => 'md5-hex',
+            'password_field' => 'user_pass',
+            'show_encryption' => false,
+            'table' => 'horde_users',
+            'username_field' => 'user_uid'
+        ), $params);
+
+        $params['password_field'] = Horde_String::lower($params['password_field']);
+        $params['username_field'] = Horde_String::lower($params['username_field']);
+
+        parent::__construct($params);
+    }
 
     /**
      * Find out if a set of login credentials are valid.
@@ -116,36 +106,20 @@ class Horde_Auth_Sql extends Horde_Auth_Base
      */
     protected function _authenticate($userId, $credentials)
     {
-        try {
-            $this->_connect();
-        } catch (Horde_Auth_Exception $e) {
-            Horde::logMessage($e, 'ERR');
-            throw new Horde_Auth_Exception('', Horde_Auth::REASON_FAILED);
-        }
-
         /* Build the SQL query. */
         $query = sprintf('SELECT * FROM %s WHERE %s = ?',
                          $this->_params['table'],
                          $this->_params['username_field']);
         $values = array($userId);
 
-        Horde::logMessage('SQL Query by Auth_sql::_authenticate(): ' . $query, 'DEBUG');
-
-        $result = $this->_db->query($query, $values);
-        if ($result instanceof PEAR_Error) {
-            Horde::logMessage($result, 'ERR');
+        try {
+            $result = $this->_db->selectOne($query, $values);
+        } catch (Horde_Db_Exception $e) {
             throw new Horde_Auth_Exception('', Horde_Auth::REASON_FAILED);
         }
 
-        $row = $result->fetchRow(DB_GETMODE_ASSOC);
-        if (is_array($row)) {
-            $result->free();
-        } else {
-            throw new Horde_Auth_Exception('', Horde_Auth::REASON_BADLOGIN);
-        }
-
-        if (!$this->_comparePasswords($row[$this->_params['password_field']],
-                                      $credentials['password'])) {
+        if (!$result ||
+            !$this->_comparePasswords($row[$this->_params['password_field']], $credentials['password'])) {
             throw new Horde_Auth_Exception('', Horde_Auth::REASON_BADLOGIN);
         }
 
@@ -173,8 +147,6 @@ class Horde_Auth_Sql extends Horde_Auth_Base
      */
     public function addUser($userId, $credentials)
     {
-        $this->_connect();
-
         /* Build the SQL query. */
         $query = sprintf('INSERT INTO %s (%s, %s) VALUES (?, ?)',
                          $this->_params['table'],
@@ -186,11 +158,10 @@ class Horde_Auth_Sql extends Horde_Auth_Base
                                                   $this->_params['encryption'],
                                                   $this->_params['show_encryption']));
 
-        Horde::logMessage('SQL Query by Auth_sql::addUser(): ' . $query, 'DEBUG');
-
-        $result = $this->_write_db->query($query, $values);
-        if ($result instanceof PEAR_Error) {
-            throw new Horde_Auth_Exception($result);
+        try {
+            $this->_db->insert($query, $values);
+        } catch (Horde_Db_Exception $e) {
+            throw new Horde_Auth_Exception($e);
         }
     }
 
@@ -205,61 +176,55 @@ class Horde_Auth_Sql extends Horde_Auth_Base
      */
     public function updateUser($oldID, $newID, $credentials)
     {
-        $this->_connect();
+        $query = sprintf('UPDATE %s SET ', $this->_params['table']);
+        $values = array();
 
         /* Build the SQL query. */
-        $tuple = array();
-        $tuple[$this->_params['username_field']] = $newID;
-        $tuple[$this->_params['password_field']] =
-            Horde_Auth::getCryptedPassword($credentials['password'],
-                                      '',
-                                      $this->_params['encryption'],
-                                      $this->_params['show_encryption']);
+        $query .= $this->_params['username_field'] . ' = ? ';
+        $values[] = $newID;
+
+        $query .= $this->_params['password_field'] . ' = ? ';
+        $values[] = Horde_Auth::getCryptedPassword($credentials['password'], '', $this->_params['encryption'], $this->_params['show_encryption']);
 
         if (empty($this->_params['soft_expiration_window'])) {
             if (!empty($this->_params['soft_expiration_field'])) {
-                $tuple[$this->_params['soft_expiration_field']] = null;
+                $query .= $this->_params['soft_expiration_field'] . ' = ? ';
+                $values[] = null;
             }
         } else {
-            $date = time();
-            $datea = localtime($date, true);
+            $datea = localtime(time(), true);
             $date = mktime($datea['tm_hour'], $datea['tm_min'],
                            $datea['tm_sec'], $datea['tm_mon'] + 1,
                            $datea['tm_mday'] + $this->_params['soft_expiration_window'],
                            $datea['tm_year']);
 
-            $tuple[$this->_params['soft_expiration_field']] = $date;
+            $query .= $this->_params['soft_expiration_field'] . ' = ? ';
+            $values[] = $date;
 
-            global $notification;
-            if (!empty($notification)) {
-                $notification->push(strftime(_("New password will expire on %s."), $date), 'horde.message');
+            if ($this->_params['notify_expire']) {
+                call_user_func($this->_params['notify_expire'], $date);
             }
 
+            $query .= $this->_params['soft_expiration_field'] . ' = ? ';
+
             if (empty($this->_params['hard_expiration_window'])) {
-                $tuple[$this->_params['hard_expiration_field']] = null;
+                $values[] = null;
             } else {
                 $datea = localtime($date, true);
-                $date = mktime($datea['tm_hour'], $datea['tm_min'],
-                               $datea['tm_sec'], $datea['tm_mon'] + 1,
-                               $datea['tm_mday'] + $this->_params['soft_expiration_window'],
-                               $datea['tm_year']);
-
-                $tuple[$this->_params['hard_expiration_field']] = $date;
+                $values[]= mktime($datea['tm_hour'], $datea['tm_min'],
+                           $datea['tm_sec'], $datea['tm_mon'] + 1,
+                           $datea['tm_mday'] + $this->_params['soft_expiration_window'],
+                           $datea['tm_year']);
             }
         }
 
-        $query = sprintf('UPDATE %s SET %s WHERE %s = ?',
-                         $this->_params['table'],
-                         Horde_SQL::updateValues($this->_write_db, $tuple),
-                         $this->_params['username_field']);
-        $values = array($oldID);
-
-        Horde::logMessage('SQL Query by Auth_sql:updateUser(): ' . $query, 'DEBUG');
+        $query = .= sprintf('WHERE %s = ?', $this->_params['username_field']);
+        $values[] = $oldID;
 
-        $result = $this->_write_db->query($query, $values);
-        if ($result instanceof PEAR_Error) {
-            Horde::logMessage($result, 'ERR');
-            throw new Horde_Auth_Exception($result);
+        try {
+            $this->_db->update($query, $values);
+        } catch (Horde_Db_Exception $e) {
+            throw new Horde_Auth_Exception($e);
         }
     }
 
@@ -274,8 +239,6 @@ class Horde_Auth_Sql extends Horde_Auth_Base
      */
     public function resetPassword($userId)
     {
-        $this->_connect();
-
         /* Get a new random password. */
         $password = Horde_Auth::genRandomPassword();
 
@@ -290,11 +253,10 @@ class Horde_Auth_Sql extends Horde_Auth_Base
                                                   $this->_params['show_encryption']),
                         $userId);
 
-        Horde::logMessage('SQL Query by Auth_sql::resetPassword(): ' . $query, 'DEBUG');
-
-        $result = $this->_write_db->query($query, $values);
-        if ($result instanceof PEAR_Error) {
-            throw new Horde_Auth_Exception($result);
+        try {
+            $this->_db->update($query, $values);
+        } catch (Horde_Db_Exception $e) {
+            throw new Horde_Auth_Exception($e);
         }
 
         return $password;
@@ -309,19 +271,16 @@ class Horde_Auth_Sql extends Horde_Auth_Base
      */
     public function removeUser($userId)
     {
-        $this->_connect();
-
         /* Build the SQL query. */
         $query = sprintf('DELETE FROM %s WHERE %s = ?',
                          $this->_params['table'],
                          $this->_params['username_field']);
         $values = array($userId);
 
-        Horde::logMessage('SQL Query by Auth_sql::removeUser(): ' . $query, 'DEBUG');
-
-        $result = $this->_write_db->query($query, $values);
-        if ($result instanceof PEAR_Error) {
-            throw new Horde_Auth_Exception($result);
+        try {
+            $this->_db->delete($query, $values);
+        } catch (Horde_Db_Exception $e) {
+            throw new Horde_Auth_Exception($e);
         }
 
         Horde_Auth::removeUserData($userId);
@@ -335,21 +294,16 @@ class Horde_Auth_Sql extends Horde_Auth_Base
      */
     public function listUsers()
     {
-        $this->_connect();
-
         /* Build the SQL query. */
         $query = sprintf('SELECT %s FROM %s',
                          $this->_params['username_field'],
                          $this->_params['table']);
 
-        Horde::logMessage('SQL Query by Auth_sql::listUsers(): ' . $query, 'DEBUG');
-
-        $res = $this->_db->getCol($query);
-        if ($res instanceof PEAR_Error) {
-            throw new Horde_Auth_Exception($res);
+        try {
+            return $this->_db->selectValues($query);
+        } catch (Horde_Db_Exception $e) {
+            throw new Horde_Auth_Exception($e);
         }
-
-        return $res;
     }
 
     /**
@@ -359,20 +313,17 @@ class Horde_Auth_Sql extends Horde_Auth_Base
      */
     public function exists($userId)
     {
-        $this->_connect();
-
         /* Build the SQL query. */
         $query = sprintf('SELECT 1 FROM %s WHERE %s = ?',
                          $this->_params['table'],
                          $this->_params['username_field']);
         $values = array($userId);
 
-        Horde::logMessage('SQL Query by Auth_sql::exists(): ' . $query, 'DEBUG');
-
-        $res = $this->_db->getOne($query, $values);
-        return ($res instanceof PEAR_Error)
-            ? false
-            : $res;
+        try {
+            return (bool)$this->_db->selectValue($query, $values);
+        } catch (Horde_Db_Exception $e) {
+            return false;
+        }
     }
 
     /**
@@ -392,94 +343,4 @@ class Horde_Auth_Sql extends Horde_Auth_Base
                                                        $this->_params['show_encryption']);
     }
 
-    /**
-     * Attempts to open a connection to the SQL server.
-     *
-     * @throws Horde_Auth_Exception
-     */
-    function _connect()
-    {
-        if ($this->_connected) {
-            return;
-        }
-
-        Horde::assertDriverConfig($this->_params, 'auth', array('phptype'),
-                                  'authentication SQL');
-
-        if (!isset($this->_params['database'])) {
-            $this->_params['database'] = '';
-        }
-        if (!isset($this->_params['username'])) {
-            $this->_params['username'] = '';
-        }
-        if (!isset($this->_params['password'])) {
-            $this->_params['password'] = '';
-        }
-        if (!isset($this->_params['hostspec'])) {
-            $this->_params['hostspec'] = '';
-        }
-        if (empty($this->_params['encryption'])) {
-            $this->_params['encryption'] = 'md5-hex';
-        }
-        if (!isset($this->_params['show_encryption'])) {
-            $this->_params['show_encryption'] = false;
-        }
-        if (empty($this->_params['table'])) {
-            $this->_params['table'] = 'horde_users';
-        }
-        if (empty($this->_params['username_field'])) {
-            $this->_params['username_field'] = 'user_uid';
-        } else {
-            $this->_params['username_field'] = Horde_String::lower($this->_params['username_field']);
-        }
-        if (empty($this->_params['password_field'])) {
-            $this->_params['password_field'] = 'user_pass';
-        } else {
-            $this->_params['password_field'] = Horde_String::lower($this->_params['password_field']);
-        }
-
-        /* Connect to the SQL server using the supplied parameters. */
-        $this->_write_db = DB::connect($this->_params,
-                                       array('persistent' => !empty($this->_params['persistent']),
-                                             'ssl' => !empty($this->_params['ssl'])));
-        if ($this->_write_db instanceof PEAR_Error) {
-            throw new Horde_Auth_Exception($this->_write_db);
-        }
-
-        // Set DB portability options.
-        switch ($this->_write_db->phptype) {
-        case 'mssql':
-            $this->_write_db->setOption('portability', DB_PORTABILITY_LOWERCASE | DB_PORTABILITY_ERRORS | DB_PORTABILITY_RTRIM);
-            break;
-        default:
-            $this->_write_db->setOption('portability', DB_PORTABILITY_LOWERCASE | DB_PORTABILITY_ERRORS);
-        }
-
-        /* Check if we need to set up the read DB connection
-         * seperately. */
-        if (!empty($this->_params['splitread'])) {
-            $params = array_merge($this->_params, $this->_params['read']);
-            $this->_db = DB::connect($params,
-                                     array('persistent' => !empty($params['persistent']),
-                                           'ssl' => !empty($params['ssl'])));
-            if ($this->_db instanceof PEAR_Error) {
-                throw new Horde_Auth_Exception($this->_db);
-            }
-
-            switch ($this->_db->phptype) {
-            case 'mssql':
-                $this->_db->setOption('portability', DB_PORTABILITY_LOWERCASE | DB_PORTABILITY_ERRORS | DB_PORTABILITY_RTRIM);
-                break;
-            default:
-                $this->_db->setOption('portability', DB_PORTABILITY_LOWERCASE | DB_PORTABILITY_ERRORS);
-            }
-
-        } else {
-            /* Default to the same DB handle for reads. */
-            $this->_db =& $this->_write_db;
-        }
-
-        $this->_connected = true;
-    }
-
 }
index e18dae5..5fc9525 100644 (file)
@@ -143,6 +143,14 @@ http://pear.php.net/dtd/package-2.0.xsd">
     <channel>pear.horde.org</channel>
     <min>0.2.0</min>
    </package>
+   <package>
+    <name>Ldap</name>
+    <channel>pear.horde.org</channel>
+   </package>
+   <package>
+    <name>Net_IMSP</name>
+    <channel>pear.horde.org</channel>
+   </package>
    <extension>
     <name>gettext</name>
    </extension>
diff --git a/framework/Core/lib/Horde/Core/Binder/Auth.php b/framework/Core/lib/Horde/Core/Binder/Auth.php
new file mode 100644 (file)
index 0000000..51731a8
--- /dev/null
@@ -0,0 +1,18 @@
+<?php
+/**
+ * @category Horde
+ * @package  Core
+ */
+class Horde_Core_Binder_Auth implements Horde_Injector_Binder
+{
+    public function create(Horde_Injector $injector)
+    {
+        return new Horde_Core_Factory_Auth($injector);
+    }
+
+    public function equals(Horde_Injector_Binder $binder)
+    {
+        return false;
+    }
+
+}
diff --git a/framework/Core/lib/Horde/Core/Factory/Auth.php b/framework/Core/lib/Horde/Core/Factory/Auth.php
new file mode 100644 (file)
index 0000000..05c4b16
--- /dev/null
@@ -0,0 +1,160 @@
+<?php
+/**
+ * A Horde_Injector:: based Horde_Auth:: factory.
+ *
+ * PHP version 5
+ *
+ * @category Horde
+ * @package  Core
+ * @author   Michael Slusarz <slusarz@horde.org>
+ * @license  http://www.fsf.org/copyleft/lgpl.html LGPL
+ * @link     http://pear.horde.org/index.php?package=Core
+ */
+
+/**
+ * A Horde_Injector:: based Horde_Auth:: factory.
+ *
+ * Copyright 2010 The Horde Project (http://www.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.
+ *
+ * @category Horde
+ * @package  Core
+ * @author   Michael Slusarz <slusarz@horde.org>
+ * @license  http://www.fsf.org/copyleft/lgpl.html LGPL
+ * @link     http://pear.horde.org/index.php?package=Core
+ */
+class Horde_Core_Factory_Auth
+{
+    /**
+     * The injector.
+     *
+     * @var Horde_Injector
+     */
+    private $_injector;
+
+    /**
+     * Singleton instances.
+     *
+     * @var array
+     */
+    private $_instances = array();
+
+    /**
+     * Constructor.
+     *
+     * @param Horde_Injector $injector  The injector to use.
+     */
+    public function __construct(Horde_Injector $injector)
+    {
+        $this->_injector = $injector;
+    }
+
+    /**
+     * Return the Horde_Auth:: instance.
+     *
+     * @param string $driver  The driver.
+     * @param array $params   Additional parameters to pass to the driver
+     *                        (will override Horde defaults).
+     *
+     * @return Horde_Auth_Base  The singleton instance.
+     * @throws Horde_Auth_Exception
+     */
+    public function getOb($driver = null, array $params = array())
+    {
+        if (is_null($driver)) {
+            $driver = $GLOBALS['conf']['auth']['driver'];
+        }
+
+        $params = array_merge(Horde::getDriverConfig('auth', $driver), $params);
+        ksort($params);
+
+        /* Get proper driver name now that we have grabbed the
+         * configuration. */
+        if (strcasecmp($driver, 'httpremote') === 0) {
+            /* BC */
+            $driver = 'Http_Remote';
+        } elseif (strcasecmp($driver, 'application') === 0) {
+            $driver = 'Horde_Core_Auth_Application';
+        } else {
+            $driver = Horde_String::ucfirst(Horde_String::lower(basename($driver)));
+        }
+
+        $sig = hash('md5', serialize(array($driver, $params)));
+
+        if (!isset($this->_instances[$sig])) {
+            $lc_driver = Horde_String::lower($driver);
+            switch ($lc_driver) {
+            case 'composite':
+                // TODO
+                $params['admin_driver'] = null;
+                $params['auth_driver'] = null;
+                break;
+
+            case 'cyrsql':
+            case 'cyrus':
+                $imap_config = array(
+                    'hostspec' => empty($params['hostspec']) ? null : $params['hostspec'],
+                    'password' => $params['cyrpass'],
+                    'port' => empty($params['port']) ? null : $params['port'],
+                    'secure' => ($params['secure'] == 'none') ? null : $params['secure'],
+                    'username' => $params['cyradmin']
+                );
+
+                try {
+                    $ob = Horde_Imap_Client::factory('Socket', $imap_config);
+                    $ob->login();
+                    $params['imap'] = $ob;
+                } catch (Horde_Imap_Client_Exception $e) {
+                    throw new Horde_Auth_Exception($e);
+                }
+                break;
+
+                if ($lc_driver == 'cyrus') {
+                    $params['backend'] = $this->getOb($params['backend']['driver'], $params['backend']['params']);
+                }
+                break;
+
+            case 'http_remote':
+                if (!empty($GLOBALS['conf']['http']['proxy']['proxy_host'])) {
+                    $params['proxy'] = $GLOBALS['conf']['http']['proxy'];
+                }
+                break;
+
+            case 'kolab':
+                $params['kolab'] = $this->_injector->getInstance('Horde_Kolab_Session');
+                break;
+
+            case 'ldap':
+                $params['ldap'] = $this->_injector->getInstance('Horde_Ldap')->getOb('horde', 'auth');
+                break;
+
+            case 'sql':
+                $params['db'] = $this->_injector->getInstance('Horde_Db')->getOb('auth');
+                break;
+            }
+
+            $params['logger'] = $this->_injector->getInstance('Horde_Log_Logger');
+            $params['notify_expire'] = array($this, 'notifyExpire');
+
+            $this->_instances[$sig] = Horde_Auth::factory($driver, $params);
+        }
+
+        return $this->_instances[$sig];
+    }
+
+    /**
+     * Expire notification callback.
+     *
+     * @param integer $date  UNIX timestamp of password expiration.
+     */
+    public function notifyExpire($date)
+    {
+        if (isset($GLOBALS['notification'])) {
+            $toexpire = ($date - time()) / 86400;
+            $GLOBALS['notification']->push(sprintf(ngettext("%d day until your password expires.", "%d days until your password expires.", $toexpire), $toexpire), 'horde.warning');
+        }
+    }
+
+}
index b859c94..617a8e0 100644 (file)
@@ -283,7 +283,7 @@ class Horde_Core_Perms_Ui
         /* Users permissions. */
         $perm_val = $permission->getUserPermissions();
         $this->_form->setSection('users', _("Individual Users"), Horde::img('user.png'), false);
-        $auth = Horde_Auth::singleton($GLOBALS['conf']['auth']['driver']);
+        $auth = $GLOBALS['injector']->getInstance('Horde_Auth')->getOb();
         if ($auth->hasCapability('list')) {
             /* The auth driver has list capabilities so set up an array which
              * the matrix field type will recognise to set up an enum box for
index c6de035..cd6267d 100644 (file)
@@ -231,6 +231,7 @@ class Horde_Registry
         /* Define binders. */
         $binders = array(
             'Horde_Alarm' => new Horde_Core_Binder_Alarm(),
+            'Horde_Auth' => new Horde_Core_Binder_Auth(),
             // 'Horde_Browser' - initialized below
             'Horde_Cache' => new Horde_Core_Binder_Cache(),
             'Horde_Core_Auth_Signup' => new Horde_Core_Binder_AuthSignup(),
@@ -1073,7 +1074,7 @@ class Horde_Registry
          * libraries from other applications. */
         $app_lib = $this->get('fileroot', $app) . '/lib';
         Horde_Autoloader::addClassPattern('/^' . $app . '(?:$|_)/i', $app_lib);
-        
+
         $checkPerms = !isset($options['check_perms']) || !empty($options['check_perms']);
 
         /* If permissions checking is requested, return an error if the
index 3fa61bf..6ef3630 100644 (file)
@@ -79,6 +79,7 @@ Application Framework.
       </dir> <!-- /lib/Horde/Core/Autoloader -->
       <dir name="Binder">
        <file name="Alarm.php" role="php" />
+       <file name="Auth.php" role="php" />
        <file name="AuthSignup.php" role="php" />
        <file name="Cache.php" role="php" />
        <file name="Data.php" role="php" />
@@ -106,6 +107,7 @@ Application Framework.
        <file name="Share.php" role="php" />
       </dir> <!-- /lib/Horde/Core/Binder -->
       <dir name="Factory">
+       <file name="Auth.php" role="php" />
        <file name="Db.php" role="php" />
        <file name="DbPear.php" role="php" />
        <file name="Data.php" role="php" />
@@ -269,6 +271,7 @@ Application Framework.
    <install name="lib/Horde/Core/Autoloader/Callback/Auth.php" as="Horde/Core/Autoloader/Callback/Auth.php" />
    <install name="lib/Horde/Core/Autoloader/Callback/Mime.php" as="Horde/Core/Autoloader/Callback/Mime.php" />
    <install name="lib/Horde/Core/Binder/Alarm.php" as="Horde/Core/Binder/Alarm.php" />
+   <install name="lib/Horde/Core/Binder/Auth.php" as="Horde/Core/Binder/Auth.php" />
    <install name="lib/Horde/Core/Binder/AuthSignup.php" as="Horde/Core/Binder/AuthSignup.php" />
    <install name="lib/Horde/Core/Binder/Cache.php" as="Horde/Core/Binder/Cache.php" />
    <install name="lib/Horde/Core/Binder/Data.php" as="Horde/Core/Binder/Data.php" />
@@ -294,6 +297,7 @@ Application Framework.
    <install name="lib/Horde/Core/Binder/Vfs.php" as="Horde/Core/Binder/Vfs.php" />
    <install name="lib/Horde/Core/Binder/Facebook.php" as="Horde/Core/Binder/Facebook.php" />
    <install name="lib/Horde/Core/Binder/Share.php" as="Horde/Core/Binder/Share.php" />
+   <install name="lib/Horde/Core/Factory/Auth.php" as="Horde/Core/Factory/Auth.php" />
    <install name="lib/Horde/Core/Factory/Db.php" as="Horde/Core/Factory/Db.php" />
    <install name="lib/Horde/Core/Factory/DbPear.php" as="Horde/Core/Factory/DbPear.php" />
    <install name="lib/Horde/Core/Factory/Data.php" as="Horde/Core/Factory/Data.php" />
index 4f6f7f6..50097e7 100644 (file)
@@ -665,7 +665,7 @@ class Group {
 
         $group_driver = null;
         $group_params = null;
-        $auth = Horde_Auth::singleton($GLOBALS['conf']['auth']['driver']);
+        $auth = $GLOBALS['injector']->getInstance('Horde_Auth')->getOb();
         if ($auth->hasCapability('groups')) {
             $group_driver = $auth->getDriver();
             $group_params = $auth;
index 1c918c8..02c89df 100644 (file)
@@ -183,7 +183,7 @@ class Kolab_Resource
         $calendar_user = $conf['kolab']['filter']['calendar_id'] . '@' . $domain;
 
         /* Load the authentication libraries */
-        $auth = Horde_Auth::singleton(isset($conf['auth']['driver'])?$conf['auth']['driver']:'kolab');
+        $auth = $GLOBALS['injector']->getInstance('Horde_Auth')->getOb(isset($conf['auth']['driver']) ? null : 'kolab');
         $authenticated = $auth->authenticate($calendar_user,
                                              array('password' => $conf['kolab']['filter']['calendar_pass']),
                                              false);
index f3c008f..9e55159 100644 (file)
@@ -115,7 +115,7 @@ class Horde_Rpc
         }
 
         // @TODO: inject this
-        $auth = Horde_Auth::singleton($GLOBALS['conf']['auth']['driver']);
+        $auth = $GLOBALS['injector']->getInstance('Horde_Auth')->getOb();
 
         if ($this->_request->getServer('PHP_AUTH_USER')) {
             $user = $this->_request->getServer('PHP_AUTH_USER');
index 6c7dc13..9004528 100644 (file)
@@ -825,7 +825,7 @@ class Horde_Rpc_Webdav extends Horde_Rpc
      */
     function check_auth($type, $username, $password)
     {
-        $auth = Horde_Auth::singleton($GLOBALS['conf']['auth']['driver']);
+        $auth = $GLOBALS['injector']->getInstance('Horde_Auth')->getOb();
         return $auth->authenticate($username, array('password' => $password));
     }
 
index bf92bed..6f163df 100644 (file)
@@ -482,7 +482,7 @@ class SyncML_Backend_Horde extends SyncML_Backend {
      */
     function _checkAuthentication($username, $password)
     {
-        $auth = Horde_Auth::singleton($GLOBALS['conf']['auth']['driver']);
+        $auth = $GLOBALS['injector']->getInstance('Horde_Auth')->getOb();
         return $auth->authenticate($username, array('password' => $password))
             ? Horde_Auth::getAuth()
             : false;
@@ -870,7 +870,7 @@ class SyncML_Backend_Horde extends SyncML_Backend {
         }
 
         /* Get an Auth object. */
-        $auth = Horde_Auth::singleton($GLOBALS['conf']['auth']['driver']);
+        $auth = $GLOBALS['injector']->getInstance('Horde_Auth')->getOb();
 
         /* Make this user an admin for the time beeing to allow deletion of
          * user data. */
@@ -917,7 +917,7 @@ class SyncML_Backend_Horde extends SyncML_Backend {
     {
         /* Get an Auth object. */
         try {
-            $auth = Horde_Auth::singleton($GLOBALS['conf']['auth']['driver']);
+            $auth = $GLOBALS['injector']->getInstance('Horde_Auth')->getOb();
         } catch (Horde_Exception $e) {
             // TODO
         }
index 92a5f12..f5220a4 100644 (file)
@@ -13,7 +13,7 @@ Horde_Registry::appInit('horde', array('admin' => true));
 
 require_once 'Horde/Group.php';
 $groups = Group::singleton();
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
 
 $form = null;
 $reload = false;
index 6faad98..ae981de 100644 (file)
@@ -12,7 +12,7 @@ require_once dirname(__FILE__) . '/../lib/base.php';
 Horde_Registry::appInit('horde', array('authentication' => 'none'));
 
 // Make sure signups are enabled before proceeding
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
 if ($conf['signup']['allow'] !== true ||
     !$auth->hasCapability('add')) {
     throw new Horde_Exception(_("User Registration has been disabled for this site."));
index 5217162..4b4d5ae 100644 (file)
@@ -11,7 +11,7 @@
 require_once dirname(__FILE__) . '/../lib/Application.php';
 Horde_Registry::appInit('horde', array('admin' => true));
 
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
 
 if ($conf['signup']['allow'] && $conf['signup']['approve']) {
     $signup = $injector->getInstance('Horde_Core_Auth_Signup');
index 6bc9785..5629bec 100644 (file)
@@ -95,7 +95,7 @@ class Horde_Prefs_Ui
 
         /* Hide appropriate prefGroups. */
         try {
-            Horde_Auth::singleton($conf['auth']['driver'])->hasCapability('update');
+            $GLOBALS['injector']->getInstance('Horde_Auth')->getOb()->hasCapability('update');
         } catch (Horde_Exception $e) {
             $ui->suppressGroups[] = 'forgotpass';
         }
index 8cd82e1..d7a7030 100644 (file)
@@ -98,8 +98,8 @@ if (!$is_auth) {
 
 /* Get an Auth object. */
 $auth = ($app && $is_auth)
-    ? Horde_Auth::singleton('application', array('app' => $app))
-    : Horde_Auth::singleton($conf['auth']['driver']);
+    ? $injector->getInstance('Horde_Auth')->getOb('application', array('app' => $app))
+    : $injector->getInstance('Horde_Auth')->getOb();
 
 /* Build the list of necessary login parameters. */
 $loginparams = array(
index 61371be..b8cdb44 100644 (file)
@@ -11,7 +11,7 @@
 require_once dirname(__FILE__) . '/../lib/Application.php';
 Horde_Registry::appInit('horde', array('authentication' => 'none'));
 
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
 
 // Check for COOKIE auth.
 if (empty($_COOKIE['user']) ||
index 73360ed..0deb228 100644 (file)
@@ -11,7 +11,7 @@
 require_once dirname(__FILE__) . '/../lib/Application.php';
 Horde_Registry::appInit('horde', array('authentication' => 'none'));
 
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
 
 // Check for GET auth.
 if (empty($_GET['user']) ||
index c1e3d88..f333407 100644 (file)
@@ -11,7 +11,7 @@
 require_once dirname(__FILE__) . '/../lib/Application.php';
 Horde_Registry::appInit('horde');
 
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
 
 // Check for HTTP auth.
 if (empty($_SERVER['PHP_AUTH_USER']) ||
index 4fb8b60..1d8c91e 100644 (file)
@@ -12,7 +12,7 @@ require_once dirname(__FILE__) . '/../lib/Application.php';
 Horde_Registry::appInit('horde', array('nologintasks' => true));
 
 // Make sure auth backend allows passwords to be reset.
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
 if (!$auth->hasCapability('update')) {
     $notification->push(_("Changing your password is not supported with the current configuration.  Contact your administrator."), 'horde.error');
     header('Location: ' . Horde::getServiceLink('login')->add('url', Horde_Util::getFormData('url'))->setRaw(true));
index 7dac226..ec063ea 100644 (file)
@@ -12,7 +12,7 @@ require_once dirname(__FILE__) . '/../lib/Application.php';
 Horde_Registry::appInit('horde', array('authentication' => 'none'));
 
 // Make sure auth backend allows passwords to be reset.
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
 if (!$auth->hasCapability('resetpassword')) {
     $notification->push(_("Cannot reset password automatically, contact your administrator."), 'horde.error');
     header('Location: ' . Horde::getServiceLink('login')->add('url', Horde_Util::getFormData('url'))->setRaw(true));
index a5b9e04..95499b7 100644 (file)
@@ -28,7 +28,7 @@ $fieldsList = array(
 $app = Horde_Util::getFormData('app');
 $shares = $GLOBALS['injector']->getInstance('Horde_Share')->getScope($app);
 $groups = Group::singleton();
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
 if ($registry->hasMethod('shareHelp', $app)) {
     $help = $registry->callByPackage($app, 'shareHelp');
 } else {
index 6411db6..4f636ac 100644 (file)
@@ -11,7 +11,7 @@
 require_once dirname(__FILE__) . '/lib/Application.php';
 Horde_Registry::appInit('horde', array('authentication' => 'none'));
 
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
 
 // Make sure signups are enabled before proceeding
 if ($conf['signup']['allow'] !== true ||
index 8db1e9b..7b6e3a7 100644 (file)
@@ -358,8 +358,8 @@ class IMP_Application extends Horde_Registry_Application
             $secret = $GLOBALS['injector']->getInstance('Horde_Secret');
             $params['admin_password'] = $secret->read($secret->getKey('imp'), $params['admin_password']);
         }
-        $auth = Horde_Auth::singleton('imap', $params);
-        $auth->addUser($userId, $credentials);
+
+        $GLOBALS['injector']->getInstance('Horde_Auth')->getOb('imap', $params)->addUser($userId, $credentials);
     }
 
     /**
@@ -381,8 +381,8 @@ class IMP_Application extends Horde_Registry_Application
             $secret = $GLOBALS['injector']->getInstance('Horde_Secret');
             $params['admin_password'] = $secret->read($secret->getKey('imp'), $params['admin_password']);
         }
-        $auth = Horde_Auth::singleton('imap', $params);
-        $auth->removeUser($userId);
+
+        $GLOBALS['injector']->getInstance('Horde_Auth')->getOb('imap', $params)->removeUser($userId);
     }
 
     /**
@@ -403,8 +403,8 @@ class IMP_Application extends Horde_Registry_Application
             $secret = $GLOBALS['injector']->getInstance('Horde_Secret');
             $params['admin_password'] = $secret->read($secret->getKey('imp'), $params['admin_password']);
         }
-        $auth = Horde_Auth::singleton('imap', $params);
-        return $auth->listUsers();
+
+        return $GLOBALS['injector']->getInstance('Horde_Auth')->getOb('imap', $params)->listUsers();
     }
 
     /* Preferences display/handling methods. Code is contained in
index cf8b55d..b9b7d86 100755 (executable)
@@ -64,7 +64,7 @@ require_once dirname(__FILE__) . '/../../lib/Application.php';
 Horde_Registry::appInit('ingo', array('authentication' => 'none', 'cli' => true));
 
 // Initialize authentication manager.
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
 
 // Initialize storage backend.
 $rules_storage = Ingo_Storage::factory();
index dcb74c5..8dcaf67 100644 (file)
@@ -35,7 +35,7 @@ class Koward {
         $this->registry     = &$registry;
         $this->notification = &$notification;
 
-        $this->auth = Horde_Auth::singleton($conf['auth']['driver']);
+        $this->auth = $GLOBALS['injector']->getInstance('Horde_Auth')->getOb();
 
         $this->conf       = Horde::loadConfiguration('conf.php', 'conf');
         $this->objects    = Horde::loadConfiguration('objects.php', 'objects');
index b42f780..74a25a7 100644 (file)
@@ -81,8 +81,7 @@ class Koward_Cli extends Horde_Controller_Request_Base
 
         /* Authenticate the user if possible. */
         if ($this->_argv->user) {
-            require_once 'Horde/Auth.php';
-            $auth = Horde_Auth::singleton($conf['auth']['driver']);
+            $auth = $GLOBALS['injector']->getInstance('Horde_Auth')->getOb();
             if (!$auth->authenticate($this->_argv->user,
                                      array('password' => $this->_argv->pass))) {
                 throw new InvalidArgumentException('Failed to log in!');
index 80662b2..e1bdeec 100644 (file)
@@ -89,15 +89,16 @@ $prefGroups['authentication'] = array(
     'members' => array('credentialsui'),
 );
 
-$auth = Horde_Auth::singleton($GLOBALS['conf']['auth']['driver']);
-if (is_a($auth, 'Auth') && $auth->hasCapability('update')) {
-    $prefGroups['forgotpass'] = array(
-        'column' => _("Your Information"),
-        'label' => _("Account Password"),
-        'desc' => _("Set options to allow you to reset your password if you ever forget it."),
-        'members' => array('security_question', 'security_answer', 'alternate_email')
-    );
-}
+try {
+    if ($GLOBALS['injector']->getInstance('Horde_Auth')->getOb()->hasCapability('update')) {
+        $prefGroups['forgotpass'] = array(
+            'column' => _("Your Information"),
+            'label' => _("Account Password"),
+            'desc' => _("Set options to allow you to reset your password if you ever forget it."),
+            'members' => array('security_question', 'security_answer', 'alternate_email')
+        );
+    }
+} catch (Exception $e) {}
 
 $prefGroups['language'] = array(
     'column' => _("Your Information"),
index dc9fa0f..cae5ec4 100644 (file)
@@ -38,7 +38,7 @@ if (!$share->hasPermission(Horde_Auth::getAuth(), Horde_Perms::READ)) {
                    sprintf(_("Permission denied for the requested feed (%s)."),
                            htmlspecialchars($calendar)));
     } else {
-        $auth = Horde_Auth::singleton($conf['auth']['driver']);
+        $auth = $injector->getInstance('Horde_Auth')->getOb();
         if (isset($_SERVER['PHP_AUTH_USER'])) {
             $user = $_SERVER['PHP_AUTH_USER'];
             $pass = $_SERVER['PHP_AUTH_PW'];
index 39ec58f..982937f 100644 (file)
@@ -1592,7 +1592,7 @@ class Kronolith
      */
     public static function readPermsForm($share)
     {
-        $auth = Horde_Auth::singleton($GLOBALS['conf']['auth']['driver']);
+        $auth = $GLOBALS['injector']->getInstance('Horde_Auth')->getOb();
         $perm = $share->getPermission();
         $errors = array();
 
index f571fd8..f1b99ca 100644 (file)
@@ -21,7 +21,7 @@ if (!empty($conf['share']['no_sharing'])) {
 
 $shares = $GLOBALS['injector']->getInstance('Horde_Share')->getScope();
 $groups = Group::singleton();
-$auth = Horde_Auth::singleton($conf['auth']['driver']);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
 
 $reload = false;
 $actionID = Horde_Util::getFormData('actionID', 'edit');
@@ -41,7 +41,7 @@ case 'edit':
             $perm = $share->getPermission();
         }
     }
-    
+
     if (!Horde_Auth::getAuth() ||
         (isset($share) &&
          !Horde_Auth::isAdmin() &&
index ff360c5..d79f7dd 100644 (file)
@@ -1,5 +1,5 @@
 <?php
-$auth = Horde_Auth::singleton($GLOBALS['conf']['auth']['driver']);
+$auth = $GLOBALS['injector']->getInstance('Horde_Auth')->getOb();
 require_once 'Horde/Group.php';
 $horde_groups = Group::singleton();
 if (!empty($GLOBALS['conf']['share']['any_group'])) {
index f185480..f8886cf 100755 (executable)
@@ -33,8 +33,7 @@ if (!$sure) {
 // get the list of all users if we can.  If your site
 // has a *large* number of users, you may want to comment
 // out this section to avoid unnecessary overhead.
-$authDriver = $conf['auth']['driver'];
-$auth = Horde_Auth::singleton($authDriver);
+$auth = $injector->getInstance('Horde_Auth')->getOb();
 if ($auth->hasCapability('list')) {
     $users = $auth->listUsers();
 }
index 8ff93eb..98242f4 100644 (file)
@@ -22,7 +22,7 @@ class AddUserForm extends Horde_Form {
 
         global $conf, $whups_driver;
 
-        $auth = Horde_Auth::singleton($conf['auth']['driver']);
+        $auth = $GLOBALS['injector']->getInstance('Horde_Auth')->getOb();
         if ($auth->hasCapability('list')) {
             $queue = $vars->get('queue');
             $current = $whups_driver->getQueueUsers($queue);
index 661070a..e831611 100644 (file)
@@ -208,9 +208,7 @@ class Whups_Mail {
      */
     static protected function _findAuthUser($from)
     {
-        global $conf;
-
-        $auth = Horde_Auth::singleton($conf['auth']['driver'], Horde::getDriverConfig('auth', $conf['auth']['driver']));
+        $auth = $GLOBALS['injector']->getInstance('Horde_Auth')->getOb();
 
         if ($auth->hasCapability('list')) {
             foreach ($auth->listUsers() as $user) {
index c538c5d..566aeb2 100755 (executable)
@@ -77,7 +77,7 @@ foreach ($opts as $opt) {
 
 // Login to horde if username & password are set.
 if (!empty($username) && !empty($password)) {
-    $auth = Horde_Auth::singleton($conf['auth']['driver']);
+    $auth = $injector->getInstance('Horde_Auth')->getOb();
     if (!$auth->authenticate($username, array('password' => $password))) {
         $error = _("Login is incorrect.");
         Horde::logMessage($error, 'ERR');