Add Horde_Prefs_Exception::.
} elseif ($owner == $GLOBALS['registry']->getAuth()) {
$owner_title = _("My Galleries");
} elseif (!empty($GLOBALS['conf']['gallery']['customlabel'])) {
- $uprefs = Horde_Prefs::singleton($GLOBALS['conf']['prefs']['driver'],
- 'ansel',
- $owner, '', null, false);
+ $uprefs = $GLOBALS['injector']->getInstance('Horde_Prefs')->getPrefs('ansel', array(
+ 'cache' => false,
+ 'user' => $owner
+ ));
$fullname = $uprefs->getValue('grouptitle');
if (!$fullname) {
$identity = $GLOBALS['injector']->getInstance('Horde_Prefs_Identity')->getIdentity($owner);
if ($this->_owner == $GLOBALS['registry']->getAuth() && empty($this->_params['api'])) {
return _("My Galleries");
} elseif (!empty($GLOBALS['conf']['gallery']['customlabel'])) {
- $uprefs = Horde_Prefs::singleton($GLOBALS['conf']['prefs']['driver'],
- 'ansel', $this->_owner, '', null, false);
+ $uprefs = $GLOBALS['injector']->getInstance('Horde_Prefs')->getPrefs('ansel', array(
+ 'cache' => false,
+ 'owner' => $this->_owner
+ ));
$fullname = $uprefs->getValue('grouptitle');
if (!$fullname) {
$identity = $GLOBALS['injector']->getInstance('Horde_Prefs_Identity')->getIdentity($this->_owner);
$owner_title = _("My Galleries");
$custom = '';
} elseif (!empty($GLOBALS['conf']['gallery']['customlabel'])) {
- $uprefs = Horde_Prefs::singleton($GLOBALS['conf']['prefs']['driver'],
- 'ansel',
- $group, '', null, false);
+ $uprefs = $injector->getInstance('Horde_Prefs')->getPrefs('ansel', array(
+ 'cache' => false,
+ 'user' => $group
+ ));
$custom = $uprefs->getValue('grouptitle');
$identity = new Horde_Prefs_Identity(array('prefs' => $GLOBALS['prefs'], 'user' => $group));
$fullname = $identity->getValue('fullname');
// Get user security pass
$user = Horde_Util::getFormData('username');
if ($user) {
- $u_prefs = Horde_Prefs::singleton($conf['prefs']['driver'], 'horde', $registry->convertUsername($user, true), '', null, false);
- $u_prefs->retrieve();
+ $u_prefs = $injector->getInstance('Horde_Prefs')->getPrefs('horde', array(
+ 'cache' => false,
+ 'user' => $registry->convertUsername($user, true)
+ ));
$answer = $u_prefs->getValue('security_answer');
$question = $u_prefs->getValue('security_question');
} else {
return (boolean)$GLOBALS['prefs']->getValue('friends_approval');
}
- $prefs = Horde_Prefs::singleton($GLOBALS['conf']['prefs']['driver'], 'folks', $registry->convertUsername($user, true), '', null, false);
- $prefs->retrieve();
+ $prefs = $GLOBALS['injector']->getInstance('Horde_Prefs')->getPrefs('folks', array(
+ 'cache' => false,
+ 'user' => $GLOBALS['registry']->convertUsername($user, true)
+ ));
return (boolean)$prefs->getValue('friends_approval');
}
$user = $GLOBALS['registry']->getAuth();
}
- $u_prefs = Horde_Prefs::singleton($GLOBALS['conf']['prefs']['driver'], $GLOBALS['registry']->getApp(), $user);
- $u_prefs->retrieve();
+ $u_prefs = $GLOBALS['injector']->getInstance('Horde_Prefs')->getPrefs($GLOBALS['registry']->getApp(), array(
+ 'user' => $user
+ ));
$list = $u_prefs->getValue($type);
--- /dev/null
+<?php
+/**
+ * @category Horde
+ * @package Core
+ */
+class Horde_Core_Binder_Prefs implements Horde_Injector_Binder
+{
+ public function create(Horde_Injector $injector)
+ {
+ return new Horde_Core_Factory_Prefs($injector);
+ }
+
+ public function equals(Horde_Injector_Binder $binder)
+ {
+ return false;
+ }
+}
*/
public function getIdentity($user = null, $driver = null)
{
+ global $injector, $prefs, $registry;
+
$class = empty($driver)
? 'Horde_Prefs_Identity'
: Horde_String::ucfirst($driver) . '_Prefs_Identity';
}
$params = array(
- 'user' => is_null($user) ? $GLOBALS['registry']->getAuth() : $user,
+ 'user' => is_null($user) ? $registry->getAuth() : $user,
);
- if (isset($GLOBALS['prefs']) &&
- ($params['user'] == $GLOBALS['registry']->getAuth())) {
- $params['prefs'] = $GLOBALS['prefs'];
+ if (isset($prefs) && ($params['user'] == $registry->getAuth())) {
+ $params['prefs'] = $prefs;
} else {
- $params['prefs'] = Horde_Prefs::singleton($GLOBALS['conf']['prefs']['driver'], $GLOBALS['registry']->getApp(), $user, '', null, false);
+ $params['prefs'] = $injector->getInstance('Horde_Prefs')->getPrefs($registry->getApp(), array(
+ 'cache' => false,
+ 'user' => $user
+ ));
$params['prefs']->retrieve();
}
--- /dev/null
+<?php
+/**
+ * A Horde_Injector:: based Horde_Prefs:: 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_Prefs:: 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_Prefs
+{
+ /**
+ * Instances.
+ *
+ * @var array
+ */
+ private $_instances = array();
+
+ /**
+ * The injector.
+ *
+ * @var Horde_Injector
+ */
+ private $_injector;
+
+ /**
+ * Constructor.
+ *
+ * @param Horde_Injector $injector The injector to use.
+ */
+ public function __construct(Horde_Injector $injector)
+ {
+ $this->_injector = $injector;
+ }
+
+ /**
+ * Return the Horde_Prefs:: instance.
+ *
+ * @param string $scope The scope for this set of preferences. 'session'
+ * will load a session prefs instance.
+ * @param array $opts See Horde_Prefs::factory(). Additional options:
+ * <pre>
+ * 'session' - (boolean) Use the session driver.
+ * DEFAULT: false
+ * </pre>
+ *
+ * @return Horde_Prefs The singleton instance.
+ */
+ public function getPrefs($scope = 'horde', array $opts = array())
+ {
+ if (empty($GLOBALS['conf']['prefs']['driver']) ||
+ !empty($opts['session'])) {
+ $driver = 'Session';
+ $params = array();
+ unset($opts['session']);
+ } else {
+ $driver = ucfirst($GLOBALS['conf']['prefs']['driver']);
+ $params = Horde::getDriverConfig('prefs', $driver);
+ }
+
+ $opts = array_merge(array(
+ 'cache' => true,
+ 'charset' => $GLOBALS['registry']->getCharset(),
+ 'logger' => $this->_injector->getInstance('Horde_Log_Logger'),
+ 'password' => '',
+ 'sizecallback' => ((isset($GLOBALS['conf']['prefs']['maxsize'])) ? array($this, 'sizeCallback') : null),
+ 'uicharset' => $GLOBALS['registry']->getCharset(),
+ 'user' => ''
+ ), $opts);
+ ksort($opts);
+
+ /* If $params['user_hook'] is defined, use it to retrieve the value to
+ * use for the username. */
+ if (!empty($params['user_hook']) &&
+ function_exists($params['user_hook'])) {
+ $opts['user'] = call_user_func($params['user_hook'], $opts['user']);
+ }
+
+ $sig = hash('md5', serialize($opts));
+
+ if (isset($this->_instances[$sig])) {
+ $this->_instances[$sig]->setScope($scope);
+ } else {
+ switch ($driver) {
+ case 'Sql':
+ $params['db'] = $this->_injector->getInstance('Horde_Db')->getDb();
+ // @todo All DB's use UTF-8(?) Does not seem to be a way to
+ // get this information from Horde_Db_Adapter_Base.
+ $opts['charset'] = 'UTF-8';
+ break;
+ }
+
+ try {
+ $this->_instances[$sig] = Horde_Prefs::factory($driver, $scope, $opts, $params);
+ } catch (Horde_Prefs_Exception $e) {
+ if (empty($_SESSION['prefs_cache']['unavailable'])) {
+ $_SESSION['prefs_cache']['unavailable'] = true;
+ if (isset($GLOBALS['notification'])) {
+ $GLOBALS['notification']->push(_("The preferences backend is currently unavailable and your preferences have not been loaded. You may continue to use the system with default settings."));
+ }
+ }
+ $this->_instances[$sig] = Horde_Prefs::factory('Session', $scope);
+ }
+ }
+
+ return $this->_instances[$sig];
+ }
+
+ /**
+ * Clear the instances cache.
+ */
+ public function clearCache()
+ {
+ $this->_instances = array();
+ }
+
+ /**
+ * Max size callback.
+ *
+ * @param string $pref Preference name.
+ * @param integer $size Size (in bytes).
+ *
+ * @return boolean True if oversized.
+ */
+ public function sizeCallback($pref, $size)
+ {
+ if ($size <= $GLOBALS['conf']['prefs']['maxsize']) {
+ return false;
+ }
+
+ $GLOBALS['notification']->push(sprintf(_("The preference \"%s\" could not be saved because its data exceeds the maximum allowable size"), $pref), 'horde.error');
+ return true;
+ }
+
+}
'Horde_Memcache' => new Horde_Core_Binder_Memcache(),
'Horde_Notification' => new Horde_Core_Binder_Notification(),
'Horde_Perms' => new Horde_Core_Binder_Perms(),
+ 'Horde_Prefs' => new Horde_Core_Binder_Prefs(),
'Horde_Prefs_Identity' => new Horde_Core_Binder_Identity(),
// 'Horde_Registry' - initialized below
'Horde_Secret' => new Horde_Core_Binder_Secret(),
*/
public function loadPrefs($app = null)
{
+ global $injector, $prefs;
+
if (is_null($app)) {
$app = $this->getApp();
} else {
$this->pushApp($app);
}
- /* If there is no logged in user, return an empty Horde_Prefs::
- * object with just default preferences. */
- if (!$this->getAuth()) {
- $GLOBALS['prefs'] = Horde_Prefs::factory('Session', $app, '', '', null, false);
- } else {
- if (!isset($GLOBALS['prefs']) ||
- ($GLOBALS['prefs']->getUser() != $this->getAuth())) {
- $GLOBALS['prefs'] = Horde_Prefs::factory($GLOBALS['conf']['prefs']['driver'], $app, $this->getAuth(), $this->getAuthCredential('password'));
- } else {
- $GLOBALS['prefs']->retrieve($app);
+ if ($this->getAuth()) {
+ if (isset($prefs) && ($prefs->getUser() == $this->getAuth())) {
+ $prefs->retrieve($app);
+ return;
}
- }
- }
- /**
- * Unload preferences from an application or (if no application is
- * specified) from ALL applications. Useful when a user has logged
- * out but you need to continue on the same page, etc.
- *
- * After unloading, if there is an application on the app stack to
- * load preferences from, then we reload a fresh set.
- *
- * @param string $app The application to unload prefrences for. If null,
- * ALL preferences are reset.
- */
- public function unloadPrefs($app = null)
- {
- // TODO: $app not being used?
- if ($this->getApp()) {
- $this->loadPrefs();
+ $opts = array(
+ 'password' => $this->getAuthCredential('password'),
+ 'user' => $this->getAuth()
+ );
+ } else {
+ /* If there is no logged in user, return an empty Horde_Prefs::
+ * object with just default preferences. */
+ $opts = array(
+ 'cache' => false,
+ 'session' => true
+ );
}
+
+ $prefs = $injector->getInstance('Horde_Prefs')->getPrefs($app, $opts);
}
/**
unset($_SESSION['horde_auth']);
/* Remove the user's cached preferences if they are present. */
- $this->unloadPrefs();
+ $GLOBALS['injector']->getInstance('Horde_Prefs')->clearCache();
if ($destroy) {
session_destroy();
return;
}
- /* Clear any existing info. */
- $this->clearAuth(false);
-
$_SESSION['horde_auth'] = array(
'app' => array(),
'authId' => $authId,
$this->setAuthCredential($credentials, null, $app);
/* Reload preferences for the new user. */
+ unset($GLOBALS['prefs']);
+ $GLOBALS['injector']->getInstance('Horde_Prefs')->clearCache();
$this->loadPrefs();
+
$this->setLanguageEnvironment($GLOBALS['prefs']->getValue('language'), $app);
}
<file name="Memcache.php" role="php" />
<file name="Notification.php" role="php" />
<file name="Perms.php" role="php" />
+ <file name="Prefs.php" role="php" />
<file name="Secret.php" role="php" />
<file name="SessionHandler.php" role="php" />
<file name="Share.php" role="php" />
<file name="KolabStorage.php" role="php" />
<file name="Ldap.php" role="php" />
<file name="LoginTasks.php" role="php" />
+ <file name="Prefs.php" role="php" />
<file name="Request.php" role="php" />
<file name="Share.php" role="php" />
<file name="TextFilter.php" role="php" />
<install as="Horde/Core/Binder/Memcache.php" name="lib/Horde/Core/Binder/Memcache.php" />
<install as="Horde/Core/Binder/Notification.php" name="lib/Horde/Core/Binder/Notification.php" />
<install as="Horde/Core/Binder/Perms.php" name="lib/Horde/Core/Binder/Perms.php" />
+ <install as="Horde/Core/Binder/Prefs.php" name="lib/Horde/Core/Binder/Prefs.php" />
<install as="Horde/Core/Binder/Secret.php" name="lib/Horde/Core/Binder/Secret.php" />
<install as="Horde/Core/Binder/SessionHandler.php" name="lib/Horde/Core/Binder/SessionHandler.php" />
<install as="Horde/Core/Binder/Share.php" name="lib/Horde/Core/Binder/Share.php" />
<install as="Horde/Core/Factory/KolabStorage.php" name="lib/Horde/Core/Factory/KolabStorage.php" />
<install as="Horde/Core/Factory/Ldap.php" name="lib/Horde/Core/Factory/Ldap.php" />
<install as="Horde/Core/Factory/LoginTasks.php" name="lib/Horde/Core/Factory/LoginTasks.php" />
+ <install as="Horde/Core/Factory/Prefs.php" name="lib/Horde/Core/Factory/Prefs.php" />
<install as="Horde/Core/Factory/Request.php" name="lib/Horde/Core/Factory/Request.php" />
<install as="Horde/Core/Factory/Share.php" name="lib/Horde/Core/Factory/Share.php" />
<install as="Horde/Core/Factory/TextFilter.php" name="lib/Horde/Core/Factory/TextFilter.php" />
const PREFS_DEFAULT = 8;
/**
- * Singleton instances.
+ * Connection parameters.
*
* @var array
*/
- static protected $_instances = array();
+ protected $_params = array();
/**
* Hash holding the current set of preferences. Each preference is
protected $_scopes = array();
/**
- * String containing the current username. This indicates the owner of the
- * preferences.
+ * General library options.
*
- * @var string
- */
- protected $_user = '';
-
- /**
- * Boolean indicating whether preference caching should be used.
- *
- * @var boolean
+ * @var array
*/
- protected $_caching = false;
+ protected $_opts = array(
+ 'cache' => false,
+ 'logger' => null,
+ 'password' => '',
+ 'sizecallback' => null,
+ 'user' => ''
+ );
/**
* Array to cache in. Usually a reference to an array in $_SESSION, but
protected $_hooks = array();
/**
- * 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 should be used if multiple preference sources (and, thus,
- * multiple instances) are required.
- *
- * @param mixed $driver The type of concrete subclass to return.
- * @param string $scope The scope for this set of preferences.
- * @param string $user The name of the user who owns this set of
- * preferences.
- * @param string $password The password associated with $user.
- * @param array $params A hash containing any additional configuration
- * or connection parameters a subclass might need.
- * @param boolean $caching Should caching be used?
- *
- * @return Horde_Prefs The concrete reference, or false on an error.
- * @throws Horde_Exception
- */
- static public function singleton($driver, $scope = 'horde', $user = '',
- $password = '', $params = null,
- $caching = true)
- {
- if (is_null($params)) {
- $params = Horde::getDriverConfig('prefs', $driver);
- }
-
- $signature = serialize(array($driver, $user, $params, $caching));
- if (!isset(self::$_instances[$signature])) {
- self::$_instances[$signature] = self::factory($driver, $scope, $user, $password, $params, $caching);
- }
-
- /* Preferences may be cached with a different scope. */
- self::$_instances[$signature]->setScope($scope);
-
- return self::$_instances[$signature];
- }
-
- /**
* Attempts to return a concrete instance based on $driver.
*
- * @param mixed $driver The type of concrete subclass to return.
- * @param string $scope The scope for this set of preferences.
- * @param string $user The name of the user who owns this set of
- * preferences.
- * @param string $password The password associated with $user.
- * @param array $params A hash containing any additional configuration
- * or connection parameters a subclass might need.
- * @param boolean $caching Should caching be used?
+ * @param mixed $driver The type of concrete subclass to return.
+ * @param string $scope The scope for this set of preferences.
+ * @param array $opts Additional options:
+ * <pre>
+ * 'cache' - (boolean) Should caching be used?
+ * DEFAULT: false
+ * 'charset' - (string) Default charset. [REQUIRED]
+ * 'logger' - (Horde_Log_Logger) Logging object.
+ * DEFAULT: NONE
+ * 'password' - (string) The password associated with 'user'.
+ * DEFAULT: NONE
+ * 'sizecallback' - (callback) If set, called when setting a value in
+ * the backend.
+ * DEFAULT: NONE
+ * 'uicharset' - (string) UI charset. [REQUIRED]
+ * 'user' - (string) The name of the user who owns this set of
+ * preferences.
+ * DEFAULT: NONE
+ * </pre>
+ * @param array $params A hash containing any additional configuration
+ * or connection parameters a subclass might need.
*
* @return Horde_Prefs The newly created concrete instance.
- * @throws Horde_Exception
+ * @throws Horde_Prefs_Exception
*/
- static public function factory($driver, $scope = 'horde', $user = '',
- $password = '', $params = null,
- $caching = true)
+ static public function factory($driver, $scope, array $opts = array(),
+ array $params = array())
{
$driver = ucfirst(basename($driver));
- if (empty($driver) || $driver == 'None') {
- $driver = 'Session';
- }
-
$class = __CLASS__ . '_' . $driver;
- if (!class_exists($class)) {
- throw new Horde_Exception('Class definition of ' . $class . ' not found.');
- }
-
- if (is_null($params)) {
- $params = Horde::getDriverConfig('prefs', strtolower($driver));
- }
- /* If $params['user_hook'] is defined, use it to retrieve the value to
- * use for the username ($this->_user). Otherwise, just use the value
- * passed in the $user parameter. */
- if (!empty($params['user_hook']) &&
- function_exists($params['user_hook'])) {
- $user = call_user_func($params['user_hook'], $user);
+ if (!class_exists($class)) {
+ throw new Horde_Prefs_Exception(__CLASS__ . ': class definition not found - ' . $class);
}
- $prefs = new $class($scope, $user, $password, $params, $caching);
+ $prefs = new $class($scope, $opts, $params);
$prefs->retrieve($scope);
return $prefs;
/**
* Constructor.
*
- * @param string $scope The scope for this set of preferences.
- * @param string $user The name of the user who owns this set of
- * preferences.
- * @param string $password The password associated with $user.
- * @param array $params A hash containing any additional configuration
- * or connection parameters a subclass might need.
- * @param boolean $caching Should caching be used?
+ * @param string $scope The scope for this set of preferences.
+ * @param array $opts See factory() for list of options.
+ * @param array $params A hash containing any additional configuration
+ * or connection parameters a subclass might need.
*
+ * @throws InvalidArgumentException
*/
- protected function __construct($scope, $user, $password, $params, $caching)
+ protected function __construct($scope, $opts, $params)
{
- register_shutdown_function(array($this, 'store'));
+ foreach (array('charset', 'uicharset') as $val) {
+ if (!isset($opts[$val])) {
+ throw new InvalidArgumentException('Missing ' . $val . ' parameter.');
+ }
+ }
- $this->_user = $user;
- $this->_password = $password;
- $this->_scope = $scope;
+ $this->_opts = array_merge($this->_opts, $opts);
$this->_params = $params;
- $this->_caching = $caching;
+ $this->_scope = $scope;
// Create a unique key that's safe to use for caching even if we want
// another user's preferences later, then register the cache array in
// $_SESSION.
- if ($this->_caching) {
- $cacheKey = 'horde_prefs_' . hash('sha1', $this->_user);
+ if ($this->_opts['cache']) {
+ $cacheKey = 'horde_prefs_' . $this->getUser();
// Store a reference to the $_SESSION array.
$this->_cache = &$_SESSION[$cacheKey];
}
+
+ register_shutdown_function(array($this, 'store'));
}
/**
*/
public function getCharset()
{
- return $GLOBALS['registry']->getCharset();
+ return $this->_opts['charset'];
}
/**
*/
public function getUser()
{
- return $this->_user;
+ return $this->_opts['user'];
}
/**
$result = $this->_setValue($pref, $val, true, $convert);
- Horde::logMessage(__CLASS__ . ': Storing preference value (' . $pref . ')', 'DEBUG');
+ if ($this->_opts['logger']) {
+ $this->_opts['logger']->log(__CLASS__ . ': Storing preference value (' . $pref . ')', 'DEBUG');
+ }
if ($result && $this->isDirty($pref)) {
$scope = $this->_getPreferenceScope($pref);
global $conf;
if ($convert) {
- $val = $this->convertToDriver($val, $GLOBALS['registry']->getCharset());
+ $val = $this->convertToDriver($val);
}
// If the preference's value is already equal to $val, don't
// Check to see if the value exceeds the allowable storage
// limit.
- if (isset($GLOBALS['conf']['prefs']['maxsize']) &&
- (strlen($val) > $GLOBALS['conf']['prefs']['maxsize']) &&
- isset($GLOBALS['notification'])) {
- $GLOBALS['notification']->push(sprintf(_("The preference \"%s\" could not be saved because its data exceeds the maximum allowable size"), $pref), 'horde.error');
+ if ($this->_opts['sizecallback'] &&
+ call_user_func($this->_opts['sizecallback'], $pref, strlen($val))) {
return false;
}
/* Default values have the current UI charset.
* Stored values have the backend charset. */
$value = $this->isDefault($pref)
- ? Horde_String::convertCharset($this->_prefs[$pref]['v'], $GLOBALS['registry']->getCharset(), $GLOBALS['registry']->getCharset())
- : $this->convertFromDriver($this->_prefs[$pref]['v'], $GLOBALS['registry']->getCharset());
+ ? $this->_prefs[$pref]['v']
+ : $this->convertFromDriver($this->_prefs[$pref]['v']);
} else {
$value = $this->_prefs[$pref]['v'];
}
*/
protected function _getPreferenceScope($pref)
{
- return $this->isShared($pref) ? 'horde' : $this->_scope;
+ return $this->isShared($pref) ? 'horde' : $this->getScope();
}
/**
public function retrieve($scope = null)
{
if (is_null($scope)) {
- $scope = $this->_scope;
+ $scope = $this->getScope();
} else {
- $this->_scope = $scope;
+ $this->setScope($scope);
}
$this->_loadScope('horde');
unset($this->_cache);
} else {
/* Remove this scope from the preferences cache, if it exists. */
- unset($this->_cache[$this->_scope]);
+ unset($this->_cache[$this->getScope()]);
}
}
/**
* Converts a value from the driver's charset to the specified charset.
*
- * @param mixed $value A value to convert.
- * @param string $charset The charset to convert to.
+ * @param mixed $value A value to convert.
*
* @return mixed The converted value.
*/
- public function convertFromDriver($value, $charset)
+ public function convertFromDriver($value)
{
- return $value;
+ return is_bool($value)
+ ? $value
+ : Horde_String::convertCharset($value, $this->getCharset(), $this->_opts['uicharset']);
}
/**
* Converts a value from the specified charset to the driver's charset.
*
- * @param mixed $value A value to convert.
- * @param string $charset The charset to convert from.
+ * @param mixed $value A value to convert.
*
* @return mixed The converted value.
*/
- public function convertToDriver($value, $charset)
+ public function convertToDriver($value)
{
- return $value;
+ return is_bool($value)
+ ? $value
+ : Horde_String::convertCharset($value, $this->_opts['uicharset'], $this->getCharset());
}
/**
*/
protected function _cacheUpdate($scope, $prefs)
{
- if ($this->_caching && isset($this->_cache)) {
+ if ($this->_opts['cache'] && isset($this->_cache)) {
/* Place each preference in the cache according to its
* scope. */
foreach ($prefs as $name) {
*/
protected function _cacheLookup($scope)
{
- if ($this->_caching && isset($this->_cache[$scope])) {
+ if ($this->_opts['cache'] && isset($this->_cache[$scope])) {
$this->_scopes[$scope] = $this->_cache[$scope];
return true;
}
$this->_scopes[$pref_scope][$name]['m'] & self::PREFS_DEFAULT) {
try {
- $val = Horde::callHook('prefs_hook_' . $name, array($this->_user), $scope);
+ $val = Horde::callHook('prefs_hook_' . $name, array($this->getUser()), $scope);
} catch (Horde_Exception_HookNotSet $e) {
continue;
}
if ($this->_scopes[$pref_scope][$name]['m'] & self::PREFS_DEFAULT) {
$this->_scopes[$pref_scope][$name]['v'] = $val;
} else {
- $this->_scopes[$pref_scope][$name]['v'] = $this->convertToDriver($val, $GLOBALS['registry']->getCharset());
+ $this->_scopes[$pref_scope][$name]['v'] = $this->convertToDriver($val);
}
if (!($this->_scopes[$pref_scope][$name]['m'] & self::LOCKED)) {
$this->_scopes[$pref_scope][$name]['m'] |= self::DIRTY;
--- /dev/null
+<?php
+/**
+ * Exception handler for the Prefs package.
+ *
+ * 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.
+ *
+ * @author Michael Slusarz <slusarz@horde.org>
+ * @category Horde
+ * @license http://www.fsf.org/copyleft/lgpl.html LGPL
+ * @package Prefs
+ */
+class Horde_Prefs_Exception extends Horde_Exception_Prior
+{
+}
* @category Horde
* @package Prefs
*/
-class Horde_Prefs_File extends Horde_Prefs
+class Horde_Prefs_File extends Horde_Prefs_Base
{
/**
* Current version number of the data format
/**
* Constructor.
*
- * @param string $scope The current preferences scope.
- * @param string $user The user who owns these preferences.
- * @param string $password The password associated with $user. (Unused)
- * @param array $params A hash containing connection parameters.
- * @param boolean $caching Should caching be used?
+ * @param string $scope The scope for this set of preferences.
+ * @param array $opts See factory() for list of options.
+ * @param array $params Additional parameters:
+ * <pre>
+ * 'directory' - (string) [REQUIRED] Preference storage directory.
+ * </pre>
+ *
+ * @throws InvalidArgumentException
*/
- public function __construct($scope, $user, $password, $params, $caching)
+ public function __construct($scope, $opts, $params);
{
- parent::__construct($scope, $user, $password, $params, $caching);
+ parent::__construct($scope, $opts, $params);
// Sanity check for directory
- $error = false;
if (empty($params['directory']) || !is_dir($params['directory'])) {
- Horde::logMessage(_("Preference storage directory is not available."), 'ERR');
- $error = true;
- } elseif (!is_writable($params['directory'])) {
- Horde::logMessage(sprintf(_("Directory %s is not writeable"), $params['directory']), 'ERR');
- $error = true;
+ throw new InvalidArgumentException('Preference storage directory is not available.');
}
-
- if ($error) {
- $this->_dirname = null;
- $this->_fullpath = null;
-
- if (isset($GLOBALS['notification'])) {
- $GLOBALS['notification']->push(_("The preferences backend is currently unavailable and your preferences have not been loaded. You may continue to use the system with default settings."));
- }
- } else {
- $this->_dirname = $params['directory'];
- $this->_fullpath = $this->_dirname . '/' . basename($user) . '.prefs';
+ if (!is_writable($params['directory'])) {
+ throw new InvalidArgumentException(sprintf('Directory %s is not writeable.', $params['directory']));
}
+
+ $this->_dirname = $params['directory'];
+ $this->_fullpath = $this->_dirname . '/' . basename($user) . '.prefs';
}
/**
*
* @param string $scope Scope specifier.
*
- * @throws Horde_Exception
+ * @throws Horde_Prefs_Exception
*/
protected function _retrieve($scope)
{
if ($this->_fileCache['__file_version'] == 1) {
$this->transformV1V2();
} else {
- throw new Horde_Exception(sprintf('Wrong version number found: %s (should be %d)', $this->_fileCache['__file_version'], $this->_version));
+ throw new Horde_Prefs_Exception(sprintf('Wrong version number found: %s (should be %d)', $this->_fileCache['__file_version'], $this->_version));
}
}
}
* Stores preferences in the current session.
*
* @return boolean True on success.
- * @throws Horde_Exception
+ * @throws Horde_Prefs_Exception
*/
public function store()
{
}
if ($this->_writeCache() == false) {
- throw new Horde_Exception(sprintf('Write of preferences to %s failed', $this->_filename));
+ throw new Horde_Prefs_Exception(sprintf('Write of preferences to %s failed', $this->_filename));
}
return true;
if (!($this->_identities = @unserialize($this->_prefs->getValue('identities', false)))) {
$this->_identities = $this->_prefs->getDefault('identities');
} else {
- $this->_identities = $this->_prefs->convertFromDriver($this->_identities, $GLOBALS['registry']->getCharset());
+ $this->_identities = $this->_prefs->convertFromDriver($this->_identities);
}
$this->setDefault($this->_prefs->getValue('default_identity'));
{
$identities = $this->_identities;
if (is_array($identities)) {
- $identities = $this->_prefs->convertToDriver($identities, $GLOBALS['registry']->getCharset());
+ $identities = $this->_prefs->convertToDriver($identities);
}
$this->_prefs->setValue('identities', serialize($identities), false);
$pref = @unserialize($this->_prefs->getValue('confirm_email', false));
$pref = $pref
- ? $this->_prefs->convertFromDriver($pref, $GLOBALS['registry']->getCharset())
+ ? $this->_prefs->convertFromDriver($pref)
: array();
$pref[$hash] = $this->get($id);
- $pref = $this->_prefs->convertToDriver($pref, $GLOBALS['registry']->getCharset());
+ $pref = $this->_prefs->convertToDriver($pref);
$this->_prefs->setValue('confirm_email', serialize($pref), false);
$new_addr = $this->getValue('from_addr', $id);
return array(_("Email addresses to confirm not found."), 'horde.message');
}
- $identity = $this->_prefs->convertFromDriver($confirm[$hash], $GLOBALS['registry']->getCharset());
+ $identity = $this->_prefs->convertFromDriver($confirm[$hash]);
$id = array_search($identity['id'], $this->getAll('id'));
if ($id === false) {
/* Adding a new identity. */
* @category Horde
* @package Prefs
*/
-class Horde_Prefs_Imsp extends Horde_Prefs
+class Horde_Prefs_Imsp extends Horde_Prefs_Base
{
/**
* Handle for the IMSP server connection.
protected $_imsp;
/**
- * User password.
- *
- * @var string
- */
- protected $_password;
-
- /**
* Boolean indicating whether or not we're connected to the IMSP server.
*
* @var boolean
protected $_connected = false;
/**
- * Holds the driver specific parameters.
- *
- * @var array
- */
- protected $_params = array();
-
- /**
* Retrieves the requested set of preferences from the IMSP server.
*
* @param string $scope Scope specifier.
*
- * @throws Horde_Exception
+ * @throws Horde_Prefs_Exception
*/
protected function _retrieve($scope)
{
- /* Now connect to the IMSP server. */
- try {
- $this->_connect();
- } catch (Horde_Exception $e) {
- if (empty($_SESSION['prefs_cache']['unavailable'])) {
- $_SESSION['prefs_cache']['unavailable'] = true;
- $GLOBALS['notification']->push(_("The preferences backend is currently unavailable and your preferences have not been loaded. You may continue to use the system with default settings."));
- }
- return;
- }
+ $this->_connect();
$prefs = $this->_imsp->get($scope . '.*');
if ($prefs instanceof PEAR_Error) {
- Horde::logMessage($prefs, 'ERR');
+ if ($this->_opts['logger']) {
+ $this->_opts['logger']->log($prefs, 'ERR');
+ }
return;
}
$result = $this->_imsp->set($scope . '.' . $name, $value);
if ($result instanceof PEAR_Error) {
- Horde::logMessage($result, 'ERR');
+ if ($this->_opts['logger']) {
+ $this->_opts['logger']->log($result, 'ERR');
+ }
return;
}
/**
* Attempts to set up a connection to the IMSP server.
*
- * @throws Horde_Exception
+ * @throws Horde_Prefs_Exception
*/
protected function _connect()
{
return;
}
- $this->_params['username'] = preg_match('/(^.*)@/', $this->_user, $matches)
+ $this->_params['username'] = preg_match('/(^.*)@/', $this->getUser(), $matches)
? $matches[1]
- : $this->_user;
- $this->_params['password'] = $this->_password;
+ : $this->getUser();
+ $this->_params['password'] = $this->_opts['password'];
if (isset($this->_params['socket'])) {
$this->_params['socket'] = $params['socket'] . 'imsp_' . $this->_params['username'] . '.sck';
$this->_imsp = Net_IMSP::factory('Options', $this->_params);
$result = $this->_imsp->init();
if ($result instanceof PEAR_Error) {
- Horde::logMessage($result, 'ERR');
- throw new Horde_Exception_Prior($result);
+ if ($this->_opts['logger']) {
+ $this->_opts['logger']->log($result, 'ERR');
+ }
+ throw new Horde_Prefs_Exception($result);
}
- $this->_imsp->setLogger($GLOBALS['conf']['log']);
+ // TODO
+ //$this->_imsp->setLogger($GLOBALS['conf']['log']);
$this->_connected = true;
}
*/
class Horde_Prefs_Kolab extends Horde_Prefs_Ldap
{
- /**
+ /**
* Constructor.
*
- * @param string $scope The current application scope.
- * @param string $user The user who owns these preferences.
- * @param string $password The password associated with $user.
- * @param array $params A hash containing connection parameters.
- * @param boolean $caching Should caching be used?
+ * @param string $scope The scope for this set of preferences.
+ * @param array $opts See factory() for list of options.
+ * @param array $params A hash containing any additional configuration
+ * or connection parameters a subclass might need.
*/
- public function __construct($scope, $user, $password, $params, $caching)
+ protected function __construct($scope, $opts, $params)
{
require_once 'Horde/Kolab.php';
$params = array(
'uid' => 'mail'
);
- parent::__construct($scope, $user, $password, $params, $caching);
+ parent::__construct($scope, $opts, $params);
}
}
* @category Horde
* @package Prefs
*/
-class Horde_Prefs_KolabImap extends Horde_Prefs
+class Horde_Prefs_KolabImap extends Horde_Prefs_Base
{
/**
* ID of the config default share
/**
* Opens a connection to the Kolab server.
*
- * @throws Horde_Exception
+ * @throws Horde_Prefs_Exception
*/
protected function _connect()
{
$shares = $GLOBALS['injector']->getInstance('Horde_Share')->getScope('h-prefs');
$default = $shares->getDefaultShare();
if ($default instanceof PEAR_Error) {
- Horde::logMessage($default, 'ERR');
- throw new Horde_Exception_Prior($default);
+ if ($this->_opts['logger']) {
+ $this->_opts['logger']->log($default, 'ERR');
+ }
+ throw new Horde_Prefs_Exception($default);
}
$this->_share = $default->getName();
require_once 'Horde/Kolab.php';
$connection = new Kolab('h-prefs');
if ($connection instanceof PEAR_Error) {
- Horde::logMessage($connection, 'ERR');
- throw new Horde_Exception_Prior($connection);
+ if ($this->_opts['logger']) {
+ $this->_opts['logger']->log($connection, 'ERR');
+ }
+ throw new Horde_Prefs_Exception($connection);
}
$result = $this->_connection->open($this->_share, 1);
if ($result instanceof PEAR_Error) {
- Horde::logMessage($result, 'ERR');
- throw new Horde_Exception_Prior($result);
+ if ($this->_opts['logger']) {
+ $this->_opts['logger']->log($result, 'ERR');
+ }
+ throw new Horde_Prefs_Exception($result);
}
$this->_connection = $connection;
*
* @param string $scope Scope specifier.
*
- * @throws Horde_Exception
+ * @throws Horde_Prefs_Exception
*/
protected function _retrieve($scope)
{
- try {
- $this->_connect();
- } catch (Horde_Exception $e) {
- if (empty($_SESSION['prefs_cache']['unavailable'])) {
- $_SESSION['prefs_cache']['unavailable'] = true;
- if (isset($GLOBALS['notification'])) {
- $GLOBALS['notification']->push(_("The preferences backend is currently unavailable and your preferences have not been loaded. You may continue to use the system with default settings."));
- }
- }
- return;
- }
+ $this->_connect();
try {
$pref = $this->_getPref($scope);
- } catch (Horde_Exception $e) {
+ } catch (Horde_Prefs_Exception $e) {
return;
}
* @param string $scope Scope specifier.
*
* @return array The preference value.
- * @throws Horde_Exception
+ * @throws Horde_Prefs_Exception
*/
protected function _getPref($scope)
{
$prefs = $this->_connection->getObjects();
if ($prefs instanceof PEAR_Error) {
- Horde::logMessage($prefs, 'ERR');
- throw new Horde_Exception_Prior($prefs);
+ if ($this->_opts['logger']) {
+ $this->_opts['logger']->log($prefs, 'ERR');
+ }
+ throw new Horde_Prefs_Exception($prefs);
}
foreach ($prefs as $pref) {
/**
* Stores preferences to the Kolab server.
*
- * @throws Horde_Exception
+ * @throws Horde_Prefs_Exception
*/
public function store()
{
try {
$pref = $this->_getPref($scope);
- } catch (Horde_Exception $e) {
+ } catch (Horde_Prefs_Exception $e) {
return;
}
$result = $this->_connection->_storage->save($object, $old_uid);
if ($result instanceof PEAR_Error) {
- Horde::logMessage($result, 'ERR');
+ if ($this->_opts['logger']) {
+ $this->_opts['logger']->log($result, 'ERR');
+ }
return;
}
}
class Horde_Prefs_Ldap extends Horde_Prefs
{
/**
- * Hash containing connection parameters.
- *
- * @var array
- */
- protected $_params = array();
-
- /**
* Handle for the current LDAP connection.
*
* @var resource
protected $_dn = '';
/**
- * String holding the user's password.
- *
- * @var string
- */
- protected $_password = '';
-
- /**
* Constructor.
*
- * @param string $scope The current application scope.
- * @param string $user The user who owns these preferences.
- * @param string $password The password associated with $user.
- * @param array $params A hash containing connection parameters.
- * @param boolean $caching Should caching be used?
+ * @param string $scope The scope for this set of preferences.
+ * @param array $opts See factory() for list of options.
+ * @param array $params A hash containing any additional configuration
+ * or connection parameters a subclass might need.
*/
- public function __construct($scope, $user, $password, $params, $caching)
+ protected function __construct($scope, $opts, $params);
{
/* If a valid server port has not been specified, set the default. */
if (!isset($params['port']) || !is_int($params['port'])) {
$params['port'] = 389;
}
- parent::__construct($scope, $user, $password, $params, $caching);
+ parent::__construct($scope, $opts, $params);
}
/**
* Opens a connection to the LDAP server.
*
- * @throws Horde_Exception
+ * @throws Horde_Prefs_Exception
*/
function _connect()
{
}
if (!Horde_Util::extensionExists('ldap')) {
- throw new Horde_Exception('Required LDAP extension not found.');
+ throw new Horde_Prefs_Exception('Required LDAP extension not found.');
}
Horde::assertDriverConfig($this->_params, 'prefs',
/* Connect to the LDAP server anonymously. */
$conn = ldap_connect($this->_params['hostspec'], $this->_params['port']);
if (!$conn) {
- Horde::logMessage(
- sprintf('Failed to open an LDAP connection to %s.',
- $this->_params['hostspec']), 'ERR');
- throw new Horde_Exception('Internal LDAP error. Details have been logged for the administrator.');
+ if ($this->_opts['logger']) {
+ $this->_opts['logger']->log(sprintf('Failed to open an LDAP connection to %s.', $this->_params['hostspec']), 'ERR');
+ }
+ throw new Horde_Prefs_Exception('Internal LDAP error. Details have been logged for the administrator.');
}
/* Set the LDAP protocol version. */
$result = @ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION,
$this->_params['version']);
if ($result === false) {
- Horde::logMessage(
- sprintf('Set LDAP protocol version to %d failed: [%d] %s',
- $this->_params['version'],
- @ldap_errno($conn),
- @ldap_error($conn)), 'WARN');
- throw new Horde_Exception('Internal LDAP error. Details have been logged for the administrator.');
+ if ($this->_opts['logger']) {
+ $this->_opts['logger']->log(sprintf('Set LDAP protocol version to %d failed: [%d] %s', $this->_params['version'], @ldap_errno($conn), @ldap_error($conn)), 'WARN');
+ }
+ throw new Horde_Prefs_Exception('Internal LDAP error. Details have been logged for the administrator.');
}
}
/* Start TLS if we're using it. */
- if (!empty($this->_params['tls'])) {
- if (!@ldap_start_tls($conn)) {
- Horde::logMessage(
- sprintf('STARTTLS failed: [%d] %s',
- @ldap_errno($this->_ds),
- @ldap_error($this->_ds)), 'ERR');
- }
+ if (!empty($this->_params['tls']) &&
+ !@ldap_start_tls($conn) &&
+ $this->_opts['logger']) {
+ $this->_opts['logger']->log(sprintf('STARTTLS failed: [%d] %s', @ldap_errno($this->_ds), @ldap_error($this->_ds)), 'ERR');
}
/* If necessary, bind to the LDAP server as the user with search
$bind = @ldap_bind($conn, $this->_params['searchdn'],
$this->_params['searchpw']);
if ($bind === false) {
- Horde::logMessage(
- sprintf('Bind to server %s:%d with DN %s failed: [%d] %s',
- $this->_params['hostspec'],
- $this->_params['port'],
- $this->_params['searchdn'],
- @ldap_errno($conn),
- @ldap_error($conn)), 'ERR');
- throw new Horde_Exception('Internal LDAP error. Details have been logged for the administrator.', @ldap_errno($conn));
+ if ($this->_opts['logger']) {
+ $this->_opts['logger']->log(sprintf('Bind to server %s:%d with DN %s failed: [%d] %s', $this->_params['hostspec'], $this->_params['port'], $this->_params['searchdn'], @ldap_errno($conn), @ldap_error($conn)), 'ERR');
+ }
+ throw new Horde_Prefs_Exception('Internal LDAP error. Details have been logged for the administrator.', @ldap_errno($conn));
}
}
if (function_exists('ldap_set_rebind_proc')) {
$result = @ldap_set_rebind_proc($conn, array($this, 'rebindProc'));
if ($result === false) {
- Horde::logMessage(
- sprintf('Setting referral callback failed: [%d] %s',
- @ldap_errno($conn),
- @ldap_error($conn)), 'WARN');
- throw new Horde_Exception(_("Internal LDAP error. Details have been logged for the administrator."), @ldap_errno($conn));
+ if ($this->_opts['logger']) {
+ $this->_opts['logger']->log(sprintf('Setting referral callback failed: [%d] %s', @ldap_errno($conn), @ldap_error($conn)), 'WARN');
+ }
+ throw new Horde_Prefs_Exception(_("Internal LDAP error. Details have been logged for the administrator."), @ldap_errno($conn));
}
}
/* Search for the user's full DN. */
$search = @ldap_search($this->_connection, $this->_params['basedn'],
- $this->_params['uid'] . '=' . $this->_user, array('dn'));
+ $this->_params['uid'] . '=' . $this->getUser(), array('dn'));
if ($search === false) {
- Horde::logMessage(
- sprintf('Error while searching the directory for the user\'s DN: [%d]: %s',
- @ldap_errno($this->_connection),
- @ldap_error($this->_connection)), 'ERR');
- throw new Horde_Exception('Internal LDAP error. Details have been logged for the administrator.', @ldap_errno($conn));
+ if ($this->_opts['logger']) {
+ $this->_opts['logger']->log(sprintf('Error while searching the directory for the user\'s DN: [%d]: %s', @ldap_errno($this->_connection), @ldap_error($this->_connection)), 'ERR');
+ }
+ throw new Horde_Prefs_Exception('Internal LDAP error. Details have been logged for the administrator.', @ldap_errno($conn));
}
$result = @ldap_get_entries($this->_connection, $search);
if ($result === false) {
- Horde::logMessage(
- sprintf('Error while retrieving LDAP search results for the user\'s DN: [%d]: %s',
- @ldap_errno($this->_connection),
- @ldap_error($this->_connection)), 'ERR');
- throw new Horde_Exception('Internal LDAP error. Details have been logged for the administrator.', @ldap_errno($this->_connection));
+ if ($this->_opts['logger']) {
+ $this->_opts['logger']->log(sprintf('Error while retrieving LDAP search results for the user\'s DN: [%d]: %s', @ldap_errno($this->_connection), @ldap_error($this->_connection)), 'ERR');
+ }
+ throw new Horde_Prefs_Exception('Internal LDAP error. Details have been logged for the administrator.', @ldap_errno($this->_connection));
}
if ($result['count'] != 1) {
- Horde::logMessage(
- 'Zero or more than one DN returned from search; unable to determine user\'s correct DN.', 'ERR');
- throw new Horde_Exception('Internal LDAP error. Details have been logged for the administrator.');
+ if ($this->_opts['logger']) {
+ $this->_opts['logger']->log('Zero or more than one DN returned from search; unable to determine user\'s correct DN.', 'ERR');
+ }
+ throw new Horde_Prefs_Exception('Internal LDAP error. Details have been logged for the administrator.');
}
$this->_dn = $result[0]['dn'];
switch($this->_params['writeas']) {
case 'user':
$result = @ldap_bind($this->_connection,
- $this->_dn, $this->_password);
+ $this->_dn, $this->_opts['password']);
break;
case 'admin':
}
if ($result === false) {
- Horde::logMessage(
- sprintf('Error rebinding for prefs writing: [%d]: %s',
- @ldap_errno($this->_connection),
- @ldap_error($this->_connection)), 'ERR');
- throw new Horde_Exception('Internal LDAP error. Details have been logged for the administrator.', @ldap_errno($this->_connection));
+ if ($this->_opts['logger']) {
+ $this->_opts['logger']->log(sprintf('Error rebinding for prefs writing: [%d]: %s', @ldap_errno($this->_connection), @ldap_error($this->_connection)), 'ERR');
+ }
+ throw new Horde_Prefs_Exception('Internal LDAP error. Details have been logged for the administrator.', @ldap_errno($this->_connection));
}
// We now have a ready-to-use connection.
/* Make sure the server we're being redirected to is in our list of
valid servers. */
if (strpos($this->_params['hostspec'], $who) === false) {
- Horde::logMessage(
- sprintf('Referral target %s for DN %s is not in the authorized server list.',
- $who, $bind_dn), 'ERR');
+ if ($this->_opts['logger']) {
+ $this->_opts['logger']->log(sprintf('Referral target %s for DN %s is not in the authorized server list.', $who, $bind_dn), 'ERR');
+ }
return 1;
}
switch($this->_params['writeas']) {
case 'user':
$bind_dn = $this->_dn;
- $bind_pw = $this->_password;
+ $bind_pw = $this->_opts['password'];
break;
case 'admin':
/* Bind to the new server. */
$bind = @ldap_bind($conn, $bind_dn, $bind_pw);
- if ($bind === false) {
- Horde::logMessage(
- sprintf('Rebind to server %s:%d with DN %s failed: [%d] %s',
- $this->_params['hostspec'],
- $this->_params['port'],
- $bind_dn,
- @ldap_errno($this->_connection),
- @ldap_error($this->_connection)), 'ERR');
+ if (($bind === false) && $this->_opts['logger']) {
+ $this->_opts['logger']->log(sprintf('Rebind to server %s:%d with DN %s failed: [%d] %s', $this->_params['hostspec'], $this->_params['port'], $bind_dn, @ldap_errno($this->_connection), @ldap_error($this->_connection)), 'ERR');
}
return 0;
*/
function _retrieve($scope)
{
- try {
- $this->_connect();
- } catch (Horde_Exception $e) {
- if (empty($_SESSION['prefs_cache']['unavailable'])) {
- $_SESSION['prefs_cache']['unavailable'] = true;
- $GLOBALS['notification']->push(_("The preferences backend is currently unavailable and your preferences have not been loaded. You may continue to use the system with default settings."));
- }
- return;
- }
+ $this->_connect();
// Search for the multi-valued field containing the array of
// preferences.
$search = @ldap_search($this->_connection, $this->_params['basedn'],
- $this->_params['uid'] . '=' . $this->_user,
+ $this->_params['uid'] . '=' . $this->getUser(),
array($scope . 'Prefs'));
if ($search === false) {
- Horde::logMessage(
- sprintf('Error while searching for the user\'s prefs: [%d]: %s',
- @ldap_errno($this->_connection),
- @ldap_error($this->_connection)), 'ERR');
+ if ($this->_opts['logger']) {
+ $this->_opts['logger']->log(sprintf('Error while searching for the user\'s prefs: [%d]: %s', @ldap_errno($this->_connection), @ldap_error($this->_connection)), 'ERR');
+ }
return;
}
$result = @ldap_get_entries($this->_connection, $search);
if ($result === false) {
- Horde::logMessage(
- sprintf('Error while retrieving LDAP search results for the user\'s prefs: [%d]: %s',
- @ldap_errno($this->_connection),
- @ldap_error($this->_connection)), 'ERR');
+ if ($this->_opts['logger']) {
+ $this->_opts['logger']->log(sprintf('Error while retrieving LDAP search results for the user\'s prefs: [%d]: %s', @ldap_errno($this->_connection), @ldap_error($this->_connection)), 'ERR');
+ }
return;
}
/**
* Stores preferences to the LDAP server.
*
- * @throws Horde_Exception
+ * @throws Horde_Prefs_Exception
*/
public function store()
{
// to successfully store LDAP prefs. Check for both of them,
// and add them if necessary.
$search = @ldap_search($this->_connection, $this->_params['basedn'],
- $this->_params['uid'] . '=' . $this->_user,
+ $this->_params['uid'] . '=' . $this->getUser(),
array('objectclass'));
if ($search === false) {
- Horde::logMessage(
- sprintf('Error searching the directory for required objectClasses: [%d] %s',
- @ldap_errno($this->_connection),
- @ldap_error($this->_connection)), 'ERR');
+ if ($this->_opts['logger']) {
+ $this->_opts['logger']->log(sprintf('Error searching the directory for required objectClasses: [%d] %s', @ldap_errno($this->_connection), @ldap_error($this->_connection)), 'ERR');
+ }
return;
}
$result = @ldap_get_entries($this->_connection, $search);
if ($result === false) {
- Horde::logMessage(
- sprintf('Error retrieving results while checking for required objectClasses: [%d] %s',
- @ldap_errno($this->_connection),
- @ldap_error($this->_connection)), 'ERR');
+ if ($this->_opts['logger']) {
+ $this->_opts['logger']->log(sprintf('Error retrieving results while checking for required objectClasses: [%d] %s', @ldap_errno($this->_connection), @ldap_error($this->_connection)), 'ERR');
+ }
return;
}
$result = @ldap_mod_replace($this->_connection, $this->_dn,
$new_values);
if ($result === false) {
- Horde::logMessage(
- sprintf('Unable to modify user\'s objectClass for preferences: [%d] %s',
- @ldap_errno($this->_connection),
- @ldap_error($this->_connection)), 'ERR');
+ if ($this->_opts['logger']) {
+ $this->_opts['logger']->log(sprintf('Unable to modify user\'s objectClass for preferences: [%d] %s', @ldap_errno($this->_connection), @ldap_error($this->_connection)), 'ERR');
+ }
return;
}
/**
* Clears all preferences from the LDAP backend.
*
- * @throws Horde_Exception
+ * @throws Horde_Prefs_Exception
*/
public function clear()
{
$search = @ldap_read($this->_connection, $this->_dn,
'objectClass=hordePerson', $attrs, 1);
if ($search === false) {
- Horde::logMessage(
- sprintf('Error while getting preferenes from LDAP: [%d] %s',
- @ldap_errno($this->_connection),
- @ldap_error($this->_connection)), 'ERR');
+ if ($this->_opts['logger']) {
+ $this->_opts['logger']->log(sprintf('Error while getting preferenes from LDAP: [%d] %s', @ldap_errno($this->_connection), @ldap_error($this->_connection)), 'ERR');
+ }
return;
}
$result = @ldap_get_entries($this->_connection, $search);
if ($result === false) {
- Horde::logMessage(
- sprintf('Error while retrieving results from LDAP: [%d] %s',
- @ldap_errno($this->_connection),
- @ldap_error($this->_connection)), 'ERR');
+ if ($this->_opts['logger']) {
+ $this->_opts['logger']->log(sprintf('Error while retrieving results from LDAP: [%d] %s', @ldap_errno($this->_connection), @ldap_error($this->_connection)), 'ERR');
+ }
return;
}
$attrs[$result[0][$i]] = array();
}
$result = @ldap_mod_del($this->_connection, $this->_dn, $attrs);
- if ($result === false) {
- Horde::logMessage(
- sprintf('Unable to clear user\'s preferences: [%d] %s',
- @ldap_errno($this->_connection),
- @ldap_error($this->_connection)), 'ERR');
+ if (($result === false) && $this->_opts['logger']) {
+ $this->_opts['logger']->log(sprintf('Unable to clear user\'s preferences: [%d] %s', @ldap_errno($this->_connection), @ldap_error($this->_connection)), 'ERR');
}
$this->cleanup(true);
*
* @author Jon Parise <jon@horde.org>
* @category Horde
+ * @license http://www.fsf.org/copyleft/lgpl.html LGPL
* @package Prefs
*/
class Horde_Prefs_Sql extends Horde_Prefs
{
/**
- * Hash containing connection parameters.
- *
- * @var array
- */
- protected $_params = array();
-
- /**
* Handle for the current database connection.
*
* @var Horde_Db_Adapter_Base
protected $_db;
/**
- * Returns the charset used by the concrete preference backend.
+ * Constructor.
*
- * @return string The preference backend's charset.
+ * @param string $scope The scope for this set of preferences.
+ * @param array $opts See factory() for list of options.
+ * @param array $params A hash containing any additional configuration
+ * or connection parameters a subclass might need.
+ * <pre>
+ * 'db' - (Horde_Db_Adapter_Base) [REQUIRED] The DB instance.
+ * 'table' - (string) The name of the prefs table.
+ * DEFAULT: 'horde_prefs'
+ * </pre>
+ *
+ * @throws InvalidArgumentException
*/
- public function getCharset()
+ protected function __construct($scope, $opts, $params)
{
- return $this->_params['charset'];
+ if (!isset($params['db'])) {
+ throw new InvalidArgumentException('Missing db parameter.');
+ }
+ $this->_db = $params['db'];
+ unset($params['db']);
+
+ $params = array_merge(array(
+ 'table' => 'horde_prefs'
+ ), $params);
+
+ parent::__construct($scope, $opts, $params);
}
/**
*/
protected function _retrieve($scope)
{
- try {
- $this->_connect();
- } catch (Horde_Exception $e) {
- if (empty($_SESSION['prefs_cache']['unavailable'])) {
- $_SESSION['prefs_cache']['unavailable'] = true;
- if (isset($GLOBALS['notification'])) {
- $GLOBALS['notification']->push(_("The preferences backend is currently unavailable and your preferences have not been loaded. You may continue to use the system with default settings."));
- }
- }
- return;
- }
-
$query = 'SELECT pref_scope, pref_name, pref_value FROM ' .
$this->_params['table'] . ' ' .
'WHERE pref_uid = ? AND pref_scope = ?';
- $values = array($this->_user, $scope);
+ $values = array($this->getUser(), $scope);
try {
$result = $this->_db->selectAll($query, $values);
} catch (Horde_Db_Exception $e) {
- Horde::logMessage('No preferences were retrieved.', 'DEBUG');
+ if ($this->_opts['logger']) {
+ $this->_opts['logger']->log('No preferences were retrieved.', 'DEBUG');
+ }
return;
}
switch ($this->_db->adapterName()) {
case 'PDO_PostgreSQL':
+ // TODO: Should be done in DB driver
if (is_resource($row['pref_value'])) {
$val = stream_get_contents($row['pref_value']);
fclose($row['pref_value']);
{
// Get the list of preferences that have changed. If there are
// none, no need to hit the backend.
- $dirty_prefs = $this->_dirtyPrefs();
- if (!$dirty_prefs) {
+ if (!($dirty_prefs = $this->_dirtyPrefs())) {
return;
}
- $this->_connect();
-
// For each preference, check for an existing table row and
// update it if it's there, or create a new one if it's not.
foreach ($dirty_prefs as $scope => $prefs) {
$query = 'SELECT 1 FROM ' . $this->_params['table'] .
' WHERE pref_uid = ? AND pref_name = ?' .
' AND pref_scope = ?';
- $values = array($this->_user, $name, $scope);
+ $values = array($this->getUser(), $name, $scope);
try {
$check = $this->_db->selectValue($query, $values);
} catch (Horde_Db_Exception $e) {
- Horde::logMessage('Failed checking prefs for ' . $this->_user . ': ' . $e->getMessage(), 'ERR');
return;
}
switch ($this->_db->adapterName()) {
case 'PDO_PostgreSQL':
+ // TODO: Should be done in DB driver
$value = pg_escape_bytea($value);
break;
}
'(pref_uid, pref_scope, pref_name, pref_value) VALUES' .
'(?, ?, ?, ?)';
$values = array(
- $this->_user,
+ $this->getUser(),
$scope,
$name,
$value
' AND pref_scope = ?';
$values = array(
$value,
- $this->_user,
+ $this->getUser(),
$name,
$scope
);
*/
public function clear()
{
- $this->_connect();
-
// Build the SQL query.
$query = 'DELETE FROM ' . $this->_params['table'] .
' WHERE pref_uid = ?';
- $values = array($this->_user);
+ $values = array($this->getUser());
// Execute the query.
try {
parent::clear();
}
- /**
- * Converts a value from the driver's charset to the specified charset.
- *
- * @param mixed $value A value to convert.
- * @param string $charset The charset to convert to.
- *
- * @return mixed The converted value.
- */
- public function convertFromDriver($value, $charset)
- {
- static $converted = array();
-
- if (is_array($value)) {
- return Horde_String::convertCharset($value, $this->_params['charset'], $charset);
- }
-
- if (is_bool($value)) {
- return $value;
- }
-
- if (!isset($converted[$charset][$value])) {
- $converted[$charset][$value] = Horde_String::convertCharset($value, $this->_params['charset'], $charset);
- }
-
- return $converted[$charset][$value];
- }
-
- /**
- * Converts a value from the specified charset to the driver's charset.
- *
- * @param mixed $value A value to convert.
- * @param string $charset The charset to convert from.
- *
- * @return mixed The converted value.
- */
- public function convertToDriver($value, $charset)
- {
- return Horde_String::convertCharset($value, $charset, $this->_params['charset']);
- }
-
- /**
- * Attempts to open a persistent connection to the SQL server.
- *
- * @throws Horde_Exception
- */
- protected function _connect()
- {
- if ($this->_connected) {
- return;
- }
-
- $this->_db = $GLOBALS['injector']->getInstance('Horde_Db')->getDb('horde', 'prefs');
- $this->_params = array_merge(array(
- 'table' => 'horde_prefs'
- ), Horde::getDriverConfig('prefs'));
- $this->_connected = true;
- }
-
}
<api>beta</api>
</stability>
<license uri="http://www.gnu.org/copyleft/lesser.html">LGPL</license>
- <notes>* Moved UI code to Horde_Core::.
+ <notes>* Remove dependency on horde/Core.
+ * Use Horde_Db as backend for Sql driver.
+ * Moved UI code to horde/Core.
* Initial Horde 4 package.
</notes>
<contents>
<dir name="Horde">
<dir name="Prefs">
<file name="CategoryManager.php" role="php" />
+ <file name="Exception.php" role="php" />
<file name="File.php" role="php" />
<file name="Identity.php" role="php" />
<file name="Imsp.php" role="php" />
<min>1.7.0</min>
</pearinstaller>
<package>
- <name>Core</name>
+ <name>Exception</name>
<channel>pear.horde.org</channel>
</package>
<package>
</required>
<optional>
<package>
+ <name>Db</name>
+ <channel>pear.horde.org</channel>
+ </package>
+ <package>
<name>Mime</name>
<channel>pear.horde.org</channel>
</package>
<phprelease>
<filelist>
<install name="lib/Horde/Prefs/CategoryManager.php" as="Horde/Prefs/CategoryManager.php" />
+ <install name="lib/Horde/Prefs/Exception.php" as="Horde/Prefs/Exception.php" />
<install name="lib/Horde/Prefs/File.php" as="Horde/Prefs/File.php" />
<install name="lib/Horde/Prefs/Identity.php" as="Horde/Prefs/Identity.php" />
<install name="lib/Horde/Prefs/Imsp.php" as="Horde/Prefs/Imsp.php" />
$haveError = false;
/* Remove user's prefs */
- $prefs = Horde_Prefs::singleton($conf['prefs']['driver'], null, $user);
- if (is_a($result = $prefs->clear(), 'PEAR_Error')) {
- Horde::logMessage($result, 'ERR');
+ $prefs = $GLOBALS['injector']->getInstance('Horde_Prefs')->getPrefs('horde', array(
+ 'user' => $user
+ ));
+ try {
+ $prefs->clear();
+ } catch (Horde_Exception $e) {
$haveError = true;
}
$cli->message('Importing ' . $user . '\'s preferences');
// Reset user prefs
- $prefs = Horde_Prefs::factory($conf['prefs']['driver'], 'horde', $user, null, null, false);
+ $prefs = $injector->getInstance('Horde_Prefs')->getPrefs('horde', array(
+ 'cache' => false,
+ 'user' => $user
+ ));
$prefs_cache = array();
// Read pref file, one line at a time
$GLOBALS['registry']->setAuth($user, array());
$cli->message('Importing ' . $user . '\'s preferences');
- $prefs = Horde_Prefs::factory($conf['prefs']['driver'], 'horde', $user, null, null, false);
+ $prefs = $GLOBALS['injector']->getInstance('Horde_Prefs')->getPrefs('horde', array(
+ 'cache' => false,
+ 'user' => $user
+ ));
savePrefs($user, null, $prefs_cache);
}
/* If a username has been supplied try fetching the prefs stored info. */
if ($username = $vars->get('username')) {
$username = Horde_Auth::addHook($username);
- $prefs = Horde_Prefs::singleton($conf['prefs']['driver'], 'horde', $username, '', null, false);
- $prefs->retrieve();
+ $prefs = $injector->getInstance('Horde_Prefs')->getPrefs('horde', array(
+ 'cache' => false,
+ 'user' => $username
+ ));
$email = $prefs->getValue('alternate_email');
/* Does the alternate email stored in prefs match the one submitted? */
if ($vars->get('email') == $email) {
/* Load $mail_user's preferences so that we can use their
* locale information for the notification message. */
- $prefs = Horde_Prefs::singleton($conf['prefs']['driver'], 'horde', $mail_user);
- $prefs->retrieve();
+ $prefs = $injector->getInstance('Horde_Prefs')->getPrefs('horde', array(
+ 'cache' => false,
+ 'user' => $mail_user
+ ));
$mail_identity = $injector->getInstance('Horde_Prefs_Identity')->getIdentity($mail_user);
$mail_address = $mail_identity->getDefaultFromAddress();
*/
protected function _retrieve($field, $readonly = false)
{
- $prefs = Horde_Prefs::singleton($GLOBALS['conf']['prefs']['driver'],
- $GLOBALS['registry']->getApp(),
- Ingo::getUser(), '', null, false);
- $prefs->retrieve();
+ $prefs = $GLOBALS['injector']->getInstance('Horde_Prefs')->getPrefs('ingo', array(
+ 'cache' => false,
+ 'user' => Ingo::getUser()
+ ));
switch ($field) {
case self::ACTION_BLACKLIST:
/* Convert vacation from the old format. */
$data = unserialize($prefs->getValue('vacation'));
} elseif (is_array($data)) {
- $data = $prefs->convertFromDriver($data, $GLOBALS['registry']->getCharset());
+ $data = $prefs->convertFromDriver($data);
}
if ($data) {
$ob->setVacationAddresses($data['addresses'], false);
*/
protected function _store($ob)
{
- $prefs = Horde_Prefs::singleton($GLOBALS['conf']['prefs']['driver'],
- $GLOBALS['registry']->getApp(),
- Ingo::getUser(), '', null, false);
- $prefs->retrieve();
+ $prefs = $GLOBALS['injector']->getInstance('Horde_Prefs')->getPrefs('ingo', array(
+ 'cache' => false,
+ 'user' => Ingo::getUser()
+ ));
switch ($ob->obType()) {
case self::ACTION_BLACKLIST:
'start' => $ob->getVacationStart(),
'end' => $ob->getVacationEnd(),
);
- return $prefs->setValue('vacation', serialize($prefs->convertToDriver($data, $GLOBALS['registry']->getCharset())), false);
+ return $prefs->setValue('vacation', serialize($prefs->convertToDriver($data)), false);
case self::ACTION_WHITELIST:
return $prefs->setValue('whitelist', serialize($ob->getWhitelist()));
$fb = $cache->get($key, 360);
if (!$fb) {
if ($user) {
- $prefs = Horde_Prefs::singleton($conf['prefs']['driver'], 'kronolith', $user, '', null, false);
- $prefs->retrieve();
+ $prefs = $GLOBALS['injector']->getInstance('Horde_Prefs')->getPrefs('kronolith', array(
+ 'cache' => false,
+ 'user' => $user
+ ));
$registry->setTimeZone();
$cal = @unserialize($prefs->getValue('fb_cals'));
if (is_array($cal)) {
if ($alarm_user == $current_user) {
$prefs = $GLOBALS['prefs'];
} else {
- $prefs = Horde_Prefs::singleton($GLOBALS['conf']['prefs']['driver'],
- 'kronolith', $alarm_user, null,
- null, false);
+ $prefs = $GLOBALS['injector']->getInstance('Horde_Prefs')->getPrefs('kronolith', array(
+ 'cache' => false,
+ 'user' => $alarm_user
+ ));
}
$shown_calendars = unserialize($prefs->getValue('display_cals'));
$reminder = $prefs->getValue('event_reminder');
*/
public static function _notificationPref($user, $mode, $calendar = null)
{
- $prefs = Horde_Prefs::singleton($GLOBALS['conf']['prefs']['driver'],
- 'kronolith', $user, '', null,
- false);
- $prefs->retrieve();
+ $prefs = $GLOBALS['injector']->getInstance('Horde_Prefs')->getPrefs('kronolith', array(
+ 'cache' => false,
+ 'user' => $user
+ ));
$vals = array('lang' => $prefs->getValue('language'),
'tf' => $prefs->getValue('twentyFour'),
'df' => $prefs->getValue('date_format'));
// Loop through the users and generate an agenda for them
foreach ($users as $user) {
- $prefs = Horde_Prefs::singleton($GLOBALS['conf']['prefs']['driver'],
- 'kronolith', $user);
- $prefs->retrieve();
+ $prefs = $GLOBALS['injector']->getInstance('Horde_Prefs')->getPrefs('kronolith', array(
+ 'user' => $user
+ ));
$agenda_calendars = $prefs->getValue('daily_agenda');
if (!$agenda_calendars) {
if (!is_null($creator)) {
echo "$count\n";
}
- $prefs = Horde_Prefs::factory($conf['prefs']['driver'], 'horde',
- $row['event_creator_id']);
+ $prefs = $injector->getInstance('Horde_Prefs')->getPrefs('horde', array(
+ 'cache' => false,
+ 'user' => $row['event_creator_id']
+ ));
+
$timezone = $prefs->getValue('timezone');
if (empty($timezone)) {
$timezone = date_default_timezone_get();
$users = array($user);
}
foreach ($users as $alarm_user) {
- $prefs = Horde_Prefs::singleton($GLOBALS['conf']['prefs']['driver'], 'nag', $alarm_user, null, null, false);
+ $GLOBALS['injector']->getInstance('Horde_Prefs')->getPrefs('nag', array(
+ 'cache' => false,
+ 'user' => $alarm_user
+ ));
$GLOBALS['registry']->setLanguageEnvironment($prefs->getValue('language'));
$alarm_list[] = $alarm->toAlarm($alarm_user, $prefs);
}
*/
public static function _notificationPref($user, $mode, $tasklist = null)
{
- $prefs = Horde_Prefs::singleton($GLOBALS['conf']['prefs']['driver'],
- 'nag', $user, '', null,
- false);
- $prefs->retrieve();
+ $prefs = $GLOBALS['injector']->getInstance('Horde_Prefs')->getPrefs('nag', array(
+ 'cache' => false,
+ 'user' => $user
+ ));
$vals = array('lang' => $prefs->getValue('language'),
'tf' => $prefs->getValue('twentyFour'),
'df' => $prefs->getValue('date_format'));
// Reset user prefs
unset($prefs);
- $prefs = Horde_Prefs::factory($conf['prefs']['driver'], 'turba', $user, null, null, false);
+ $prefs = $injector->getInstance('Horde_Prefs')->getPrefs('turba', array(
+ 'cache' => false,
+ 'user' => $user
+ ));
// Reset $cfgSources for current user.
unset($cfgSources);
$cli->message('Importing ' . $user . '\'s address book');
// Reset user prefs
- unset($prefs);
- $prefs = Horde_Prefs::factory($conf['prefs']['driver'], 'turba', $user, null, null, false);
+ $prefs = $injector->getInstance('Horde_Prefs')->getPrefs('turba', array(
+ 'cache' => false,
+ 'user' => $user
+ ));
// Reset $cfgSources for current user.
unset($cfgSources);