/branches/livraison_narmer/api/pear/Auth/HTTP.php |
---|
New file |
0,0 → 1,795 |
<?php |
// |
// +----------------------------------------------------------------------+ |
// | PHP Version 4 | |
// +----------------------------------------------------------------------+ |
// | Copyright (c) 1997-2004 The PHP Group | |
// +----------------------------------------------------------------------+ |
// | This source file is subject to version 2.02 of the PHP license, | |
// | that is bundled with this package in the file LICENSE, and is | |
// | available at through the world-wide-web at | |
// | http://www.php.net/license/2_02.txt. | |
// | If you did not receive a copy of the PHP license and are unable to | |
// | obtain it through the world-wide-web, please send a note to | |
// | license@php.net so we can mail you a copy immediately. | |
// +----------------------------------------------------------------------+ |
// | Authors: Martin Jansen <mj@php.net> | |
// | Rui Hirokawa <hirokawa@php.net> | |
// | David Costa <gurugeek@php.net> | |
// +----------------------------------------------------------------------+ |
// |
// $Id: HTTP.php,v 1.1 2006-12-14 15:04:28 jp_milcent Exp $ |
// |
require_once "Auth/Auth.php"; |
define('AUTH_HTTP_NONCE_TIME_LEN', 16); |
define('AUTH_HTTP_NONCE_HASH_LEN', 32); |
// {{{ class Auth_HTTP |
/** |
* PEAR::Auth_HTTP |
* |
* The PEAR::Auth_HTTP class provides methods for creating an |
* HTTP authentication system based on RFC-2617 using PHP. |
* |
* Instead of generating an HTML driven form like PEAR::Auth |
* does, this class sends header commands to the clients which |
* cause them to present a login box like they are e.g. used |
* in Apache's .htaccess mechanism. |
* |
* This class requires the PEAR::Auth package. |
* |
* @notes The HTTP Digest Authentication part is based on |
* authentication class written by Tom Pike <tom.pike@xiven.com> |
* |
* @author Martin Jansen <mj@php.net> |
* @author Rui Hirokawa <hirokawa@php.net> |
* @author David Costa <gurugeek@php.net> |
* @package Auth_HTTP |
* @extends Auth |
* @version $Revision: 1.1 $ |
*/ |
class Auth_HTTP extends Auth |
{ |
// {{{ properties |
/** |
* Authorization method: 'basic' or 'digest' |
* |
* @access public |
* @var string |
*/ |
var $authType = 'basic'; |
/** |
* Name of the realm for Basic Authentication |
* |
* @access public |
* @var string |
* @see drawLogin() |
*/ |
var $realm = "protected area"; |
/** |
* Text to send if user hits cancel button |
* |
* @access public |
* @var string |
* @see drawLogin() |
*/ |
var $CancelText = "Error 401 - Access denied"; |
/** |
* option array |
* |
* @access public |
* @var array |
*/ |
var $options = array(); |
/** |
* flag to indicate the nonce was stale. |
* |
* @access public |
* @var bool |
*/ |
var $stale = false; |
/** |
* opaque string for digest authentication |
* |
* @access public |
* @var string |
*/ |
var $opaque = 'dummy'; |
/** |
* digest URI |
* |
* @access public |
* @var string |
*/ |
var $uri = ''; |
/** |
* authorization info returned by the client |
* |
* @access public |
* @var array |
*/ |
var $auth = array(); |
/** |
* next nonce value |
* |
* @access public |
* @var string |
*/ |
var $nextNonce = ''; |
/** |
* nonce value |
* |
* @access public |
* @var string |
*/ |
var $nonce = ''; |
/** |
* Holds a reference to the global server variable |
* @var array |
*/ |
var $server; |
/** |
* Holds a reference to the global post variable |
* @var array |
*/ |
var $post; |
/** |
* Holds a reference to the global cookie variable |
* @var array |
*/ |
var $cookie; |
// }}} |
// {{{ Constructor |
/** |
* Constructor |
* |
* @param string Type of the storage driver |
* @param mixed Additional options for the storage driver |
* (example: if you are using DB as the storage |
* driver, you have to pass the dsn string here) |
* |
* @return void |
*/ |
function Auth_HTTP($storageDriver, $options = '') |
{ |
/* set default values for options */ |
$this->options = array('cryptType' => 'md5', |
'algorithm' => 'MD5', |
'qop' => 'auth-int,auth', |
'opaquekey' => 'moo', |
'noncekey' => 'moo', |
'digestRealm' => 'protected area', |
'forceDigestOnly' => false, |
'nonceLife' => 300, |
'sessionSharing' => true, |
); |
if (!empty($options['authType'])) { |
$this->authType = strtolower($options['authType']); |
} |
if (is_array($options)) { |
foreach($options as $key => $value) { |
if (array_key_exists( $key, $this->options)) { |
$this->options[$key] = $value; |
} |
} |
if (!empty($this->options['opaquekey'])) { |
$this->opaque = md5($this->options['opaquekey']); |
} |
} |
$this->Auth($storageDriver, $options); |
} |
// }}} |
// {{{ assignData() |
/** |
* Assign values from $PHP_AUTH_USER and $PHP_AUTH_PW or 'Authorization' header |
* to internal variables and sets the session id based |
* on them |
* |
* @access public |
* @return void |
*/ |
function assignData() |
{ |
if (method_exists($this, '_importGlobalVariable')) { |
$this->server = &$this->_importGlobalVariable('server'); |
} |
if ($this->authType == 'basic') { |
if (!empty($this->server['PHP_AUTH_USER'])) { |
$this->username = $this->server['PHP_AUTH_USER']; |
} |
if (!empty($this->server['PHP_AUTH_PW'])) { |
$this->password = $this->server['PHP_AUTH_PW']; |
} |
/** |
* Try to get authentication information from IIS |
*/ |
if (empty($this->username) && empty($this->password)) { |
if (!empty($this->server['HTTP_AUTHORIZATION'])) { |
list($this->username, $this->password) = |
explode(':', base64_decode(substr($this->server['HTTP_AUTHORIZATION'], 6))); |
} |
} |
} elseif ($this->authType == 'digest') { |
$this->username = ''; |
$this->password = ''; |
$this->digest_header = null; |
if (!empty($this->server['PHP_AUTH_DIGEST'])) { |
$this->digest_header = substr($this->server['PHP_AUTH_DIGEST'], |
strpos($this->server['PHP_AUTH_DIGEST'],' ')+1); |
} else { |
$headers = getallheaders(); |
if(isset($headers['Authorization']) && !empty($headers['Authorization'])) { |
$this->digest_header = substr($headers['Authorization'], |
strpos($headers['Authorization'],' ')+1); |
} |
} |
if($this->digest_header) { |
$authtemp = explode(',', $this->digest_header); |
$auth = array(); |
foreach($authtemp as $key => $value) { |
$value = trim($value); |
if(strpos($value,'=') !== false) { |
$lhs = substr($value,0,strpos($value,'=')); |
$rhs = substr($value,strpos($value,'=')+1); |
if(substr($rhs,0,1) == '"' && substr($rhs,-1,1) == '"') { |
$rhs = substr($rhs,1,-1); |
} |
$auth[$lhs] = $rhs; |
} |
} |
} |
if (!isset($auth['uri']) || !isset($auth['realm'])) { |
return; |
} |
if ($this->selfURI() == $auth['uri']) { |
$this->uri = $auth['uri']; |
if (substr($headers['Authorization'],0,7) == 'Digest ') { |
$this->authType = 'digest'; |
if (!isset($auth['nonce']) || !isset($auth['username']) || |
!isset($auth['response']) || !isset($auth['qop']) || |
!isset($auth['nc']) || !isset($auth['cnonce'])){ |
return; |
} |
if ($auth['qop'] != 'auth' && $auth['qop'] != 'auth-int') { |
return; |
} |
$this->stale = $this->_judgeStale($auth['nonce']); |
if ($this->nextNonce == false) { |
return; |
} |
$this->username = $auth['username']; |
$this->password = $auth['response']; |
$this->auth['nonce'] = $auth['nonce']; |
$this->auth['qop'] = $auth['qop']; |
$this->auth['nc'] = $auth['nc']; |
$this->auth['cnonce'] = $auth['cnonce']; |
if (isset($auth['opaque'])) { |
$this->auth['opaque'] = $auth['opaque']; |
} |
} elseif (substr($headers['Authorization'],0,6) == 'Basic ') { |
if ($this->options['forceDigestOnly']) { |
return; // Basic authentication is not allowed. |
} |
$this->authType = 'basic'; |
list($username, $password) = |
explode(':',base64_decode(substr($headers['Authorization'],6))); |
$this->username = $username; |
$this->password = $password; |
} |
} |
} else { |
return PEAR::raiseError('authType is invalid.'); |
} |
if ($this->options['sessionSharing'] && |
isset($this->username) && isset($this->password)) { |
session_id(md5('Auth_HTTP' . $this->username . $this->password)); |
} |
/** |
* set sessionName for AUTH, so that the sessionName is different |
* for distinct realms |
*/ |
$this->_sessionName = "_authhttp".md5($this->realm); |
} |
// }}} |
// {{{ login() |
/** |
* Login function |
* |
* @access private |
* @return void |
*/ |
function login() |
{ |
$login_ok = false; |
if (method_exists($this, '_loadStorage')) { |
$this->_loadStorage(); |
} |
$this->storage->_auth_obj->_sessionName =& $this->_sessionName; |
/** |
* When the user has already entered a username, |
* we have to validate it. |
*/ |
if (!empty($this->username) && !empty($this->password)) { |
if ($this->authType == 'basic' && !$this->options['forceDigestOnly']) { |
if (true === $this->storage->fetchData($this->username, $this->password)) { |
$login_ok = true; |
} |
} else { /* digest authentication */ |
if (!$this->getAuth() || $this->getAuthData('a1') == null) { |
/* |
* note: |
* - only PEAR::DB is supported as container. |
* - password should be stored in container as plain-text |
* (if $options['cryptType'] == 'none') or |
* A1 hashed form (md5('username:realm:password')) |
* (if $options['cryptType'] == 'md5') |
*/ |
$dbs = $this->storage; |
if (!DB::isConnection($dbs->db)) { |
$dbs->_connect($dbs->options['dsn']); |
} |
$query = 'SELECT '.$dbs->options['passwordcol']." FROM ".$dbs->options['table']. |
' WHERE '.$dbs->options['usernamecol']." = '". |
$dbs->db->quoteString($this->username)."' "; |
$pwd = $dbs->db->getOne($query); // password stored in container. |
if (DB::isError($pwd)) { |
return PEAR::raiseError($pwd->getMessage(), $pwd->getCode()); |
} |
if ($this->options['cryptType'] == 'none') { |
$a1 = md5($this->username.':'.$this->options['digestRealm'].':'.$pwd); |
} else { |
$a1 = $pwd; |
} |
$this->setAuthData('a1', $a1, true); |
} else { |
$a1 = $this->getAuthData('a1'); |
} |
$login_ok = $this->validateDigest($this->password, $a1); |
if ($this->nextNonce == false) { |
$login_ok = false; |
} |
} |
if (!$login_ok && is_callable($this->loginFailedCallback)) { |
call_user_func($this->loginFailedCallback,$this->username, $this); |
} |
} |
if (!empty($this->username) && $login_ok) { |
$this->setAuth($this->username); |
if (is_callable($this->loginCallback)) { |
call_user_func($this->loginCallback,$this->username, $this); |
} |
} |
/** |
* If the login failed or the user entered no username, |
* output the login screen again. |
*/ |
if (!empty($this->username) && !$login_ok) { |
$this->status = AUTH_WRONG_LOGIN; |
} |
if ((empty($this->username) || !$login_ok) && $this->showLogin) { |
$this->drawLogin($this->storage->activeUser); |
return; |
} |
if (!empty($this->username) && $login_ok && $this->authType == 'digest' |
&& $this->auth['qop'] == 'auth') { |
$this->authenticationInfo(); |
} |
} |
// }}} |
// {{{ drawLogin() |
/** |
* Launch the login box |
* |
* @param string $username Username |
* @return void |
* @access private |
*/ |
function drawLogin($username = "") |
{ |
/** |
* Send the header commands |
*/ |
if ($this->authType == 'basic') { |
header("WWW-Authenticate: Basic realm=\"".$this->realm."\""); |
header('HTTP/1.0 401 Unauthorized'); |
} else if ($this->authType == 'digest') { |
$this->nonce = $this->_getNonce(); |
$wwwauth = 'WWW-Authenticate: Digest '; |
$wwwauth .= 'qop="'.$this->options['qop'].'", '; |
$wwwauth .= 'algorithm='.$this->options['algorithm'].', '; |
$wwwauth .= 'realm="'.$this->options['digestRealm'].'", '; |
$wwwauth .= 'nonce="'.$this->nonce.'", '; |
if ($this->stale) { |
$wwwauth .= 'stale=true, '; |
} |
if (!empty($this->opaque)) { |
$wwwauth .= 'opaque="'.$this->opaque.'"' ; |
} |
$wwwauth .= "\r\n"; |
if (!$this->options['forceDigestOnly']) { |
$wwwauth .= 'WWW-Authenticate: Basic realm="'.$this->realm.'"'; |
} |
header($wwwauth); |
header('HTTP/1.0 401 Unauthorized'); |
} |
/** |
* This code is only executed if the user hits the cancel |
* button or if he enters wrong data 3 times. |
*/ |
if ($this->stale) { |
echo 'Stale nonce value, please re-authenticate.'; |
} else { |
echo $this->CancelText; |
} |
exit; |
} |
// }}} |
// {{{ setRealm() |
/** |
* Set name of the current realm |
* |
* @access public |
* @param string $realm Name of the realm |
* @param string $digestRealm Name of the realm for digest authentication |
* @return void |
*/ |
function setRealm($realm, $digestRealm = '') |
{ |
$this->realm = $realm; |
if (!empty($digestRealm)) { |
$this->options['digestRealm'] = $digestRealm; |
} |
} |
// }}} |
// {{{ setCancelText() |
/** |
* Set the text to send if user hits the cancel button |
* |
* @access public |
* @param string $text Text to send |
* @return void |
*/ |
function setCancelText($text) |
{ |
$this->CancelText = $text; |
} |
// }}} |
// {{{ validateDigest() |
/** |
* judge if the client response is valid. |
* |
* @access private |
* @param string $response client response |
* @param string $a1 password or hashed password stored in container |
* @return bool true if success, false otherwise |
*/ |
function validateDigest($response, $a1) |
{ |
if (method_exists($this, '_importGlobalVariable')) { |
$this->server = &$this->_importGlobalVariable('server'); |
} |
$a2unhashed = $this->server['REQUEST_METHOD'].":".$this->selfURI(); |
if($this->auth['qop'] == 'auth-int') { |
if(isset($GLOBALS["HTTP_RAW_POST_DATA"])) { |
// In PHP < 4.3 get raw POST data from this variable |
$body = $GLOBALS["HTTP_RAW_POST_DATA"]; |
} else if($lines = @file('php://input')) { |
// In PHP >= 4.3 get raw POST data from this file |
$body = implode("\n", $lines); |
} else { |
if (method_exists($this, '_importGlobalVariable')) { |
$this->post = &$this->_importGlobalVariable('post'); |
} |
$body = ''; |
foreach($this->post as $key => $value) { |
if($body != '') $body .= '&'; |
$body .= rawurlencode($key) . '=' . rawurlencode($value); |
} |
} |
$a2unhashed .= ':'.md5($body); |
} |
$a2 = md5($a2unhashed); |
$combined = $a1.':'. |
$this->auth['nonce'].':'. |
$this->auth['nc'].':'. |
$this->auth['cnonce'].':'. |
$this->auth['qop'].':'. |
$a2; |
$expectedResponse = md5($combined); |
if(!isset($this->auth['opaque']) || $this->auth['opaque'] == $this->opaque) { |
if($response == $expectedResponse) { // password is valid |
if(!$this->stale) { |
return true; |
} else { |
$this->drawLogin(); |
} |
} |
} |
return false; |
} |
// }}} |
// {{{ _judgeStale() |
/** |
* judge if nonce from client is stale. |
* |
* @access private |
* @param string $nonce nonce value from client |
* @return bool stale |
*/ |
function _judgeStale($nonce) |
{ |
$stale = false; |
if(!$this->_decodeNonce($nonce, $time, $hash_cli)) { |
$this->nextNonce = false; |
$stale = true; |
return $stale; |
} |
if ($time < time() - $this->options['nonceLife']) { |
$this->nextNonce = $this->_getNonce(); |
$stale = true; |
} else { |
$this->nextNonce = $nonce; |
} |
return $stale; |
} |
// }}} |
// {{{ _nonceDecode() |
/** |
* decode nonce string |
* |
* @access private |
* @param string $nonce nonce value from client |
* @param string $time decoded time |
* @param string $hash decoded hash |
* @return bool false if nonce is invalid |
*/ |
function _decodeNonce($nonce, &$time, &$hash) |
{ |
if (method_exists($this, '_importGlobalVariable')) { |
$this->server = &$this->_importGlobalVariable('server'); |
} |
if (strlen($nonce) != AUTH_HTTP_NONCE_TIME_LEN + AUTH_HTTP_NONCE_HASH_LEN) { |
return false; |
} |
$time = base64_decode(substr($nonce, 0, AUTH_HTTP_NONCE_TIME_LEN)); |
$hash_cli = substr($nonce, AUTH_HTTP_NONCE_TIME_LEN, AUTH_HTTP_NONCE_HASH_LEN); |
$hash = md5($time . $this->server['HTTP_USER_AGENT'] . $this->options['noncekey']); |
if ($hash_cli != $hash) { |
return false; |
} |
return true; |
} |
// }}} |
// {{{ _getNonce() |
/** |
* return nonce to detect timeout |
* |
* @access private |
* @return string nonce value |
*/ |
function _getNonce() |
{ |
if (method_exists($this, '_importGlobalVariable')) { |
$this->server = &$this->_importGlobalVariable('server'); |
} |
$time = time(); |
$hash = md5($time . $this->server['HTTP_USER_AGENT'] . $this->options['noncekey']); |
return base64_encode($time) . $hash; |
} |
// }}} |
// {{{ authenticationInfo() |
/** |
* output HTTP Authentication-Info header |
* |
* @notes md5 hash of contents is required if 'qop' is 'auth-int' |
* |
* @access private |
* @param string MD5 hash of content |
*/ |
function authenticationInfo($contentMD5 = '') { |
if($this->getAuth() && ($this->getAuthData('a1') != null)) { |
$a1 = $this->getAuthData('a1'); |
// Work out authorisation response |
$a2unhashed = ":".$this->selfURI(); |
if($this->auth['qop'] == 'auth-int') { |
$a2unhashed .= ':'.$contentMD5; |
} |
$a2 = md5($a2unhashed); |
$combined = $a1.':'. |
$this->nonce.':'. |
$this->auth['nc'].':'. |
$this->auth['cnonce'].':'. |
$this->auth['qop'].':'. |
$a2; |
// Send authentication info |
$wwwauth = 'Authentication-Info: '; |
if($this->nonce != $this->nextNonce) { |
$wwwauth .= 'nextnonce="'.$this->nextNonce.'", '; |
} |
$wwwauth .= 'qop='.$this->auth['qop'].', '; |
$wwwauth .= 'rspauth="'.md5($combined).'", '; |
$wwwauth .= 'cnonce="'.$this->auth['cnonce'].'", '; |
$wwwauth .= 'nc='.$this->auth['nc'].''; |
header($wwwauth); |
} |
} |
// }}} |
// {{{ setOption() |
/** |
* set authentication option |
* |
* @access public |
* @param mixed $name key of option |
* @param mixed $value value of option |
* @return void |
*/ |
function setOption($name, $value = null) |
{ |
if (is_array($name)) { |
foreach($name as $key => $value) { |
if (array_key_exists( $key, $this->options)) { |
$this->options[$key] = $value; |
} |
} |
} else { |
if (array_key_exists( $name, $this->options)) { |
$this->options[$name] = $value; |
} |
} |
} |
// }}} |
// {{{ getOption() |
/** |
* get authentication option |
* |
* @access public |
* @param string $name key of option |
* @return mixed option value |
*/ |
function getOption($name) |
{ |
if (array_key_exists( $name, $this->options)) { |
return $this->options[$name]; |
} |
if ($name == 'CancelText') { |
return $this->CancelText; |
} |
if ($name == 'Realm') { |
return $this->realm; |
} |
return false; |
} |
// }}} |
// {{{ selfURI() |
/** |
* get self URI |
* |
* @access public |
* @return string self URI |
*/ |
function selfURI() |
{ |
if (method_exists($this, '_importGlobalVariable')) { |
$this->server = &$this->_importGlobalVariable('server'); |
} |
if (preg_match("/MSIE/",$this->server['HTTP_USER_AGENT'])) { |
// query string should be removed for MSIE |
$uri = preg_replace("/^(.*)\?/","\\1",$this->server['REQUEST_URI']); |
} else { |
$uri = $this->server['REQUEST_URI']; |
} |
return $uri; |
} |
// }}} |
} |
// }}} |
/* |
* Local variables: |
* tab-width: 4 |
* c-basic-offset: 4 |
* End: |
*/ |
?> |
/branches/livraison_narmer/api/pear/Auth/Auth.php |
---|
New file |
0,0 → 1,30 |
<?php |
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */ |
/** |
* Provide compatibility with previous Auth include location. |
* |
* PHP versions 4 and 5 |
* |
* LICENSE: This source file is subject to version 3.01 of the PHP license |
* that is available through the world-wide-web at the following URI: |
* http://www.php.net/license/3_01.txt. If you did not receive a copy of |
* the PHP License and are unable to obtain it through the web, please |
* send a note to license@php.net so we can mail you a copy immediately. |
* |
* @category Authentication |
* @package Auth |
* @author Martin Jansen <mj@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version CVS: $Id: Auth.php,v 1.2 2006-12-14 15:04:28 jp_milcent Exp $ |
* @link http://pear.php.net/package/Auth |
* @deprecated File deprecated since Release 1.2.0 |
*/ |
/** |
* Include Auth package |
*/ |
require_once 'Auth.php'; |
?> |
/branches/livraison_narmer/api/pear/Auth/Container.php |
---|
New file |
0,0 → 1,224 |
<?php |
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */ |
/** |
* Auth_Container Base Class |
* |
* PHP versions 4 and 5 |
* |
* LICENSE: This source file is subject to version 3.01 of the PHP license |
* that is available through the world-wide-web at the following URI: |
* http://www.php.net/license/3_01.txt. If you did not receive a copy of |
* the PHP License and are unable to obtain it through the web, please |
* send a note to license@php.net so we can mail you a copy immediately. |
* |
* @category Authentication |
* @package Auth |
* @author Martin Jansen <mj@php.net> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version CVS: $Id: Container.php,v 1.2 2006-12-14 15:04:28 jp_milcent Exp $ |
* @link http://pear.php.net/package/Auth |
*/ |
/** |
* Storage class for fetching login data |
* |
* @category Authentication |
* @package Auth |
* @author Martin Jansen <mj@php.net> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version Release: 1.4.3 File: $Revision: 1.2 $ |
* @link http://pear.php.net/package/Auth |
*/ |
class Auth_Container |
{ |
// {{{ properties |
/** |
* User that is currently selected from the storage container. |
* |
* @access public |
*/ |
var $activeUser = ""; |
// }}} |
// {{{ Auth_Container() [constructor] |
/** |
* Constructor |
* |
* Has to be overwritten by each storage class |
* |
* @access public |
*/ |
function Auth_Container() |
{ |
} |
// }}} |
// {{{ fetchData() |
/** |
* Fetch data from storage container |
* |
* Has to be overwritten by each storage class |
* |
* @access public |
*/ |
function fetchData($username, $password, $isChallengeResponse=false) |
{ |
} |
// }}} |
// {{{ verifyPassword() |
/** |
* Crypt and verfiy the entered password |
* |
* @param string Entered password |
* @param string Password from the data container (usually this password |
* is already encrypted. |
* @param string Type of algorithm with which the password from |
* the container has been crypted. (md5, crypt etc.) |
* Defaults to "md5". |
* @return bool True, if the passwords match |
*/ |
function verifyPassword($password1, $password2, $cryptType = "md5") |
{ |
switch ($cryptType) { |
case "crypt" : |
return ((string)crypt($password1, $password2) === (string)$password2); |
break; |
case "none" : |
case "" : |
return ((string)$password1 === (string)$password2); |
break; |
case "md5" : |
return ((string)md5($password1) === (string)$password2); |
break; |
default : |
if (function_exists($cryptType)) { |
return ((string)$cryptType($password1) === (string)$password2); |
} elseif (method_exists($this,$cryptType)) { |
return ((string)$this->$cryptType($password1) === (string)$password2); |
} else { |
return false; |
} |
break; |
} |
} |
// }}} |
// {{{ supportsChallengeResponse() |
/** |
* Returns true if the container supports Challenge Response |
* password authentication |
*/ |
function supportsChallengeResponse() |
{ |
return(false); |
} |
// }}} |
// {{{ getCryptType() |
/** |
* Returns the crypt current crypt type of the container |
* |
* @return string |
*/ |
function getCryptType() |
{ |
return(''); |
} |
// }}} |
// {{{ listUsers() |
/** |
* List all users that are available from the storage container |
*/ |
function listUsers() |
{ |
return AUTH_METHOD_NOT_SUPPORTED; |
} |
// }}} |
// {{{ getUser() |
/** |
* Returns a user assoc array |
* |
* Containers which want should overide this |
* |
* @param string The username |
*/ |
function getUser($username) |
{ |
$users = $this->listUsers(); |
if ($users === AUTH_METHOD_NOT_SUPPORTED) { |
return AUTH_METHOD_NOT_SUPPORTED; |
} |
for ($i=0; $c = count($users), $i<$c; $i++) { |
if ($users[$i]['username'] == $username) { |
return $users[$i]; |
} |
} |
return false; |
} |
// }}} |
// {{{ addUser() |
/** |
* Add a new user to the storage container |
* |
* @param string Username |
* @param string Password |
* @param array Additional information |
* |
* @return boolean |
*/ |
function addUser($username, $password, $additional=null) |
{ |
return AUTH_METHOD_NOT_SUPPORTED; |
} |
// }}} |
// {{{ removeUser() |
/** |
* Remove user from the storage container |
* |
* @param string Username |
*/ |
function removeUser($username) |
{ |
return AUTH_METHOD_NOT_SUPPORTED; |
} |
// }}} |
// {{{ changePassword() |
/** |
* Change password for user in the storage container |
* |
* @param string Username |
* @param string The new password |
*/ |
function changePassword($username, $password) |
{ |
return AUTH_METHOD_NOT_SUPPORTED; |
} |
// }}} |
} |
?> |
/branches/livraison_narmer/api/pear/Auth/SASL.php |
---|
New file |
0,0 → 1,98 |
<?php |
// +-----------------------------------------------------------------------+ |
// | Copyright (c) 2002-2003 Richard Heyes | |
// | All rights reserved. | |
// | | |
// | Redistribution and use in source and binary forms, with or without | |
// | modification, are permitted provided that the following conditions | |
// | are met: | |
// | | |
// | o Redistributions of source code must retain the above copyright | |
// | notice, this list of conditions and the following disclaimer. | |
// | o Redistributions in binary form must reproduce the above copyright | |
// | notice, this list of conditions and the following disclaimer in the | |
// | documentation and/or other materials provided with the distribution.| |
// | o The names of the authors may not be used to endorse or promote | |
// | products derived from this software without specific prior written | |
// | permission. | |
// | | |
// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | |
// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | |
// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | |
// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | |
// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | |
// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | |
// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | |
// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | |
// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | |
// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
// | | |
// +-----------------------------------------------------------------------+ |
// | Author: Richard Heyes <richard@php.net> | |
// +-----------------------------------------------------------------------+ |
// |
// $Id: SASL.php,v 1.1 2006-12-14 15:04:28 jp_milcent Exp $ |
/** |
* Client implementation of various SASL mechanisms |
* |
* @author Richard Heyes <richard@php.net> |
* @access public |
* @version 1.0 |
* @package Auth_SASL |
*/ |
require_once('PEAR.php'); |
class Auth_SASL |
{ |
/** |
* Factory class. Returns an object of the request |
* type. |
* |
* @param string $type One of: Anonymous |
* Plain |
* CramMD5 |
* DigestMD5 |
* Types are not case sensitive |
*/ |
function &factory($type) |
{ |
switch (strtolower($type)) { |
case 'anonymous': |
$filename = 'Auth/SASL/Anonymous.php'; |
$classname = 'Auth_SASL_Anonymous'; |
break; |
case 'login': |
$filename = 'Auth/SASL/Login.php'; |
$classname = 'Auth_SASL_Login'; |
break; |
case 'plain': |
$filename = 'Auth/SASL/Plain.php'; |
$classname = 'Auth_SASL_Plain'; |
break; |
case 'crammd5': |
$filename = 'Auth/SASL/CramMD5.php'; |
$classname = 'Auth_SASL_CramMD5'; |
break; |
case 'digestmd5': |
$filename = 'Auth/SASL/DigestMD5.php'; |
$classname = 'Auth_SASL_DigestMD5'; |
break; |
default: |
return PEAR::raiseError('Invalid SASL mechanism type'); |
break; |
} |
require_once($filename); |
return new $classname(); |
} |
} |
?> |
/branches/livraison_narmer/api/pear/Auth/Controller.php |
---|
New file |
0,0 → 1,302 |
<?php |
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */ |
/** |
* Auth Controller |
* |
* PHP versions 4 and 5 |
* |
* LICENSE: This source file is subject to version 3.01 of the PHP license |
* that is available through the world-wide-web at the following URI: |
* http://www.php.net/license/3_01.txt. If you did not receive a copy of |
* the PHP License and are unable to obtain it through the web, please |
* send a note to license@php.net so we can mail you a copy immediately. |
* |
* @category Authentication |
* @package Auth |
* @author Yavor Shahpasov <yavo@netsmart.com.cy> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version CVS: $Id: Controller.php,v 1.1 2006-12-14 15:04:28 jp_milcent Exp $ |
* @link http://pear.php.net/package/Auth |
* @since File available since Release 1.3.0 |
*/ |
/** |
* Controlls access to a group of php access |
* and redirects to a predefined login page as |
* needed |
* |
* In all pages |
* <code> |
* include_once('Auth.php'); |
* include_once('Auth/Controller.php'); |
* $_auth = new Auth('File', 'passwd'); |
* $authController = new Auth_Controller($_auth, 'login.php', 'index.php'); |
* $authController->start(); |
* </code> |
* |
* In login.php |
* <code> |
* include_once('Auth.php'); |
* include_once('Auth/Controller.php'); |
* $_auth = new Auth('File', 'passwd'); |
* $authController = new Auth_Controller($_auth, 'login.php', 'index.php'); |
* $authController->start(); |
* if( $authController->isAuthorised() ){ |
* $authController->redirectBack(); |
* } |
* </code> |
* |
* @category Authentication |
* @author Yavor Shahpasov <yavo@netsmart.com.cy> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version Release: 1.4.3 File: $Revision: 1.1 $ |
* @link http://pear.php.net/package/Auth |
* @since Class available since Release 1.3.0 |
*/ |
class Auth_Controller |
{ |
// {{{ properties |
/** |
* The Auth instance this controller is managing |
* |
* @var object Auth |
*/ |
var $auth = null; |
/** |
* The login URL |
* @var string |
* */ |
var $login = null; |
/** |
* The default index page to use when the caller page is not set |
* |
* @var string |
*/ |
var $default = null; |
/** |
* If this is set to true after a succesfull login the |
* Auth_Controller::redirectBack() is invoked automatically |
* |
* @var boolean |
*/ |
var $autoRedirectBack = false; |
// }}} |
// {{{ Auth_Controller() [constructor] |
/** |
* Constructor |
* |
* @param Auth An auth instance |
* @param string The login page |
* @param string The default page to go to if return page is not set |
* @param array Some rules about which urls need to be sent to the login page |
* @return void |
* @todo Add a list of urls which need redirection |
*/ |
function Auth_Controller(&$auth_obj, $login='login.php', $default='index.php', $accessList=array()) |
{ |
$this->auth =& $auth_obj; |
$this->_loginPage = $login; |
$this->_defaultPage = $default; |
@session_start(); |
if (!empty($_GET['return']) && $_GET['return'] && !strstr($_GET['return'], $this->_loginPage)) { |
$this->auth->setAuthData('returnUrl', $_GET['return']); |
} |
if(!empty($_GET['authstatus']) && $this->auth->status == '') { |
$this->auth->status = $_GET['authstatus']; |
} |
} |
// }}} |
// {{{ setAutoRedirectBack() |
/** |
* Enables auto redirection when login is done |
* |
* @param bool Sets the autoRedirectBack flag to this |
* @see Auth_Controller::autoRedirectBack |
* @return void |
*/ |
function setAutoRedirectBack($flag = true) |
{ |
$this->autoRedirectBack = $flag; |
} |
// }}} |
// {{{ redirectBack() |
/** |
* Redirects Back to the calling page |
* |
* @return void |
*/ |
function redirectBack() |
{ |
// If redirectback go there |
// else go to the default page |
$returnUrl = $this->auth->getAuthData('returnUrl'); |
if(!$returnUrl) { |
$returnUrl = $this->_defaultPage; |
} |
// Add some entropy to the return to make it unique |
// avoind problems with cached pages and proxies |
if(strpos($returnUrl, '?') === false) { |
$returnUrl .= '?'; |
} |
$returnUrl .= uniqid(''); |
// Track the auth status |
if($this->auth->status != '') { |
$url .= '&authstatus='.$this->auth->status; |
} |
header('Location:'.$returnUrl); |
print("You could not be redirected to <a href=\"$returnUrl\">$returnUrl</a>"); |
} |
// }}} |
// {{{ redirectLogin() |
/** |
* Redirects to the login Page if not authorised |
* |
* put return page on the query or in auth |
* |
* @return void |
*/ |
function redirectLogin() |
{ |
// Go to the login Page |
// For Auth, put some check to avoid infinite redirects, this should at least exclude |
// the login page |
$url = $this->_loginPage; |
if(strpos($url, '?') === false) { |
$url .= '?'; |
} |
if(!strstr($_SERVER['PHP_SELF'], $this->_loginPage)) { |
$url .= 'return='.urlencode($_SERVER['PHP_SELF']); |
} |
// Track the auth status |
if($this->auth->status != '') { |
$url .= '&authstatus='.$this->auth->status; |
} |
header('Location:'.$url); |
print("You could not be redirected to <a href=\"$url\">$url</a>"); |
} |
// }}} |
// {{{ start() |
/** |
* Starts the Auth Procedure |
* |
* If the page requires login the user is redirected to the login page |
* otherwise the Auth::start is called to initialize Auth |
* |
* @return void |
* @todo Implement an access list which specifies which urls/pages need login and which do not |
*/ |
function start() |
{ |
// Check the accessList here |
// ACL should be a list of urls with allow/deny |
// If allow set allowLogin to false |
// Some wild card matching should be implemented ?,* |
if(!strstr($_SERVER['PHP_SELF'], $this->_loginPage) && !$this->auth->checkAuth()) { |
$this->redirectLogin(); |
} else { |
$this->auth->start(); |
// Logged on and on login page |
if(strstr($_SERVER['PHP_SELF'], $this->_loginPage) && $this->auth->checkAuth()){ |
$this->autoRedirectBack ? |
$this->redirectBack() : |
null ; |
} |
} |
} |
// }}} |
// {{{ isAuthorised() |
/** |
* Checks is the user is logged on |
* @see Auth::checkAuth() |
*/ |
function isAuthorised() |
{ |
return($this->auth->checkAuth()); |
} |
// }}} |
// {{{ checkAuth() |
/** |
* Proxy call to auth |
* @see Auth::checkAuth() |
*/ |
function checkAuth() |
{ |
return($this->auth->checkAuth()); |
} |
// }}} |
// {{{ logout() |
/** |
* Proxy call to auth |
* @see Auth::logout() |
*/ |
function logout() |
{ |
return($this->auth->logout()); |
} |
// }}} |
// {{{ getUsername() |
/** |
* Proxy call to auth |
* @see Auth::getUsername() |
*/ |
function getUsername() |
{ |
return($this->auth->getUsername()); |
} |
// }}} |
// {{{ getStatus() |
/** |
* Proxy call to auth |
* @see Auth::getStatus() |
*/ |
function getStatus() |
{ |
return($this->auth->getStatus()); |
} |
// }}} |
} |
?> |
/branches/livraison_narmer/api/pear/Auth/PrefManager.php |
---|
New file |
0,0 → 1,426 |
<?php |
require_once("DB.php"); |
/** |
* A simple preference manager, takes userid, preference name pairs and returns the value |
* of that preference. |
* |
* CREATE TABLE `preferences` ( |
* `user_id` varchar( 255 ) NOT NULL default '', |
* `pref_id` varchar( 32 ) NOT NULL default '', |
* `pref_value` longtext NOT NULL , |
* PRIMARY KEY ( `user_id` , `pref_id` ) |
* ) |
* |
* @author Jon Wood <jon@jellybob.co.uk> |
* @package Auth_PrefManager |
* @category Authentication |
*/ |
class Auth_PrefManager |
{ |
/** |
* The database object. |
* @var object |
* @access private |
*/ |
var $_db; |
/** |
* The user name to get preferences from if the user specified doesn't |
* have that preference set. |
* @var string |
* @access private |
*/ |
var $_defaultUser = "__default__"; |
/** |
* Should we search for default values, or just fail when we find out that |
* the specified user didn't have it set. |
* |
* @var bool |
* @access private |
*/ |
var $_returnDefaults = true; |
/** |
* The table containing the preferences. |
* @var string |
* @access private |
*/ |
var $_table = "preferences"; |
/** |
* The column containing user ids. |
* @var string |
* @access private |
*/ |
var $_userColumn = "user_id"; |
/** |
* The column containing preference names. |
* @var string |
* @access private |
*/ |
var $_nameColumn = "pref_id"; |
/** |
* The column containing preference values. |
* @var string |
* @access private |
*/ |
var $_valueColumn = "pref_value"; |
/** |
* The quoted value column. |
* @var string |
* @access private |
*/ |
var $_valueColumnQuoted = "pref_value"; |
/** |
* The session variable that the cache array is stored in. |
* @var string |
* @access private |
*/ |
var $_cacheName = "prefCache"; |
/** |
* The last error given. |
* @var string |
* @access private |
*/ |
var $_lastError; |
/** |
* Defines whether the cache should be used or not. |
* @var bool |
* @access private |
*/ |
var $_useCache = true; |
/** |
* Defines whether values should be serialized before saving. |
* @var bool |
* @access private |
*/ |
var $_serialize = false; |
/** |
* Constructor |
* |
* Options: |
* table: The table to get prefs from. [preferences] |
* userColumn: The field name to search for userid's [user_id] |
* nameColumn: The field name to search for preference names [pref_name] |
* valueColumn: The field name to search for preference values [pref_value] |
* defaultUser: The userid assigned to default values [__default__] |
* cacheName: The name of cache in the session variable ($_SESSION[cacheName]) [prefsCache] |
* useCache: Whether or not values should be cached. |
* serialize: Should preference values be serialzed before saving? |
* |
* @param string $dsn The DSN of the database connection to make, or a DB object. |
* @param array $properties An array of properties to set. |
* @param string $defaultUser The default user to manage for. |
* @return bool Success or failure. |
* @access public |
*/ |
function Auth_PrefManager($dsn, $properties = NULL) |
{ |
// Connect to the database. |
if (isset($dsn)) { |
if (is_string($dsn)) { |
$this->_db = DB::Connect($dsn); |
if (DB::isError($this->_db)) { |
$this->_lastError = "DB Error: ".$this->_db->getMessage(); |
} |
} else if (is_subclass_of($dsn, 'db_common')) { |
$this->_db = &$dsn; |
} else { |
$this->_lastError = "Invalid DSN specified."; |
return false; |
} |
} else { |
$this->_lastError = "No DSN specified."; |
return false; |
} |
if (is_array($properties)) { |
if (isset($properties["table"])) { $this->_table = $this->_db->quoteIdentifier($properties["table"]); } |
if (isset($properties["userColumn"])) { $this->_userColumn = $this->_db->quoteIdentifier($properties["userColumn"]); } |
if (isset($properties["nameColumn"])) { $this->_nameColumn = $this->_db->quoteIdentifier($properties["nameColumn"]); } |
if (isset($properties["valueColumn"])) { $this->_valueColumn = $properties["valueColumn"]; } |
if (isset($properties["valueColumn"])) { $this->_valueColumnQuoted = $this->_db->quoteIdentifier($properties["valueColumn"]); } |
if (isset($properties["defaultUser"])) { $this->_defaultUser = $properties["defaultUser"]; } |
if (isset($properties["cacheName"])) { $this->_cacheName = $properties["cacheName"]; } |
if (isset($properties["useCache"])) { $this->_useCache = $properties["useCache"]; } |
if (isset($properties["serialize"])) { $this->_serialize = $properties["serialize"]; } |
} |
return true; |
} |
function setReturnDefaults($returnDefaults = true) |
{ |
if (is_bool($returnDefaults)) { |
$this->_returnDefaults = $returnDefaults; |
} |
} |
/** |
* Sets whether the cache should be used. |
* |
* @param bool $use Should the cache be used. |
* @access public |
*/ |
function useCache($use = true) |
{ |
$this->_useCache = $use; |
} |
/** |
* Cleans out the cache. |
* |
* @access public |
*/ |
function clearCache() |
{ |
unset($_SESSION[$this->_cacheName]); |
} |
/** |
* Get a preference for the specified user, or, if returning default values |
* is enabled, the default. |
* |
* @param string $user_id The user to get the preference for. |
* @param string $pref_id The preference to get. |
* @param bool $showDefaults Should default values be searched (overrides the global setting). |
* @return mixed The value if it's found, or NULL if it isn't. |
* @access public |
*/ |
function getPref($user_id, $pref_id, $showDefaults = true) |
{ |
if (isset($_SESSION[$this->_cacheName][$user_id][$pref_id]) && $this->_useCache) { |
// Value is cached for the specified user, so give them the cached copy. |
return $_SESSION[$this->_cacheName][$user_id][$pref_id]; |
} else { |
// Not cached, search the database for this user's preference. |
$query = sprintf("SELECT * FROM %s WHERE %s=%s AND %s=%s", $this->_table, |
$this->_userColumn, |
$this->_db->quote($user_id), |
$this->_nameColumn, |
$this->_db->quote($pref_id)); |
$result = $this->_db->query($query); |
if (DB::isError($result)) { |
// Ouch! The query failed! |
$this->_lastError = "DB Error: ".$result->getMessage(); |
return NULL; |
} else if ($result->numRows()) { |
// The query found a value, so we can cache that, and then return it. |
$row = $result->fetchRow(DB_FETCHMODE_ASSOC); |
$_SESSION[$this->_cacheName][$user_id][$pref_id] = $this->_unpack($row[$this->_valueColumn]); |
return $_SESSION[$this->_cacheName][$user_id][$pref_id]; |
} else if ($this->_returnDefaults && $showDefaults) { |
// I was doing this with a call to getPref again, but it threw things into an |
// infinite loop if the default value didn't exist. If you can fix that, it would |
// be great ;) |
if (isset($_SESSION[$this->_cacheName][$this->_defaultUser][$pref_id]) && $this->_useCache) { |
$_SESSION[$this->_cacheName][$user_id][$pref_id] = $_SESSION[$this->_cacheName][$this->_defaultUser][$pref_id]; |
return $_SESSION[$this->_cacheName][$this->_defaultUser][$pref_id]; |
} else { |
$query = sprintf("SELECT * FROM %s WHERE %s=%s AND %s=%s", $this->_table, |
$this->_userColumn, |
$this->_db->quote($this->_defaultUser), |
$this->_nameColumn, |
$this->_db->quote($pref_id)); |
$result = $this->_db->query($query); |
if (DB::isError($result)) { |
$this->_lastError = "DB Error: ".$result->getMessage(); |
return NULL; |
} else { |
if ($result->numRows()) { |
$row = $result->fetchRow(DB_FETCHMODE_ASSOC); |
$_SESSION[$this->_cacheName][$this->_defaultUser][$pref_id] = $this->_unpack($row[$this->_valueColumn]); |
$_SESSION[$this->_cacheName][$user_id][$pref_id] = $_SESSION[$this->_cacheName][$this->_defaultUser][$pref_id]; |
return $_SESSION[$this->_cacheName][$user_id][$pref_id]; |
} else { |
return NULL; |
} |
} |
} |
} else { |
// We've used up all the resources we're allowed to search, so return a NULL. |
return NULL; |
} |
} |
} |
/** |
* A shortcut function for getPref($this->_defaultUser, $pref_id, $value), |
* useful if you have a logged in user, but want to get defaults anyway. |
* |
* @param string $pref_id The name of the preference to get. |
* @return mixed The value if it's found, or NULL if it isn't. |
* @access public |
*/ |
function getDefaultPref($pref_id) |
{ |
return $this->getPref($this->_defaultUser, $pref_id); |
} |
/** |
* Set a preference for the specified user. |
* |
* @param string $user_id The user to set for. |
* @param string $pref_id The preference to set. |
* @param mixed $value The value it should be set to. |
* @return bool Sucess or failure. |
* @access public |
*/ |
function setPref($user_id, $pref_id, $value) |
{ |
// Start off by checking if the preference is already set (if it is we need to do |
// an UPDATE, if not, it's an INSERT. |
if ($this->_exists($user_id, $pref_id, false)) { |
$query = sprintf("UPDATE %s SET %s=%s WHERE %s=%s AND %s=%s", $this->_table, |
$this->_valueColumnQuoted, |
$this->_db->quote($this->_pack($value)), |
$this->_userColumn, |
$this->_db->quote($user_id), |
$this->_nameColumn, |
$this->_db->quote($pref_id)); |
} else { |
$query = sprintf("INSERT INTO %s (%s, %s, %s) VALUES(%s, %s, %s)", $this->_table, |
$this->_userColumn, |
$this->_nameColumn, |
$this->_valueColumnQuoted, |
$this->_db->quote($user_id), |
$this->_db->quote($pref_id), |
$this->_db->quote($this->_pack($value))); |
} |
$result = $this->_db->query($query); |
if (DB::isError($result)) { |
$this->_lastError = "DB Error: ".$result->getMessage(); |
return false; |
} else { |
if ($this->_useCache) { |
$_SESSION[$this->_cacheName][$user_id][$pref_id] = $value; |
} |
return true; |
} |
} |
/** |
* A shortcut function for setPref($this->_defaultUser, $pref_id, $value) |
* |
* @param string $pref_id The name of the preference to set. |
* @param mixed $value The value to set it to. |
* @return bool Sucess or failure. |
* @access public |
*/ |
function setDefaultPref($pref_id, $value) |
{ |
return $this->setPref($this->_defaultUser, $pref_id, $value); |
} |
/** |
* Deletes a preference for the specified user. |
* |
* @param string $user_id The userid of the user to delete from. |
* @param string $pref_id The preference to delete. |
* @return bool Success/Failure |
* @access public |
*/ |
function deletePref($user_id, $pref_id) |
{ |
if ($this->getPref($user_id, $pref_id) == NULL) { |
// The user doesn't have this variable anyway ;) |
return true; |
} else { |
$query = sprintf("DELETE FROM %s WHERE %s=%s AND %s=%s", $this->_table, |
$this->_userColumn, |
$this->_db->quote($user_id), |
$this->_nameColumn, |
$this->_db->quote($pref_id)); |
$result = $this->_db->query($query); |
if (DB::isError($result)) { |
$this->_lastError = "DB Error: ".$result->getMessage(); |
return false; |
} else { |
if ($this->_useCache) { |
unset($_SESSION[$this->_cacheName][$user_id][$pref_id]); |
} |
return true; |
} |
} |
} |
/** |
* Deletes a preference for the default user. |
* |
* @param string $pref_id The preference to delete. |
* @return bool Success/Failure |
* @access public |
*/ |
function deleteDefaultPref($pref_id) |
{ |
return $this->deletePref($this->_defaultUser, $pref_id); |
} |
/** |
* Checks if a preference exists in the database. |
* |
* @param string $user_id The userid of the preference owner. |
* @param string $pref_id The preference to check for. |
* @return bool True if the preference exists. |
* @access private |
*/ |
function _exists($user_id, $pref_id) |
{ |
$query = sprintf("SELECT COUNT(%s) FROM %s WHERE %s=%s AND %s=%s", $this->_nameColumn, |
$this->_table, |
$this->_userColumn, |
$this->_db->quoteSmart($user_id), |
$this->_nameColumn, |
$this->_db->quote($pref_id)); |
$result = $this->_db->getOne($query); |
if (DB::isError($result)) { |
$this->_lastError = "DB Error: ".$result->getMessage(); |
return false; |
} else { |
return (bool)$result; |
} |
} |
/** |
* Does anything needed to prepare a value for saving in the database. |
* |
* @param mixed $value The value to be saved. |
* @return string The value in a format valid for saving to the database. |
* @access private |
*/ |
function _pack($value) |
{ |
if ($this->_serialize) { |
return serialize($value); |
} else { |
return $value; |
} |
} |
/** |
* Does anything needed to create a value of the preference, such as unserializing. |
* |
* @param string $value The value of the preference. |
* @return mixed The unpacked version of the preference. |
* @access private |
*/ |
function _unpack($value) |
{ |
if ($this->_serialize) { |
return unserialize($value); |
} else { |
return $value; |
} |
} |
} |
?> |
/branches/livraison_narmer/api/pear/Auth/RADIUS.php |
---|
New file |
0,0 → 1,964 |
<?php |
/* vim: set expandtab tabstop=4 shiftwidth=4: */ |
/* |
Copyright (c) 2003, Michael Bretterklieber <michael@bretterklieber.com> |
All rights reserved. |
Redistribution and use in source and binary forms, with or without |
modification, are permitted provided that the following conditions |
are met: |
1. Redistributions of source code must retain the above copyright |
notice, this list of conditions and the following disclaimer. |
2. Redistributions in binary form must reproduce the above copyright |
notice, this list of conditions and the following disclaimer in the |
documentation and/or other materials provided with the distribution. |
3. The names of the authors may not be used to endorse or promote products |
derived from this software without specific prior written permission. |
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND |
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED |
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. |
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, |
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY |
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING |
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, |
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
This code cannot simply be copied and put under the GNU Public License or |
any other GPL-like (LGPL, GPL2) License. |
$Id: RADIUS.php,v 1.1 2006-12-14 15:04:28 jp_milcent Exp $ |
*/ |
require_once 'PEAR.php'; |
/** |
* Client implementation of RADIUS. This are wrapper classes for |
* the RADIUS PECL. |
* Provides RADIUS Authentication (RFC2865) and RADIUS Accounting (RFC2866). |
* |
* @package Auth_RADIUS |
* @author Michael Bretterklieber <michael@bretterklieber.com> |
* @access public |
* @version $Revision: 1.1 $ |
*/ |
/** |
* class Auth_RADIUS |
* |
* Abstract base class for RADIUS |
* |
* @package Auth_RADIUS |
*/ |
class Auth_RADIUS extends PEAR { |
/** |
* List of RADIUS servers. |
* @var array |
* @see addServer(), putServer() |
*/ |
var $_servers = array(); |
/** |
* Path to the configuration-file. |
* @var string |
* @see setConfigFile() |
*/ |
var $_configfile = null; |
/** |
* Resource. |
* @var resource |
* @see open(), close() |
*/ |
var $res = null; |
/** |
* Username for authentication and accounting requests. |
* @var string |
*/ |
var $username = null; |
/** |
* Password for plaintext-authentication (PAP). |
* @var string |
*/ |
var $password = null; |
/** |
* List of known attributes. |
* @var array |
* @see dumpAttributes(), getAttributes() |
*/ |
var $attributes = array(); |
/** |
* List of raw attributes. |
* @var array |
* @see dumpAttributes(), getAttributes() |
*/ |
var $rawAttributes = array(); |
/** |
* List of raw vendor specific attributes. |
* @var array |
* @see dumpAttributes(), getAttributes() |
*/ |
var $rawVendorAttributes = array(); |
/** |
* Constructor |
* |
* Loads the RADIUS PECL/extension |
* |
* @return void |
*/ |
function Auth_RADIUS() |
{ |
$this->PEAR(); |
$this->loadExtension('radius'); |
} |
/** |
* Adds a RADIUS server to the list of servers for requests. |
* |
* At most 10 servers may be specified. When multiple servers |
* are given, they are tried in round-robin fashion until a |
* valid response is received |
* |
* @access public |
* @param string $servername Servername or IP-Address |
* @param integer $port Portnumber |
* @param string $sharedSecret Shared secret |
* @param integer $timeout Timeout for each request |
* @param integer $maxtries Max. retries for each request |
* @return void |
*/ |
function addServer($servername = 'localhost', $port = 0, $sharedSecret = 'testing123', $timeout = 3, $maxtries = 3) |
{ |
$this->_servers[] = array($servername, $port, $sharedSecret, $timeout, $maxtries); |
} |
/** |
* Returns an error message, if an error occurred. |
* |
* @access public |
* @return string |
*/ |
function getError() |
{ |
return radius_strerror($this->res); |
} |
/** |
* Sets the configuration-file. |
* |
* @access public |
* @param string $file Path to the configuration file |
* @return void |
*/ |
function setConfigfile($file) |
{ |
$this->_configfile = $file; |
} |
/** |
* Puts an attribute. |
* |
* @access public |
* @param integer $attrib Attribute-number |
* @param mixed $port Attribute-value |
* @param type $type Attribute-type |
* @return bool true on success, false on error |
*/ |
function putAttribute($attrib, $value, $type = null) |
{ |
if ($type == null) { |
$type = gettype($value); |
} |
switch ($type) { |
case 'integer': |
return radius_put_int($this->res, $attrib, $value); |
case 'addr': |
return radius_put_addr($this->res, $attrib, $value); |
case 'string': |
default: |
return radius_put_attr($this->res, $attrib, $value); |
} |
} |
/** |
* Puts a vendor-specific attribute. |
* |
* @access public |
* @param integer $vendor Vendor (MSoft, Cisco, ...) |
* @param integer $attrib Attribute-number |
* @param mixed $port Attribute-value |
* @param type $type Attribute-type |
* @return bool true on success, false on error |
*/ |
function putVendorAttribute($vendor, $attrib, $value, $type = null) |
{ |
if ($type == null) { |
$type = gettype($value); |
} |
switch ($type) { |
case 'integer': |
return radius_put_vendor_int($this->res, $vendor, $attrib, $value); |
case 'addr': |
return radius_put_vendor_addr($this->res, $vendor,$attrib, $value); |
case 'string': |
default: |
return radius_put_vendor_attr($this->res, $vendor, $attrib, $value); |
} |
} |
/** |
* Prints known attributes received from the server. |
* |
* @access public |
*/ |
function dumpAttributes() |
{ |
foreach ($this->attributes as $name => $data) { |
echo "$name:$data<br>\n"; |
} |
} |
/** |
* Overwrite this. |
* |
* @access public |
*/ |
function open() |
{ |
} |
/** |
* Overwrite this. |
* |
* @access public |
*/ |
function createRequest() |
{ |
} |
/** |
* Puts standard attributes. |
* |
* @access public |
*/ |
function putStandardAttributes() |
{ |
if (isset($_SERVER)) { |
$var = &$_SERVER; |
} else { |
$var = &$GLOBALS['HTTP_SERVER_VARS']; |
} |
$this->putAttribute(RADIUS_NAS_IDENTIFIER, isset($var['HTTP_HOST']) ? $var['HTTP_HOST'] : 'localhost'); |
$this->putAttribute(RADIUS_NAS_PORT_TYPE, RADIUS_VIRTUAL); |
$this->putAttribute(RADIUS_SERVICE_TYPE, RADIUS_FRAMED); |
$this->putAttribute(RADIUS_FRAMED_PROTOCOL, RADIUS_PPP); |
$this->putAttribute(RADIUS_CALLING_STATION_ID, isset($var['REMOTE_HOST']) ? $var['REMOTE_HOST'] : '127.0.0.1'); |
} |
/** |
* Puts custom attributes. |
* |
* @access public |
*/ |
function putAuthAttributes() |
{ |
if (isset($this->username)) { |
$this->putAttribute(RADIUS_USER_NAME, $this->username); |
} |
} |
/** |
* Configures the radius library. |
* |
* @access public |
* @param string $servername Servername or IP-Address |
* @param integer $port Portnumber |
* @param string $sharedSecret Shared secret |
* @param integer $timeout Timeout for each request |
* @param integer $maxtries Max. retries for each request |
* @return bool true on success, false on error |
* @see addServer() |
*/ |
function putServer($servername, $port = 0, $sharedsecret = 'testing123', $timeout = 3, $maxtries = 3) |
{ |
if (!radius_add_server($this->res, $servername, $port, $sharedsecret, $timeout, $maxtries)) { |
return false; |
} |
return true; |
} |
/** |
* Configures the radius library via external configurationfile |
* |
* @access public |
* @param string $servername Servername or IP-Address |
* @return bool true on success, false on error |
*/ |
function putConfigfile($file) |
{ |
if (!radius_config($this->res, $file)) { |
return false; |
} |
return true; |
} |
/** |
* Initiates a RADIUS request. |
* |
* @access public |
* @return bool true on success, false on errors |
*/ |
function start() |
{ |
if (!$this->open()) { |
return false; |
} |
foreach ($this->_servers as $s) { |
// Servername, port, sharedsecret, timeout, retries |
if (!$this->putServer($s[0], $s[1], $s[2], $s[3], $s[4])) { |
return false; |
} |
} |
if (!empty($this->_configfile)) { |
if (!$this->putConfigfile($this->_configfile)) { |
return false; |
} |
} |
$this->createRequest(); |
$this->putStandardAttributes(); |
$this->putAuthAttributes(); |
return true; |
} |
/** |
* Sends a prepared RADIUS request and waits for a response |
* |
* @access public |
* @return mixed true on success, false on reject, PEAR_Error on error |
*/ |
function send() |
{ |
$req = radius_send_request($this->res); |
if (!$req) { |
return $this->raiseError('Error sending request: ' . $this->getError()); |
} |
switch($req) { |
case RADIUS_ACCESS_ACCEPT: |
if (is_subclass_of($this, 'auth_radius_acct')) { |
return $this->raiseError('RADIUS_ACCESS_ACCEPT is unexpected for accounting'); |
} |
return true; |
case RADIUS_ACCESS_REJECT: |
return false; |
case RADIUS_ACCOUNTING_RESPONSE: |
if (is_subclass_of($this, 'auth_radius_pap')) { |
return $this->raiseError('RADIUS_ACCOUNTING_RESPONSE is unexpected for authentication'); |
} |
return true; |
default: |
return $this->raiseError("Unexpected return value: $req"); |
} |
} |
/** |
* Reads all received attributes after sending the request. |
* |
* This methos stores know attributes in the property attributes, |
* all attributes (including known attibutes) are stored in rawAttributes |
* or rawVendorAttributes. |
* NOTE: call this functio also even if the request was rejected, because the |
* Server returns usualy an errormessage |
* |
* @access public |
* @return bool true on success, false on error |
*/ |
function getAttributes() |
{ |
while ($attrib = radius_get_attr($this->res)) { |
if (!is_array($attrib)) { |
return false; |
} |
$attr = $attrib['attr']; |
$data = $attrib['data']; |
$this->rawAttributes[$attr] = $data; |
switch ($attr) { |
case RADIUS_FRAMED_IP_ADDRESS: |
$this->attributes['framed_ip'] = radius_cvt_addr($data); |
break; |
case RADIUS_FRAMED_IP_NETMASK: |
$this->attributes['framed_mask'] = radius_cvt_addr($data); |
break; |
case RADIUS_FRAMED_MTU: |
$this->attributes['framed_mtu'] = radius_cvt_int($data); |
break; |
case RADIUS_FRAMED_COMPRESSION: |
$this->attributes['framed_compression'] = radius_cvt_int($data); |
break; |
case RADIUS_SESSION_TIMEOUT: |
$this->attributes['session_timeout'] = radius_cvt_int($data); |
break; |
case RADIUS_IDLE_TIMEOUT: |
$this->attributes['idle_timeout'] = radius_cvt_int($data); |
break; |
case RADIUS_SERVICE_TYPE: |
$this->attributes['service_type'] = radius_cvt_int($data); |
break; |
case RADIUS_CLASS: |
$this->attributes['class'] = radius_cvt_int($data); |
break; |
case RADIUS_FRAMED_PROTOCOL: |
$this->attributes['framed_protocol'] = radius_cvt_int($data); |
break; |
case RADIUS_FRAMED_ROUTING: |
$this->attributes['framed_routing'] = radius_cvt_int($data); |
break; |
case RADIUS_FILTER_ID: |
$this->attributes['filter_id'] = radius_cvt_string($data); |
break; |
case RADIUS_VENDOR_SPECIFIC: |
$attribv = radius_get_vendor_attr($data); |
if (!is_array($attribv)) { |
return false; |
} |
$vendor = $attribv['vendor']; |
$attrv = $attribv['attr']; |
$datav = $attribv['data']; |
$this->rawVendorAttributes[$vendor][$attrv] = $datav; |
if ($vendor == RADIUS_VENDOR_MICROSOFT) { |
switch ($attrv) { |
case RADIUS_MICROSOFT_MS_CHAP2_SUCCESS: |
$this->attributes['ms_chap2_success'] = radius_cvt_string($datav); |
break; |
case RADIUS_MICROSOFT_MS_CHAP_ERROR: |
$this->attributes['ms_chap_error'] = radius_cvt_string(substr($datav,1)); |
break; |
case RADIUS_MICROSOFT_MS_CHAP_DOMAIN: |
$this->attributes['ms_chap_domain'] = radius_cvt_string($datav); |
break; |
case RADIUS_MICROSOFT_MS_MPPE_ENCRYPTION_POLICY: |
$this->attributes['ms_mppe_encryption_policy'] = radius_cvt_int($datav); |
break; |
case RADIUS_MICROSOFT_MS_MPPE_ENCRYPTION_TYPES: |
$this->attributes['ms_mppe_encryption_types'] = radius_cvt_int($datav); |
break; |
case RADIUS_MICROSOFT_MS_CHAP_MPPE_KEYS: |
$demangled = radius_demangle($this->res, $datav); |
$this->attributes['ms_chap_mppe_lm_key'] = substr($demangled, 0, 8); |
$this->attributes['ms_chap_mppe_nt_key'] = substr($demangled, 8, RADIUS_MPPE_KEY_LEN); |
break; |
case RADIUS_MICROSOFT_MS_MPPE_SEND_KEY: |
$this->attributes['ms_chap_mppe_send_key'] = radius_demangle_mppe_key($this->res, $datav); |
break; |
case RADIUS_MICROSOFT_MS_MPPE_RECV_KEY: |
$this->attributes['ms_chap_mppe_recv_key'] = radius_demangle_mppe_key($this->res, $datav); |
break; |
case RADIUS_MICROSOFT_MS_PRIMARY_DNS_SERVER: |
$this->attributes['ms_primary_dns_server'] = radius_cvt_string($datav); |
break; |
} |
} |
break; |
} |
} |
return true; |
} |
/** |
* Frees resources. |
* |
* Calling this method is always a good idea, because all security relevant |
* attributes are filled with Nullbytes to leave nothing in the mem. |
* |
* @access public |
*/ |
function close() |
{ |
if ($this->res != null) { |
radius_close($this->res); |
$this->res = null; |
} |
$this->username = str_repeat("\0", strlen($this->username)); |
$this->password = str_repeat("\0", strlen($this->password)); |
} |
} |
/** |
* class Auth_RADIUS_PAP |
* |
* Class for authenticating using PAP (Plaintext) |
* |
* @package Auth_RADIUS |
*/ |
class Auth_RADIUS_PAP extends Auth_RADIUS |
{ |
/** |
* Constructor |
* |
* @param string $username Username |
* @param string $password Password |
* @return void |
*/ |
function Auth_RADIUS_PAP($username = null, $password = null) |
{ |
$this->Auth_RADIUS(); |
$this->username = $username; |
$this->password = $password; |
} |
/** |
* Creates a RADIUS resource |
* |
* Creates a RADIUS resource for authentication. This should be the first |
* call before you make any other things with the library. |
* |
* @return bool true on success, false on error |
*/ |
function open() |
{ |
$this->res = radius_auth_open(); |
if (!$this->res) { |
return false; |
} |
return true; |
} |
/** |
* Creates an authentication request |
* |
* Creates an authentication request. |
* You MUST call this method before you can put any attribute |
* |
* @return bool true on success, false on error |
*/ |
function createRequest() |
{ |
if (!radius_create_request($this->res, RADIUS_ACCESS_REQUEST)) { |
return false; |
} |
return true; |
} |
/** |
* Put authentication specific attributes |
* |
* @return void |
*/ |
function putAuthAttributes() |
{ |
if (isset($this->username)) { |
$this->putAttribute(RADIUS_USER_NAME, $this->username); |
} |
if (isset($this->password)) { |
$this->putAttribute(RADIUS_USER_PASSWORD, $this->password); |
} |
} |
} |
/** |
* class Auth_RADIUS_CHAP_MD5 |
* |
* Class for authenticating using CHAP-MD5 see RFC1994. |
* Instead og the plaintext password the challenge and |
* the response are needed. |
* |
* @package Auth_RADIUS |
*/ |
class Auth_RADIUS_CHAP_MD5 extends Auth_RADIUS_PAP |
{ |
/** |
* 8 Bytes binary challenge |
* @var string |
*/ |
var $challenge = null; |
/** |
* 16 Bytes MD5 response binary |
* @var string |
*/ |
var $response = null; |
/** |
* Id of the authentication request. Should incremented after every request. |
* @var integer |
*/ |
var $chapid = 1; |
/** |
* Constructor |
* |
* @param string $username Username |
* @param string $challenge 8 Bytes Challenge (binary) |
* @param integer $chapid Requestnumber |
* @return void |
*/ |
function Auth_RADIUS_CHAP_MD5($username = null, $challenge = null, $chapid = 1) |
{ |
$this->Auth_RADIUS_PAP(); |
$this->username = $username; |
$this->challenge = $challenge; |
$this->chapid = $chapid; |
} |
/** |
* Put CHAP-MD5 specific attributes |
* |
* For authenticating using CHAP-MD5 via RADIUS you have to put the challenge |
* and the response. The chapid is inserted in the first byte of the response. |
* |
* @return void |
*/ |
function putAuthAttributes() |
{ |
if (isset($this->username)) { |
$this->putAttribute(RADIUS_USER_NAME, $this->username); |
} |
if (isset($this->response)) { |
$response = pack('C', $this->chapid) . $this->response; |
$this->putAttribute(RADIUS_CHAP_PASSWORD, $response); |
} |
if (isset($this->challenge)) { |
$this->putAttribute(RADIUS_CHAP_CHALLENGE, $this->challenge); |
} |
} |
/** |
* Frees resources. |
* |
* Calling this method is always a good idea, because all security relevant |
* attributes are filled with Nullbytes to leave nothing in the mem. |
* |
* @access public |
*/ |
function close() |
{ |
Auth_RADIUS_PAP::close(); |
$this->challenge = str_repeat("\0", strlen($this->challenge)); |
$this->response = str_repeat("\0", strlen($this->response)); |
} |
} |
/** |
* class Auth_RADIUS_MSCHAPv1 |
* |
* Class for authenticating using MS-CHAPv1 see RFC2433 |
* |
* @package Auth_RADIUS |
*/ |
class Auth_RADIUS_MSCHAPv1 extends Auth_RADIUS_CHAP_MD5 |
{ |
/** |
* LAN-Manager-Response |
* @var string |
*/ |
var $lmResponse = null; |
/** |
* Wether using deprecated LM-Responses or not. |
* 0 = use LM-Response, 1 = use NT-Response |
* @var bool |
*/ |
var $flags = 1; |
/** |
* Put MS-CHAPv1 specific attributes |
* |
* For authenticating using MS-CHAPv1 via RADIUS you have to put the challenge |
* and the response. The response has this structure: |
* struct rad_mschapvalue { |
* u_char ident; |
* u_char flags; |
* u_char lm_response[24]; |
* u_char response[24]; |
* }; |
* |
* @return void |
*/ |
function putAuthAttributes() |
{ |
if (isset($this->username)) { |
$this->putAttribute(RADIUS_USER_NAME, $this->username); |
} |
if (isset($this->response) || isset($this->lmResponse)) { |
$lmResp = isset($this->lmResponse) ? $this->lmResponse : str_repeat ("\0", 24); |
$ntResp = isset($this->response) ? $this->response : str_repeat ("\0", 24); |
$resp = pack('CC', $this->chapid, $this->flags) . $lmResp . $ntResp; |
$this->putVendorAttribute(RADIUS_VENDOR_MICROSOFT, RADIUS_MICROSOFT_MS_CHAP_RESPONSE, $resp); |
} |
if (isset($this->challenge)) { |
$this->putVendorAttribute(RADIUS_VENDOR_MICROSOFT, RADIUS_MICROSOFT_MS_CHAP_CHALLENGE, $this->challenge); |
} |
} |
} |
/** |
* class Auth_RADIUS_MSCHAPv2 |
* |
* Class for authenticating using MS-CHAPv2 see RFC2759 |
* |
* @package Auth_RADIUS |
*/ |
class Auth_RADIUS_MSCHAPv2 extends Auth_RADIUS_MSCHAPv1 |
{ |
/** |
* 16 Bytes binary challenge |
* @var string |
*/ |
var $challenge = null; |
/** |
* 16 Bytes binary Peer Challenge |
* @var string |
*/ |
var $peerChallenge = null; |
/** |
* Put MS-CHAPv2 specific attributes |
* |
* For authenticating using MS-CHAPv1 via RADIUS you have to put the challenge |
* and the response. The response has this structure: |
* struct rad_mschapv2value { |
* u_char ident; |
* u_char flags; |
* u_char pchallenge[16]; |
* u_char reserved[8]; |
* u_char response[24]; |
* }; |
* where pchallenge is the peer challenge. Like for MS-CHAPv1 we set the flags field to 1. |
* @return void |
*/ |
function putAuthAttributes() |
{ |
if (isset($this->username)) { |
$this->putAttribute(RADIUS_USER_NAME, $this->username); |
} |
if (isset($this->response) && isset($this->peerChallenge)) { |
// Response: chapid, flags (1 = use NT Response), Peer challenge, reserved, Response |
$resp = pack('CCa16a8a24',$this->chapid , 1, $this->peerChallenge, str_repeat("\0", 8), $this->response); |
$this->putVendorAttribute(RADIUS_VENDOR_MICROSOFT, RADIUS_MICROSOFT_MS_CHAP2_RESPONSE, $resp); |
} |
if (isset($this->challenge)) { |
$this->putVendorAttribute(RADIUS_VENDOR_MICROSOFT, RADIUS_MICROSOFT_MS_CHAP_CHALLENGE, $this->challenge); |
} |
} |
/** |
* Frees resources. |
* |
* Calling this method is always a good idea, because all security relevant |
* attributes are filled with Nullbytes to leave nothing in the mem. |
* |
* @access public |
*/ |
function close() |
{ |
Auth_RADIUS_MSCHAPv1::close(); |
$this->peerChallenge = str_repeat("\0", strlen($this->peerChallenge)); |
} |
} |
/** |
* class Auth_RADIUS_Acct |
* |
* Class for RADIUS accounting |
* |
* @package Auth_RADIUS |
*/ |
class Auth_RADIUS_Acct extends Auth_RADIUS |
{ |
/** |
* Defines where the Authentication was made, possible values are: |
* RADIUS_AUTH_RADIUS, RADIUS_AUTH_LOCAL, RADIUS_AUTH_REMOTE |
* @var integer |
*/ |
var $authentic = null; |
/** |
* Defines the type of the accounting request, on of: |
* RADIUS_START, RADIUS_STOP, RADIUS_ACCOUNTING_ON, RADIUS_ACCOUNTING_OFF |
* @var integer |
*/ |
var $status_type = null; |
/** |
* The time the user was logged in in seconds |
* @var integer |
*/ |
var $session_time = null; |
/** |
* A uniq identifier for the session of the user, maybe the PHP-Session-Id |
* @var string |
*/ |
var $session_id = null; |
/** |
* Constructor |
* |
* Generates a predefined session_id. We use the Remote-Address, the PID, and the Current user. |
* @return void |
*/ |
function Auth_RADIUS_Acct() |
{ |
$this->Auth_RADIUS(); |
if (isset($_SERVER)) { |
$var = &$_SERVER; |
} else { |
$var = &$GLOBALS['HTTP_SERVER_VARS']; |
} |
$this->session_id = sprintf("%s:%d-%s", isset($var['REMOTE_ADDR']) ? $var['REMOTE_ADDR'] : '127.0.0.1' , getmypid(), get_current_user()); |
} |
/** |
* Creates a RADIUS resource |
* |
* Creates a RADIUS resource for accounting. This should be the first |
* call before you make any other things with the library. |
* |
* @return bool true on success, false on error |
*/ |
function open() |
{ |
$this->res = radius_acct_open(); |
if (!$this->res) { |
return false; |
} |
return true; |
} |
/** |
* Creates an accounting request |
* |
* Creates an accounting request. |
* You MUST call this method before you can put any attribute. |
* |
* @return bool true on success, false on error |
*/ |
function createRequest() |
{ |
if (!radius_create_request($this->res, RADIUS_ACCOUNTING_REQUEST)) { |
return false; |
} |
return true; |
} |
/** |
* Put attributes for accounting. |
* |
* Here we put some accounting values. There many more attributes for accounting, |
* but for web-applications only certain attributes make sense. |
* @return void |
*/ |
function putAuthAttributes() |
{ |
$this->putAttribute(RADIUS_ACCT_SESSION_ID, $this->session_id); |
$this->putAttribute(RADIUS_ACCT_STATUS_TYPE, $this->status_type); |
if (isset($this->session_time) && $this->status_type == RADIUS_STOP) { |
$this->putAttribute(RADIUS_ACCT_SESSION_TIME, $this->session_time); |
} |
if (isset($this->authentic)) { |
$this->putAttribute(RADIUS_ACCT_AUTHENTIC, $this->authentic); |
} |
} |
} |
/** |
* class Auth_RADIUS_Acct_Start |
* |
* Class for RADIUS accounting. Its usualy used, after the user has logged in. |
* |
* @package Auth_RADIUS |
*/ |
class Auth_RADIUS_Acct_Start extends Auth_RADIUS_Acct |
{ |
/** |
* Defines the type of the accounting request. |
* It is set to RADIUS_START by default in this class. |
* @var integer |
*/ |
var $status_type = Auth_RADIUS_Acct_Stop; |
} |
/** |
* class Auth_RADIUS_Acct_Start |
* |
* Class for RADIUS accounting. Its usualy used, after the user has logged out. |
* |
* @package Auth_RADIUS |
*/ |
class Auth_RADIUS_Acct_Stop extends Auth_RADIUS_Acct |
{ |
/** |
* Defines the type of the accounting request. |
* It is set to RADIUS_STOP by default in this class. |
* @var integer |
*/ |
var $status_type = RADIUS_STOP; |
} |
?> |
/branches/livraison_narmer/api/pear/Auth/Anonymous.php |
---|
New file |
0,0 → 1,138 |
<?php |
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */ |
/** |
* Anonymous authentication support |
* |
* PHP versions 4 and 5 |
* |
* LICENSE: This source file is subject to version 3.01 of the PHP license |
* that is available through the world-wide-web at the following URI: |
* http://www.php.net/license/3_01.txt. If you did not receive a copy of |
* the PHP License and are unable to obtain it through the web, please |
* send a note to license@php.net so we can mail you a copy immediately. |
* |
* @category Authentication |
* @package Auth |
* @author Yavor Shahpasov <yavo@netsmart.com.cy> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version CVS: $Id: Anonymous.php,v 1.1 2006-12-14 15:04:28 jp_milcent Exp $ |
* @link http://pear.php.net/package/Auth |
* @since File available since Release 1.3.0 |
*/ |
/** |
* Include Auth package |
*/ |
require_once 'Auth.php'; |
/** |
* Anonymous Authentication |
* |
* This class provides anonymous authentication if username and password |
* were not supplied |
* |
* @category Authentication |
* @package Auth |
* @author Yavor Shahpasov <yavo@netsmart.com.cy> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version Release: 1.4.3 File: $Revision: 1.1 $ |
* @link http://pear.php.net/package/Auth |
* @since Class available since Release 1.3.0 |
*/ |
class Auth_Anonymous extends Auth |
{ |
// {{{ properties |
/** |
* Whether to allow anonymous authentication |
* |
* @var boolean |
*/ |
var $allow_anonymous = true; |
/** |
* Username to use for anonymous user |
* |
* @var string |
*/ |
var $anonymous_username = 'anonymous'; |
// }}} |
// {{{ Auth_Anonymous() [constructor] |
/** |
* Pass all parameters to Parent Auth class |
* |
* Set up the storage driver. |
* |
* @param string Type of the storage driver |
* @param mixed Additional options for the storage driver |
* (example: if you are using DB as the storage |
* driver, you have to pass the dsn string here) |
* |
* @param string Name of the function that creates the login form |
* @param boolean Should the login form be displayed if neccessary? |
* @return void |
* @see Auth::Auth() |
*/ |
function Auth_Anonymous($storageDriver, $options = '', $loginFunction = '', $showLogin = true) { |
parent::Auth($storageDriver, $options, $loginFunction, $showLogin); |
} |
// }}} |
// {{{ login() |
/** |
* Login function |
* |
* If no username & password is passed then login as the username |
* provided in $this->anonymous_username else call standard login() |
* function. |
* |
* @return void |
* @access private |
* @see Auth::login() |
*/ |
function login() { |
if ( $this->allow_anonymous |
&& empty($this->username) |
&& empty($this->password) ) { |
$this->setAuth($this->anonymous_username); |
if (is_callable($this->loginCallback)) { |
call_user_func_array($this->loginCallback, array($this->username, $this) ); |
} |
} else { |
// Call normal login system |
parent::login(); |
} |
} |
// }}} |
// {{{ forceLogin() |
/** |
* Force the user to login |
* |
* Calling this function forces the user to provide a real username and |
* password before continuing. |
* |
* @return void |
*/ |
function forceLogin() { |
$this->allow_anonymous = false; |
if( !empty($this->session['username']) && $this->session['username'] == $this->anonymous_username ) { |
$this->logout(); |
} |
} |
// }}} |
} |
?> |
/branches/livraison_narmer/api/pear/Auth/Frontend/Html.php |
---|
New file |
0,0 → 1,142 |
<?php |
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */ |
/** |
* Standard Html Login form |
* |
* PHP versions 4 and 5 |
* |
* LICENSE: This source file is subject to version 3.01 of the PHP license |
* that is available through the world-wide-web at the following URI: |
* http://www.php.net/license/3_01.txt. If you did not receive a copy of |
* the PHP License and are unable to obtain it through the web, please |
* send a note to license@php.net so we can mail you a copy immediately. |
* |
* @category Authentication |
* @package Auth |
* @author Martin Jansen <mj@php.net> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version CVS: $Id: Html.php,v 1.1 2006-12-14 15:04:29 jp_milcent Exp $ |
* @link http://pear.php.net/package/Auth |
* @since File available since Release 1.3.0 |
*/ |
/** |
* Standard Html Login form |
* |
* @category Authentication |
* @package Auth |
* @author Yavor Shahpasov <yavo@netsmart.com.cy> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version Release: 1.4.3 File: $Revision: 1.1 $ |
* @link http://pear.php.net/package/Auth |
* @since Class available since Release 1.3.0 |
*/ |
class Auth_Frontend_Html { |
// {{{ render() |
/** |
* Displays the login form |
* |
* @param object The calling auth instance |
* @param string The previously used username |
* @return void |
*/ |
function render(&$caller, $username = '') { |
$loginOnClick = 'return true;'; |
// Try To Use Challene response |
// TODO javascript might need some improvement for work on other browsers |
if($caller->advancedsecurity && $caller->storage->supportsChallengeResponse() ) { |
// Init the secret cookie |
$caller->session['loginchallenege'] = md5(microtime()); |
print "\n"; |
print '<script language="JavaScript">'."\n"; |
include 'Auth/Frontend/md5.js'; |
print "\n"; |
print ' function securePassword() { '."\n"; |
print ' var pass = document.getElementById(\''.$caller->getPostPasswordField().'\');'."\n"; |
print ' var secret = document.getElementById(\'authsecret\')'."\n"; |
//print ' alert(pass);alert(secret); '."\n"; |
// If using md5 for password storage md5 the password before |
// we hash it with the secret |
// print ' alert(pass.value);'; |
if ($caller->storage->getCryptType() == 'md5' ) { |
print ' pass.value = hex_md5(pass.value); '."\n"; |
#print ' alert(pass.value);'; |
} |
print ' pass.value = hex_md5(pass.value+\''.$caller->session['loginchallenege'].'\'); '."\n"; |
// print ' alert(pass.value);'; |
print ' secret.value = 1;'."\n"; |
print ' var doLogin = document.getElementById(\'doLogin\')'."\n"; |
print ' doLogin.disabled = true;'."\n"; |
print ' return true;'; |
print ' } '."\n"; |
print '</script>'."\n";; |
print "\n"; |
$loginOnClick = ' return securePassword(); '; |
} |
print '<center>'."\n"; |
$status = ''; |
if (!empty($caller->status) && $caller->status == AUTH_EXPIRED) { |
$status = '<i>Your session has expired. Please login again!</i>'."\n"; |
} else if (!empty($caller->status) && $caller->status == AUTH_IDLED) { |
$status = '<i>You have been idle for too long. Please login again!</i>'."\n"; |
} else if (!empty ($caller->status) && $caller->status == AUTH_WRONG_LOGIN) { |
$status = '<i>Wrong login data!</i>'."\n"; |
} else if (!empty ($caller->status) && $caller->status == AUTH_SECURITY_BREACH) { |
$status = '<i>Security problem detected. </i>'."\n"; |
} |
print '<form method="post" action="'.$caller->server['PHP_SELF'].'" ' |
.'onSubmit="'.$loginOnClick.'">'."\n"; |
print '<table border="0" cellpadding="2" cellspacing="0" ' |
.'summary="login form" align="center" >'."\n"; |
print '<tr>'."\n"; |
print ' <td colspan="2" bgcolor="#eeeeee"><strong>Login </strong>' |
.$status.'</td>'."\n"; |
print '</tr>'."\n"; |
print '<tr>'."\n"; |
print ' <td>Username:</td>'."\n"; |
print ' <td><input type="text" id="'.$caller->getPostUsernameField() |
.'" name="'.$caller->getPostUsernameField().'" value="' . $username |
.'" /></td>'."\n"; |
print '</tr>'."\n"; |
print '<tr>'."\n"; |
print ' <td>Password:</td>'."\n"; |
print ' <td><input type="password" id="'.$caller->getPostPasswordField() |
.'" name="'.$caller->getPostPasswordField().'" /></td>'."\n"; |
print '</tr>'."\n"; |
print '<tr>'."\n"; |
//onClick=" '.$loginOnClick.' " |
print ' <td colspan="2" bgcolor="#eeeeee"><input value="Login" ' |
.'id="doLogin" name="doLogin" type="submit" /></td>'."\n"; |
print '</tr>'."\n"; |
print '</table>'."\n"; |
// Might be a good idea to make the variable name variable |
print '<input type="hidden" id="authsecret" name="authsecret" value="" />'; |
print '</form>'."\n"; |
print '</center>'."\n"; |
} |
// }}} |
} |
?> |
/branches/livraison_narmer/api/pear/Auth/Frontend/md5.js |
---|
New file |
0,0 → 1,256 |
/* |
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message |
* Digest Algorithm, as defined in RFC 1321. |
* Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. |
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet |
* Distributed under the BSD License |
* See http://pajhome.org.uk/crypt/md5 for more info. |
*/ |
/* |
* Configurable variables. You may need to tweak these to be compatible with |
* the server-side, but the defaults work in most cases. |
*/ |
var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */ |
var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */ |
var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */ |
/* |
* These are the functions you'll usually want to call |
* They take string arguments and return either hex or base-64 encoded strings |
*/ |
function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));} |
function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));} |
function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));} |
function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); } |
function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); } |
function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); } |
/* |
* Perform a simple self-test to see if the VM is working |
*/ |
function md5_vm_test() |
{ |
return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72"; |
} |
/* |
* Calculate the MD5 of an array of little-endian words, and a bit length |
*/ |
function core_md5(x, len) |
{ |
/* append padding */ |
x[len >> 5] |= 0x80 << ((len) % 32); |
x[(((len + 64) >>> 9) << 4) + 14] = len; |
var a = 1732584193; |
var b = -271733879; |
var c = -1732584194; |
var d = 271733878; |
for(var i = 0; i < x.length; i += 16) |
{ |
var olda = a; |
var oldb = b; |
var oldc = c; |
var oldd = d; |
a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936); |
d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586); |
c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819); |
b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330); |
a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897); |
d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426); |
c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341); |
b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983); |
a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416); |
d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417); |
c = md5_ff(c, d, a, b, x[i+10], 17, -42063); |
b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162); |
a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682); |
d = md5_ff(d, a, b, c, x[i+13], 12, -40341101); |
c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290); |
b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329); |
a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510); |
d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632); |
c = md5_gg(c, d, a, b, x[i+11], 14, 643717713); |
b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302); |
a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691); |
d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083); |
c = md5_gg(c, d, a, b, x[i+15], 14, -660478335); |
b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848); |
a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438); |
d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690); |
c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961); |
b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501); |
a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467); |
d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784); |
c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473); |
b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734); |
a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558); |
d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463); |
c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562); |
b = md5_hh(b, c, d, a, x[i+14], 23, -35309556); |
a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060); |
d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353); |
c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632); |
b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640); |
a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174); |
d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222); |
c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979); |
b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189); |
a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487); |
d = md5_hh(d, a, b, c, x[i+12], 11, -421815835); |
c = md5_hh(c, d, a, b, x[i+15], 16, 530742520); |
b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651); |
a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844); |
d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415); |
c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905); |
b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055); |
a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571); |
d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606); |
c = md5_ii(c, d, a, b, x[i+10], 15, -1051523); |
b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799); |
a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359); |
d = md5_ii(d, a, b, c, x[i+15], 10, -30611744); |
c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380); |
b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649); |
a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070); |
d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379); |
c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259); |
b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551); |
a = safe_add(a, olda); |
b = safe_add(b, oldb); |
c = safe_add(c, oldc); |
d = safe_add(d, oldd); |
} |
return Array(a, b, c, d); |
} |
/* |
* These functions implement the four basic operations the algorithm uses. |
*/ |
function md5_cmn(q, a, b, x, s, t) |
{ |
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b); |
} |
function md5_ff(a, b, c, d, x, s, t) |
{ |
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); |
} |
function md5_gg(a, b, c, d, x, s, t) |
{ |
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); |
} |
function md5_hh(a, b, c, d, x, s, t) |
{ |
return md5_cmn(b ^ c ^ d, a, b, x, s, t); |
} |
function md5_ii(a, b, c, d, x, s, t) |
{ |
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); |
} |
/* |
* Calculate the HMAC-MD5, of a key and some data |
*/ |
function core_hmac_md5(key, data) |
{ |
var bkey = str2binl(key); |
if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz); |
var ipad = Array(16), opad = Array(16); |
for(var i = 0; i < 16; i++) |
{ |
ipad[i] = bkey[i] ^ 0x36363636; |
opad[i] = bkey[i] ^ 0x5C5C5C5C; |
} |
var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz); |
return core_md5(opad.concat(hash), 512 + 128); |
} |
/* |
* Add integers, wrapping at 2^32. This uses 16-bit operations internally |
* to work around bugs in some JS interpreters. |
*/ |
function safe_add(x, y) |
{ |
var lsw = (x & 0xFFFF) + (y & 0xFFFF); |
var msw = (x >> 16) + (y >> 16) + (lsw >> 16); |
return (msw << 16) | (lsw & 0xFFFF); |
} |
/* |
* Bitwise rotate a 32-bit number to the left. |
*/ |
function bit_rol(num, cnt) |
{ |
return (num << cnt) | (num >>> (32 - cnt)); |
} |
/* |
* Convert a string to an array of little-endian words |
* If chrsz is ASCII, characters >255 have their hi-byte silently ignored. |
*/ |
function str2binl(str) |
{ |
var bin = Array(); |
var mask = (1 << chrsz) - 1; |
for(var i = 0; i < str.length * chrsz; i += chrsz) |
bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32); |
return bin; |
} |
/* |
* Convert an array of little-endian words to a string |
*/ |
function binl2str(bin) |
{ |
var str = ""; |
var mask = (1 << chrsz) - 1; |
for(var i = 0; i < bin.length * 32; i += chrsz) |
str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask); |
return str; |
} |
/* |
* Convert an array of little-endian words to a hex string. |
*/ |
function binl2hex(binarray) |
{ |
var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef"; |
var str = ""; |
for(var i = 0; i < binarray.length * 4; i++) |
{ |
str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) + |
hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF); |
} |
return str; |
} |
/* |
* Convert an array of little-endian words to a base-64 string |
*/ |
function binl2b64(binarray) |
{ |
var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; |
var str = ""; |
for(var i = 0; i < binarray.length * 4; i += 3) |
{ |
var triplet = (((binarray[i >> 2] >> 8 * ( i %4)) & 0xFF) << 16) |
| (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 ) |
| ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF); |
for(var j = 0; j < 4; j++) |
{ |
if(i * 8 + j * 6 > binarray.length * 32) str += b64pad; |
else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F); |
} |
} |
return str; |
} |
/branches/livraison_narmer/api/pear/Auth/Container/Array.php |
---|
New file |
0,0 → 1,159 |
<?php |
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */ |
/** |
* Storage driver for use against a PHP Array |
* |
* PHP versions 4 and 5 |
* |
* LICENSE: This source file is subject to version 3.01 of the PHP license |
* that is available through the world-wide-web at the following URI: |
* http://www.php.net/license/3_01.txt. If you did not receive a copy of |
* the PHP License and are unable to obtain it through the web, please |
* send a note to license@php.net so we can mail you a copy immediately. |
* |
* @category Authentication |
* @package Auth |
* @author georg_1 at have2 dot com |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version CVS: $Id: Array.php,v 1.1 2006-12-14 15:04:28 jp_milcent Exp $ |
* @since File available since Release 1.4.0 |
*/ |
/** |
* Include Auth_Container base class |
*/ |
require_once "Auth/Container.php"; |
/** |
* Include PEAR package for error handling |
*/ |
require_once "PEAR.php"; |
/** |
* Storage driver for fetching authentication data from a PHP Array |
* |
* This container takes two options when configuring: |
* |
* cryptType: The crypt used to store the password. Currently recognised |
* are: none, md5 and crypt. default: none |
* users: A named array of usernames and passwords. |
* Ex: |
* array( |
* 'guest' => '084e0343a0486ff05530df6c705c8bb4', // password guest |
* 'georg' => 'fc77dba827fcc88e0243404572c51325' // password georg |
* ) |
* |
* Usage Example: |
* <?php |
* $AuthOptions = array( |
* 'users' => array( |
* 'guest' => '084e0343a0486ff05530df6c705c8bb4', // password guest |
* 'georg' => 'fc77dba827fcc88e0243404572c51325' // password georg |
* ), |
* 'cryptType'=>'md5', |
* ); |
* |
* $auth = new Auth("Array", $AuthOptions); |
* ?> |
* |
* @category Authentication |
* @package Auth |
* @author georg_1 at have2 dot com |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version Release: 1.4.3 File: $Revision: 1.1 $ |
* @since File available since Release 1.4.0 |
*/ |
class Auth_Container_Array extends Auth_Container { |
// {{{ properties |
/** |
* The users and their password to authenticate against |
* |
* @var array $users |
*/ |
var $users; |
/** |
* The cryptType used on the passwords |
* |
* @var string $cryptType |
*/ |
var $cryptType = 'none'; |
// }}} |
// {{{ Auth_Container_Array() |
/** |
* Constructor for Array Container |
* |
* @param array $data Options for the container |
* @return void |
*/ |
function Auth_Container_Array($data) |
{ |
if (!is_array($data)) { |
PEAR::raiseError('The options for Auth_Container_Array must be an array'); |
} |
if (isset($data['users']) && is_array($data['users'])) { |
$this->users = $data['users']; |
} else { |
$this->users = array(); |
PEAR::raiseError('Auth_Container_Array: no user data found inoptions array'); |
} |
if (isset($data['cryptType'])) { |
$this->cryptType = $data['cryptType']; |
} |
} |
// }}} |
// {{{ fetchData() |
/** |
* Get user information from array |
* |
* This function uses the given username to fetch the corresponding |
* login data from the array. If an account that matches the passed |
* username and password is found, the function returns true. |
* Otherwise it returns false. |
* |
* @param string Username |
* @param string Password |
* @return boolean|PEAR_Error Error object or boolean |
*/ |
function fetchData($user, $pass) |
{ |
if ( isset($this->users[$user]) |
&& $this->verifyPassword($pass, $this->users[$user], $this->cryptType)) { |
return true; |
} |
return false; |
} |
// }}} |
// {{{ listUsers() |
/** |
* Returns a list of users available within the container |
* |
* @return array |
*/ |
function listUsers() |
{ |
$ret = array(); |
foreach ($this->users as $username => $password) { |
$ret[]['username'] = $username; |
} |
return $ret; |
} |
// }}} |
} |
?> |
/branches/livraison_narmer/api/pear/Auth/Container/File.php |
---|
New file |
0,0 → 1,305 |
<?php |
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */ |
/** |
* Storage driver for use against a generic password file |
* |
* PHP versions 4 and 5 |
* |
* LICENSE: This source file is subject to version 3.01 of the PHP license |
* that is available through the world-wide-web at the following URI: |
* http://www.php.net/license/3_01.txt. If you did not receive a copy of |
* the PHP License and are unable to obtain it through the web, please |
* send a note to license@php.net so we can mail you a copy immediately. |
* |
* @category Authentication |
* @package Auth |
* @author Stefan Ekman <stekman@sedata.org> |
* @author Martin Jansen <mj@php.net> |
* @author Mika Tuupola <tuupola@appelsiini.net> |
* @author Michael Wallner <mike@php.net> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version CVS: $Id: File.php,v 1.2 2006-12-14 15:04:28 jp_milcent Exp $ |
* @link http://pear.php.net/package/Auth |
*/ |
/** |
* Include PEAR File_Passwd package |
*/ |
require_once "File/Passwd.php"; |
/** |
* Include Auth_Container base class |
*/ |
require_once "Auth/Container.php"; |
/** |
* Include PEAR package for error handling |
*/ |
require_once "PEAR.php"; |
/** |
* Storage driver for fetching login data from an encrypted password file. |
* |
* This storage container can handle CVS pserver style passwd files. |
* |
* @category Authentication |
* @package Auth |
* @author Stefan Ekman <stekman@sedata.org> |
* @author Martin Jansen <mj@php.net> |
* @author Mika Tuupola <tuupola@appelsiini.net> |
* @author Michael Wallner <mike@php.net> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version Release: 1.4.3 File: $Revision: 1.2 $ |
* @link http://pear.php.net/package/Auth |
*/ |
class Auth_Container_File extends Auth_Container |
{ |
// {{{ properties |
/** |
* Path to passwd file |
* |
* @var string |
*/ |
var $pwfile = ''; |
/** |
* Options for container |
* |
* @var array |
*/ |
var $options = array(); |
// }}} |
// {{{ Auth_Container_File() [constructor] |
/** |
* Constructor of the container class |
* |
* @param string $filename path to passwd file |
* @return object Auth_Container_File new Auth_Container_File object |
*/ |
function Auth_Container_File($filename) { |
$this->_setDefaults(); |
// Only file is a valid option here |
if(is_array($filename)) { |
$this->pwfile = $filename['file']; |
$this->_parseOptions($filename); |
} else { |
$this->pwfile = $filename; |
} |
} |
// }}} |
// {{{ fetchData() |
/** |
* Authenticate an user |
* |
* @param string username |
* @param string password |
* @return mixed boolean|PEAR_Error |
*/ |
function fetchData($user, $pass) |
{ |
return File_Passwd::staticAuth($this->options['type'], $this->pwfile, $user, $pass); |
} |
// }}} |
// {{{ listUsers() |
/** |
* List all available users |
* |
* @return array |
*/ |
function listUsers() |
{ |
$pw_obj = &$this->_load(); |
if (PEAR::isError($pw_obj)) { |
return array(); |
} |
$users = $pw_obj->listUser(); |
if (!is_array($users)) { |
return array(); |
} |
foreach ($users as $key => $value) { |
$retVal[] = array("username" => $key, |
"password" => $value['passwd'], |
"cvsuser" => $value['system']); |
} |
return $retVal; |
} |
// }}} |
// {{{ addUser() |
/** |
* Add a new user to the storage container |
* |
* @param string username |
* @param string password |
* @param mixed Additional parameters to File_Password_*::addUser() |
* |
* @return boolean |
*/ |
function addUser($user, $pass, $additional='') |
{ |
$params = array($user, $pass); |
if (is_array($additional)) { |
foreach ($additional as $item) { |
$params[] = $item; |
} |
} else { |
$params[] = $additional; |
} |
$pw_obj = &$this->_load(); |
if (PEAR::isError($pw_obj)) { |
return false; |
} |
$res = call_user_func_array(array(&$pw_obj, 'addUser'), $params); |
if (PEAR::isError($res)) { |
return false; |
} |
$res = $pw_obj->save(); |
if (PEAR::isError($res)) { |
return false; |
} |
return true; |
} |
// }}} |
// {{{ removeUser() |
/** |
* Remove user from the storage container |
* |
* @param string Username |
* @return boolean |
*/ |
function removeUser($user) |
{ |
$pw_obj = &$this->_load(); |
if (PEAR::isError($pw_obj)) { |
return false; |
} |
$res = $pw_obj->delUser($user); |
if (PEAR::isError($res)) { |
return false; |
} |
$res = $pw_obj->save(); |
if (PEAR::isError($res)) { |
return false; |
} |
return true; |
} |
// }}} |
// {{{ changePassword() |
/** |
* Change password for user in the storage container |
* |
* @param string Username |
* @param string The new password |
*/ |
function changePassword($username, $password) |
{ |
$pw_obj = &$this->_load(); |
if (PEAR::isError($pw_obj)) { |
return false; |
} |
$res = $pw_obj->changePasswd($username, $password); |
if (PEAR::isError($res)) { |
return false; |
} |
$res = $pw_obj->save(); |
if (PEAR::isError($res)) { |
return false; |
} |
return true; |
} |
// }}} |
// {{{ _load() |
/** |
* Load and initialize the File_Passwd object |
* |
* @return object File_Passwd_Cvs|PEAR_Error |
*/ |
function &_load() |
{ |
static $pw_obj; |
if (!isset($pw_obj)) { |
$pw_obj = File_Passwd::factory($this->options['type']); |
if (PEAR::isError($pw_obj)) { |
return $pw_obj; |
} |
$pw_obj->setFile($this->pwfile); |
$res = $pw_obj->load(); |
if (PEAR::isError($res)) { |
return $res; |
} |
} |
return $pw_obj; |
} |
// }}} |
// {{{ _setDefaults() |
/** |
* Set some default options |
* |
* @access private |
* @return void |
*/ |
function _setDefaults() |
{ |
$this->options['type'] = 'Cvs'; |
} |
// }}} |
// {{{ _parseOptions() |
/** |
* Parse options passed to the container class |
* |
* @access private |
* @param array |
*/ |
function _parseOptions($array) |
{ |
foreach ($array as $key => $value) { |
if (isset($this->options[$key])) { |
$this->options[$key] = $value; |
} |
} |
} |
// }}} |
} |
?> |
/branches/livraison_narmer/api/pear/Auth/Container/LDAP.php |
---|
New file |
0,0 → 1,773 |
<?php |
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */ |
/** |
* Storage driver for use against an LDAP server |
* |
* PHP versions 4 and 5 |
* |
* LICENSE: This source file is subject to version 3.01 of the PHP license |
* that is available through the world-wide-web at the following URI: |
* http://www.php.net/license/3_01.txt. If you did not receive a copy of |
* the PHP License and are unable to obtain it through the web, please |
* send a note to license@php.net so we can mail you a copy immediately. |
* |
* @category Authentication |
* @package Auth |
* @author Jan Wagner <wagner@netsols.de> |
* @author Adam Ashley <aashley@php.net> |
* @author Hugues Peeters <hugues.peeters@claroline.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version CVS: $Id: LDAP.php,v 1.2 2006-12-14 15:04:28 jp_milcent Exp $ |
* @link http://pear.php.net/package/Auth |
*/ |
/** |
* Include Auth_Container base class |
*/ |
require_once "Auth/Container.php"; |
/** |
* Include PEAR package for error handling |
*/ |
require_once "PEAR.php"; |
/** |
* Storage driver for fetching login data from LDAP |
* |
* This class is heavily based on the DB and File containers. By default it |
* connects to localhost:389 and searches for uid=$username with the scope |
* "sub". If no search base is specified, it will try to determine it via |
* the namingContexts attribute. It takes its parameters in a hash, connects |
* to the ldap server, binds anonymously, searches for the user, and tries |
* to bind as the user with the supplied password. When a group was set, it |
* will look for group membership of the authenticated user. If all goes |
* well the authentication was successful. |
* |
* Parameters: |
* |
* host: localhost (default), ldap.netsols.de or 127.0.0.1 |
* port: 389 (default) or 636 or whereever your server runs |
* url: ldap://localhost:389/ |
* useful for ldaps://, works only with openldap2 ? |
* it will be preferred over host and port |
* version: LDAP version to use, ususally 2 (default) or 3, |
* must be an integer! |
* referrals: If set, determines whether the LDAP library automatically |
* follows referrals returned by LDAP servers or not. Possible |
* values are true (default) or false. |
* binddn: If set, searching for user will be done after binding |
* as this user, if not set the bind will be anonymous. |
* This is reported to make the container work with MS |
* Active Directory, but should work with any server that |
* is configured this way. |
* This has to be a complete dn for now (basedn and |
* userdn will not be appended). |
* bindpw: The password to use for binding with binddn |
* basedn: the base dn of your server |
* userdn: gets prepended to basedn when searching for user |
* userscope: Scope for user searching: one, sub (default), or base |
* userattr: the user attribute to search for (default: uid) |
* userfilter: filter that will be added to the search filter |
* this way: (&(userattr=username)(userfilter)) |
* default: (objectClass=posixAccount) |
* attributes: array of additional attributes to fetch from entry. |
* these will added to auth data and can be retrieved via |
* Auth::getAuthData(). An empty array will fetch all attributes, |
* array('') will fetch no attributes at all (default) |
* If you add 'dn' as a value to this array, the users DN that was |
* used for binding will be added to auth data as well. |
* attrformat: The returned format of the additional data defined in the |
* 'attributes' option. Two formats are available. |
* LDAP returns data formatted in a |
* multidimensional array where each array starts with a |
* 'count' element providing the number of attributes in the |
* entry, or the number of values for attributes. When set |
* to this format, the only way to retrieve data from the |
* Auth object is by calling getAuthData('attributes'). |
* AUTH returns data formatted in a |
* structure more compliant with other Auth Containers, |
* where each attribute element can be directly called by |
* getAuthData() method from Auth. |
* For compatibily with previous LDAP container versions, |
* the default format is LDAP. |
* groupdn: gets prepended to basedn when searching for group |
* groupattr: the group attribute to search for (default: cn) |
* groupfilter: filter that will be added to the search filter when |
* searching for a group: |
* (&(groupattr=group)(memberattr=username)(groupfilter)) |
* default: (objectClass=groupOfUniqueNames) |
* memberattr : the attribute of the group object where the user dn |
* may be found (default: uniqueMember) |
* memberisdn: whether the memberattr is the dn of the user (default) |
* or the value of userattr (usually uid) |
* group: the name of group to search for |
* groupscope: Scope for group searching: one, sub (default), or base |
* start_tls: enable/disable the use of START_TLS encrypted connection |
* (default: false) |
* debug: Enable/Disable debugging output (default: false) |
* try_all: Whether to try all user accounts returned from the search |
* or just the first one. (default: false) |
* |
* To use this storage container, you have to use the following syntax: |
* |
* <?php |
* ... |
* |
* $a1 = new Auth("LDAP", array( |
* 'host' => 'localhost', |
* 'port' => '389', |
* 'version' => 3, |
* 'basedn' => 'o=netsols,c=de', |
* 'userattr' => 'uid' |
* 'binddn' => 'cn=admin,o=netsols,c=de', |
* 'bindpw' => 'password')); |
* |
* $a2 = new Auth('LDAP', array( |
* 'url' => 'ldaps://ldap.netsols.de', |
* 'basedn' => 'o=netsols,c=de', |
* 'userscope' => 'one', |
* 'userdn' => 'ou=People', |
* 'groupdn' => 'ou=Groups', |
* 'groupfilter' => '(objectClass=posixGroup)', |
* 'memberattr' => 'memberUid', |
* 'memberisdn' => false, |
* 'group' => 'admin' |
* )); |
* |
* $a3 = new Auth('LDAP', array( |
* 'host' => 'ldap.netsols.de', |
* 'port' => 389, |
* 'version' => 3, |
* 'referrals' => false, |
* 'basedn' => 'dc=netsols,dc=de', |
* 'binddn' => 'cn=Jan Wagner,cn=Users,dc=netsols,dc=de', |
* 'bindpw' => 'password', |
* 'userattr' => 'samAccountName', |
* 'userfilter' => '(objectClass=user)', |
* 'attributes' => array(''), |
* 'group' => 'testing', |
* 'groupattr' => 'samAccountName', |
* 'groupfilter' => '(objectClass=group)', |
* 'memberattr' => 'member', |
* 'memberisdn' => true, |
* 'groupdn' => 'cn=Users', |
* 'groupscope' => 'one', |
* 'debug' => true); |
* |
* The parameter values have to correspond |
* to the ones for your LDAP server of course. |
* |
* When talking to a Microsoft ActiveDirectory server you have to |
* use 'samaccountname' as the 'userattr' and follow special rules |
* to translate the ActiveDirectory directory names into 'basedn'. |
* The 'basedn' for the default 'Users' folder on an ActiveDirectory |
* server for the ActiveDirectory Domain (which is not related to |
* its DNS name) "win2000.example.org" would be: |
* "CN=Users, DC=win2000, DC=example, DC=org' |
* where every component of the domain name becomes a DC attribute |
* of its own. If you want to use a custom users folder you have to |
* replace "CN=Users" with a sequence of "OU" attributes that specify |
* the path to your custom folder in reverse order. |
* So the ActiveDirectory folder |
* "win2000.example.org\Custom\Accounts" |
* would become |
* "OU=Accounts, OU=Custom, DC=win2000, DC=example, DC=org' |
* |
* It seems that binding anonymously to an Active Directory |
* is not allowed, so you have to set binddn and bindpw for |
* user searching. |
* |
* LDAP Referrals need to be set to false for AD to work sometimes. |
* |
* Example a3 shows a full blown and tested example for connection to |
* Windows 2000 Active Directory with group mebership checking |
* |
* Note also that if you want an encrypted connection to an MS LDAP |
* server, then, on your webserver, you must specify |
* TLS_REQCERT never |
* in /etc/ldap/ldap.conf or in the webserver user's ~/.ldaprc (which |
* may or may not be read depending on your configuration). |
* |
* |
* @category Authentication |
* @package Auth |
* @author Jan Wagner <wagner@netsols.de> |
* @author Adam Ashley <aashley@php.net> |
* @author Hugues Peeters <hugues.peeters@claroline.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version Release: 1.4.3 File: $Revision: 1.2 $ |
* @link http://pear.php.net/package/Auth |
*/ |
class Auth_Container_LDAP extends Auth_Container |
{ |
// {{{ properties |
/** |
* Options for the class |
* @var array |
*/ |
var $options = array(); |
/** |
* Connection ID of LDAP Link |
* @var string |
*/ |
var $conn_id = false; |
// }}} |
// {{{ Auth_Container_LDAP() [constructor] |
/** |
* Constructor of the container class |
* |
* @param $params, associative hash with host,port,basedn and userattr key |
* @return object Returns an error object if something went wrong |
*/ |
function Auth_Container_LDAP($params) |
{ |
if (false === extension_loaded('ldap')) { |
return PEAR::raiseError('Auth_Container_LDAP: LDAP Extension not loaded', |
41, PEAR_ERROR_DIE); |
} |
$this->_setDefaults(); |
if (is_array($params)) { |
$this->_parseOptions($params); |
} |
} |
// }}} |
// {{{ _prepare() |
/** |
* Prepare LDAP connection |
* |
* This function checks if we have already opened a connection to |
* the LDAP server. If that's not the case, a new connection is opened. |
* |
* @access private |
* @return mixed True or a PEAR error object. |
*/ |
function _prepare() |
{ |
if (!$this->_isValidLink()) { |
$res = $this->_connect(); |
if (PEAR::isError($res)) { |
return $res; |
} |
} |
return true; |
} |
// }}} |
// {{{ _connect() |
/** |
* Connect to the LDAP server using the global options |
* |
* @access private |
* @return object Returns a PEAR error object if an error occurs. |
*/ |
function _connect() |
{ |
// connect |
if (isset($this->options['url']) && $this->options['url'] != '') { |
$this->_debug('Connecting with URL', __LINE__); |
$conn_params = array($this->options['url']); |
} else { |
$this->_debug('Connecting with host:port', __LINE__); |
$conn_params = array($this->options['host'], $this->options['port']); |
} |
if (($this->conn_id = @call_user_func_array('ldap_connect', $conn_params)) === false) { |
return PEAR::raiseError('Auth_Container_LDAP: Could not connect to server.', 41); |
} |
$this->_debug('Successfully connected to server', __LINE__); |
// switch LDAP version |
if (is_numeric($this->options['version']) && $this->options['version'] > 2) { |
$this->_debug("Switching to LDAP version {$this->options['version']}", __LINE__); |
@ldap_set_option($this->conn_id, LDAP_OPT_PROTOCOL_VERSION, $this->options['version']); |
// start TLS if available |
if (isset($this->options['start_tls']) && $this->options['start_tls']) { |
$this->_debug("Starting TLS session", __LINE__); |
if (@ldap_start_tls($this->conn_id) === false) { |
return PEAR::raiseError('Auth_Container_LDAP: Could not start tls.', 41); |
} |
} |
} |
// switch LDAP referrals |
if (is_bool($this->options['referrals'])) { |
$this->_debug("Switching LDAP referrals to " . (($this->options['referrals']) ? 'true' : 'false'), __LINE__); |
@ldap_set_option($this->conn_id, LDAP_OPT_REFERRALS, $this->options['referrals']); |
} |
// bind with credentials or anonymously |
if (strlen($this->options['binddn']) && strlen($this->options['bindpw'])) { |
$this->_debug('Binding with credentials', __LINE__); |
$bind_params = array($this->conn_id, $this->options['binddn'], $this->options['bindpw']); |
} else { |
$this->_debug('Binding anonymously', __LINE__); |
$bind_params = array($this->conn_id); |
} |
// bind for searching |
if ((@call_user_func_array('ldap_bind', $bind_params)) === false) { |
$this->_debug(); |
$this->_disconnect(); |
return PEAR::raiseError("Auth_Container_LDAP: Could not bind to LDAP server.", 41); |
} |
$this->_debug('Binding was successful', __LINE__); |
return true; |
} |
// }}} |
// {{{ _disconnect() |
/** |
* Disconnects (unbinds) from ldap server |
* |
* @access private |
*/ |
function _disconnect() |
{ |
if ($this->_isValidLink()) { |
$this->_debug('disconnecting from server'); |
@ldap_unbind($this->conn_id); |
} |
} |
// }}} |
// {{{ _getBaseDN() |
/** |
* Tries to find Basedn via namingContext Attribute |
* |
* @access private |
*/ |
function _getBaseDN() |
{ |
$err = $this->_prepare(); |
if ($err !== true) { |
return PEAR::raiseError($err->getMessage(), $err->getCode()); |
} |
if ($this->options['basedn'] == "" && $this->_isValidLink()) { |
$this->_debug("basedn not set, searching via namingContexts.", __LINE__); |
$result_id = @ldap_read($this->conn_id, "", "(objectclass=*)", array("namingContexts")); |
if (@ldap_count_entries($this->conn_id, $result_id) == 1) { |
$this->_debug("got result for namingContexts", __LINE__); |
$entry_id = @ldap_first_entry($this->conn_id, $result_id); |
$attrs = @ldap_get_attributes($this->conn_id, $entry_id); |
$basedn = $attrs['namingContexts'][0]; |
if ($basedn != "") { |
$this->_debug("result for namingContexts was $basedn", __LINE__); |
$this->options['basedn'] = $basedn; |
} |
} |
@ldap_free_result($result_id); |
} |
// if base ist still not set, raise error |
if ($this->options['basedn'] == "") { |
return PEAR::raiseError("Auth_Container_LDAP: LDAP search base not specified!", 41); |
} |
return true; |
} |
// }}} |
// {{{ _isValidLink() |
/** |
* determines whether there is a valid ldap conenction or not |
* |
* @accessd private |
* @return boolean |
*/ |
function _isValidLink() |
{ |
if (is_resource($this->conn_id)) { |
if (get_resource_type($this->conn_id) == 'ldap link') { |
return true; |
} |
} |
return false; |
} |
// }}} |
// {{{ _setDefaults() |
/** |
* Set some default options |
* |
* @access private |
*/ |
function _setDefaults() |
{ |
$this->options['url'] = ''; |
$this->options['host'] = 'localhost'; |
$this->options['port'] = '389'; |
$this->options['version'] = 2; |
$this->options['referrals'] = true; |
$this->options['binddn'] = ''; |
$this->options['bindpw'] = ''; |
$this->options['basedn'] = ''; |
$this->options['userdn'] = ''; |
$this->options['userscope'] = 'sub'; |
$this->options['userattr'] = 'uid'; |
$this->options['userfilter'] = '(objectClass=posixAccount)'; |
$this->options['attributes'] = array(''); // no attributes |
// $this->options['attrformat'] = 'LDAP'; // returns attribute array as PHP LDAP functions return it |
$this->options['attrformat'] = 'AUTH'; // returns attribute like other Auth containers |
$this->options['group'] = ''; |
$this->options['groupdn'] = ''; |
$this->options['groupscope'] = 'sub'; |
$this->options['groupattr'] = 'cn'; |
$this->options['groupfilter'] = '(objectClass=groupOfUniqueNames)'; |
$this->options['memberattr'] = 'uniqueMember'; |
$this->options['memberisdn'] = true; |
$this->options['start_tls'] = false; |
$this->options['debug'] = false; |
$this->options['try_all'] = false; // Try all user ids returned not just the first one |
} |
// }}} |
// {{{ _parseOptions() |
/** |
* Parse options passed to the container class |
* |
* @access private |
* @param array |
*/ |
function _parseOptions($array) |
{ |
$array = $this->_setV12OptionsToV13($array); |
foreach ($array as $key => $value) { |
if (array_key_exists($key, $this->options)) { |
if ($key == 'attributes') { |
if (is_array($value)) { |
$this->options[$key] = $value; |
} else { |
$this->options[$key] = explode(',', $value); |
} |
} else { |
$this->options[$key] = $value; |
} |
} |
} |
} |
// }}} |
// {{{ _setV12OptionsToV13() |
/** |
* Adapt deprecated options from Auth 1.2 LDAP to Auth 1.3 LDAP |
* |
* @author Hugues Peeters <hugues.peeters@claroline.net> |
* @access private |
* @param array |
* @return array |
*/ |
function _setV12OptionsToV13($array) |
{ |
if (isset($array['useroc'])) |
$array['userfilter'] = "(objectClass=".$array['useroc'].")"; |
if (isset($array['groupoc'])) |
$array['groupfilter'] = "(objectClass=".$array['groupoc'].")"; |
if (isset($array['scope'])) |
$array['userscope'] = $array['scope']; |
return $array; |
} |
// }}} |
// {{{ _scope2function() |
/** |
* Get search function for scope |
* |
* @param string scope |
* @return string ldap search function |
*/ |
function _scope2function($scope) |
{ |
switch($scope) { |
case 'one': |
$function = 'ldap_list'; |
break; |
case 'base': |
$function = 'ldap_read'; |
break; |
default: |
$function = 'ldap_search'; |
break; |
} |
return $function; |
} |
// }}} |
// {{{ fetchData() |
/** |
* Fetch data from LDAP server |
* |
* Searches the LDAP server for the given username/password |
* combination. Escapes all LDAP meta characters in username |
* before performing the query. |
* |
* @param string Username |
* @param string Password |
* @return boolean |
*/ |
function fetchData($username, $password) |
{ |
$err = $this->_prepare(); |
if ($err !== true) { |
return PEAR::raiseError($err->getMessage(), $err->getCode()); |
} |
$err = $this->_getBaseDN(); |
if ($err !== true) { |
return PEAR::raiseError($err->getMessage(), $err->getCode()); |
} |
// UTF8 Encode username for LDAPv3 |
if (@ldap_get_option($this->conn_id, LDAP_OPT_PROTOCOL_VERSION, $ver) && $ver == 3) { |
$this->_debug('UTF8 encoding username for LDAPv3', __LINE__); |
$username = utf8_encode($username); |
} |
// make search filter |
$filter = sprintf('(&(%s=%s)%s)', |
$this->options['userattr'], |
$this->_quoteFilterString($username), |
$this->options['userfilter']); |
// make search base dn |
$search_basedn = $this->options['userdn']; |
if ($search_basedn != '' && substr($search_basedn, -1) != ',') { |
$search_basedn .= ','; |
} |
$search_basedn .= $this->options['basedn']; |
// attributes |
$attributes = $this->options['attributes']; |
// make functions params array |
$func_params = array($this->conn_id, $search_basedn, $filter, $attributes); |
// search function to use |
$func_name = $this->_scope2function($this->options['userscope']); |
$this->_debug("Searching with $func_name and filter $filter in $search_basedn", __LINE__); |
// search |
if (($result_id = @call_user_func_array($func_name, $func_params)) === false) { |
$this->_debug('User not found', __LINE__); |
} elseif (@ldap_count_entries($this->conn_id, $result_id) >= 1) { // did we get some possible results? |
$this->_debug('User(s) found', __LINE__); |
$first = true; |
$entry_id = null; |
do { |
// then get the user dn |
if ($first) { |
$entry_id = @ldap_first_entry($this->conn_id, $result_id); |
$first = false; |
} else { |
$entry_id = @ldap_next_entry($this->conn_id, $entry_id); |
if ($entry_id === false) |
break; |
} |
$user_dn = @ldap_get_dn($this->conn_id, $entry_id); |
// as the dn is not fetched as an attribute, we save it anyway |
if (is_array($attributes) && in_array('dn', $attributes)) { |
$this->_debug('Saving DN to AuthData', __LINE__); |
$this->_auth_obj->setAuthData('dn', $user_dn); |
} |
// fetch attributes |
if ($attributes = @ldap_get_attributes($this->conn_id, $entry_id)) { |
if (is_array($attributes) && isset($attributes['count']) && |
$attributes['count'] > 0) { |
// ldap_get_attributes() returns a specific multi dimensional array |
// format containing all the attributes and where each array starts |
// with a 'count' element providing the number of attributes in the |
// entry, or the number of values for attribute. For compatibility |
// reasons, it remains the default format returned by LDAP container |
// setAuthData(). |
// The code below optionally returns attributes in another format, |
// more compliant with other Auth containers, where each attribute |
// element are directly set in the 'authData' list. This option is |
// enabled by setting 'attrformat' to |
// 'AUTH' in the 'options' array. |
// eg. $this->options['attrformat'] = 'AUTH' |
if ( strtoupper($this->options['attrformat']) == 'AUTH' ) { |
$this->_debug('Saving attributes to Auth data in AUTH format', __LINE__); |
unset ($attributes['count']); |
foreach ($attributes as $attributeName => $attributeValue ) { |
if (is_int($attributeName)) continue; |
if (is_array($attributeValue) && isset($attributeValue['count'])) { |
unset ($attributeValue['count']); |
} |
if (count($attributeValue)<=1) $attributeValue = $attributeValue[0]; |
$this->_auth_obj->setAuthData($attributeName, $attributeValue); |
} |
} |
else |
{ |
$this->_debug('Saving attributes to Auth data in LDAP format', __LINE__); |
$this->_auth_obj->setAuthData('attributes', $attributes); |
} |
} |
} |
@ldap_free_result($result_id); |
// need to catch an empty password as openldap seems to return TRUE |
// if anonymous binding is allowed |
if ($password != "") { |
$this->_debug("Bind as $user_dn", __LINE__); |
// try binding as this user with the supplied password |
if (@ldap_bind($this->conn_id, $user_dn, $password)) { |
$this->_debug('Bind successful', __LINE__); |
// check group if appropiate |
if (strlen($this->options['group'])) { |
// decide whether memberattr value is a dn or the username |
$this->_debug('Checking group membership', __LINE__); |
$return = $this->checkGroup(($this->options['memberisdn']) ? $user_dn : $username); |
$this->_disconnect(); |
return $return; |
} else { |
$this->_debug('Authenticated', __LINE__); |
$this->_disconnect(); |
return true; // user authenticated |
} // checkGroup |
} // bind |
} // non-empty password |
} while ($this->options['try_all'] == true); // interate through entries |
} // get results |
// default |
$this->_debug('NOT authenticated!', __LINE__); |
$this->_disconnect(); |
return false; |
} |
// }}} |
// {{{ checkGroup() |
/** |
* Validate group membership |
* |
* Searches the LDAP server for group membership of the |
* supplied username. Quotes all LDAP filter meta characters in |
* the user name before querying the LDAP server. |
* |
* @param string Distinguished Name of the authenticated User |
* @return boolean |
*/ |
function checkGroup($user) |
{ |
$err = $this->_prepare(); |
if ($err !== true) { |
return PEAR::raiseError($err->getMessage(), $err->getCode()); |
} |
// make filter |
$filter = sprintf('(&(%s=%s)(%s=%s)%s)', |
$this->options['groupattr'], |
$this->options['group'], |
$this->options['memberattr'], |
$this->_quoteFilterString($user), |
$this->options['groupfilter']); |
// make search base dn |
$search_basedn = $this->options['groupdn']; |
if ($search_basedn != '' && substr($search_basedn, -1) != ',') { |
$search_basedn .= ','; |
} |
$search_basedn .= $this->options['basedn']; |
$func_params = array($this->conn_id, $search_basedn, $filter, |
array($this->options['memberattr'])); |
$func_name = $this->_scope2function($this->options['groupscope']); |
$this->_debug("Searching with $func_name and filter $filter in $search_basedn", __LINE__); |
// search |
if (($result_id = @call_user_func_array($func_name, $func_params)) != false) { |
if (@ldap_count_entries($this->conn_id, $result_id) == 1) { |
@ldap_free_result($result_id); |
$this->_debug('User is member of group', __LINE__); |
return true; |
} |
} |
// default |
$this->_debug('User is NOT member of group', __LINE__); |
return false; |
} |
// }}} |
// {{{ _debug() |
/** |
* Outputs debugging messages |
* |
* @access private |
* @param string Debugging Message |
* @param integer Line number |
*/ |
function _debug($msg = '', $line = 0) |
{ |
if ($this->options['debug'] == true) { |
if ($msg == '' && $this->_isValidLink()) { |
$msg = 'LDAP_Error: ' . @ldap_err2str(@ldap_errno($this->_conn_id)); |
} |
print("$line: $msg <br />"); |
} |
} |
// }}} |
// {{{ _quoteFilterString() |
/** |
* Escapes LDAP filter special characters as defined in RFC 2254. |
* |
* @access private |
* @param string Filter String |
*/ |
function _quoteFilterString($filter_str) |
{ |
$metas = array( '\\', '*', '(', ')', "\x00"); |
$quoted_metas = array('\\\\', '\*', '\(', '\)', "\\\x00"); |
return str_replace($metas, $quoted_metas, $filter_str); |
} |
// }}} |
} |
?> |
/branches/livraison_narmer/api/pear/Auth/Container/POP3.php |
---|
New file |
0,0 → 1,143 |
<?php |
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */ |
/** |
* Storage driver for use against a POP3 server |
* |
* PHP versions 4 and 5 |
* |
* LICENSE: This source file is subject to version 3.01 of the PHP license |
* that is available through the world-wide-web at the following URI: |
* http://www.php.net/license/3_01.txt. If you did not receive a copy of |
* the PHP License and are unable to obtain it through the web, please |
* send a note to license@php.net so we can mail you a copy immediately. |
* |
* @category Authentication |
* @package Auth |
* @author Stefan Ekman <stekman@sedata.org> |
* @author Martin Jansen <mj@php.net> |
* @author Mika Tuupola <tuupola@appelsiini.net> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version CVS: $Id: POP3.php,v 1.2 2006-12-14 15:04:28 jp_milcent Exp $ |
* @link http://pear.php.net/package/Auth |
* @since File available since Release 1.2.0 |
*/ |
/** |
* Include Auth_Container base class |
*/ |
require_once 'Auth/Container.php'; |
/** |
* Include PEAR package for error handling |
*/ |
require_once 'PEAR.php'; |
/** |
* Include PEAR Net_POP3 package |
*/ |
require_once 'Net/POP3.php'; |
/** |
* Storage driver for Authentication on a POP3 server. |
* |
* @category Authentication |
* @package Auth |
* @author Martin Jansen <mj@php.net> |
* @author Mika Tuupola <tuupola@appelsiini.net> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version Release: 1.4.3 File: $Revision: 1.2 $ |
* @link http://pear.php.net/package/Auth |
* @since Class available since Release 1.2.0 |
*/ |
class Auth_Container_POP3 extends Auth_Container |
{ |
// {{{ properties |
/** |
* POP3 Server |
* @var string |
*/ |
var $server='localhost'; |
/** |
* POP3 Server port |
* @var string |
*/ |
var $port='110'; |
/** |
* POP3 Authentication method |
* |
* Prefered POP3 authentication method. Acceptable values: |
* Boolean TRUE - Use Net_POP3's autodetection |
* String 'DIGEST-MD5','CRAM-MD5','LOGIN','PLAIN','APOP','USER' |
* - Attempt this authentication style first |
* then fallback to autodetection. |
* @var mixed |
*/ |
var $method=true; |
// }}} |
// {{{ Auth_Container_POP3() [constructor] |
/** |
* Constructor of the container class |
* |
* @param $server string server or server:port combination |
* @return object Returns an error object if something went wrong |
*/ |
function Auth_Container_POP3($server=null) |
{ |
if (isset($server) && !is_null($server)) { |
if (is_array($server)) { |
if (isset($server['host'])) { |
$this->server = $server['host']; |
} |
if (isset($server['port'])) { |
$this->port = $server['port']; |
} |
if (isset($server['method'])) { |
$this->method = $server['method']; |
} |
} else { |
if (strstr($server, ':')) { |
$serverparts = explode(':', trim($server)); |
$this->server = $serverparts[0]; |
$this->port = $serverparts[1]; |
} else { |
$this->server = $server; |
} |
} |
} |
} |
// }}} |
// {{{ fetchData() |
/** |
* Try to login to the POP3 server |
* |
* @param string Username |
* @param string Password |
* @return boolean |
*/ |
function fetchData($username, $password) |
{ |
$pop3 =& new Net_POP3(); |
$res = $pop3->connect($this->server, $this->port, $this->method); |
if (!$res) { |
return $res; |
} |
$result = $pop3->login($username, $password); |
$pop3->disconnect(); |
return $result; |
} |
// }}} |
} |
?> |
/branches/livraison_narmer/api/pear/Auth/Container/SAP.php |
---|
New file |
0,0 → 1,177 |
<?php |
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */ |
/** |
* Storage driver for use against a SAP system using the SAPRFC PHP extension. |
* |
* Requires the SAPRFC ext available at http://saprfc.sourceforge.net/ |
* |
* PHP version 5 |
* |
* LICENSE: This source file is subject to version 3.01 of the PHP license |
* that is available through the world-wide-web at the following URI: |
* http://www.php.net/license/3_01.txt. If you did not receive a copy of |
* the PHP License and are unable to obtain it through the web, please |
* send a note to license@php.net so we can mail you a copy immediately. |
* |
* @category Authentication |
* @package Auth |
* @author Stoyan Stefanov <ssttoo@gmail.com> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version CVS: $Id: SAP.php,v 1.1 2006-12-14 15:04:28 jp_milcent Exp $ |
* @link http://pear.php.net/package/Auth |
* @since File available since Release 1.4.0 |
*/ |
/** |
* Include Auth_Container base class |
*/ |
require_once 'Auth/Container.php'; |
/** |
* Include PEAR for error handling |
*/ |
require_once 'PEAR.php'; |
/** |
* Performs authentication against a SAP system using the SAPRFC PHP extension. |
* |
* When the option GETSSO2 is TRUE (default) |
* the Single Sign-On (SSO) ticket is retrieved |
* and stored as an Auth attribute called 'sap' |
* in order to be reused for consecutive connections. |
* |
* @category Authentication |
* @package Auth |
* @author Stoyan Stefanov <ssttoo@gmail.com> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version Release: 1.4.3 File: $Revision: 1.1 $ |
* @since Class available since Release 1.4.0 |
*/ |
class Auth_Container_SAP extends Auth_Container { |
// {{{ properties |
/** |
* @var array Default options |
*/ |
var $options = array( |
'CLIENT' => '000', |
'LANG' => 'EN', |
'GETSSO2' => true, |
); |
// }}} |
// {{{ Auth_Container_SAP() |
/** |
* Class constructor. Checks that required options |
* are present and that the SAPRFC extension is loaded |
* |
* Options that can be passed and their defaults: |
* <pre> |
* array( |
* 'ASHOST' => "", |
* 'SYSNR' => "", |
* 'CLIENT' => "000", |
* 'GWHOST' =>"", |
* 'GWSERV' =>"", |
* 'MSHOST' =>"", |
* 'R3NAME' =>"", |
* 'GROUP' =>"", |
* 'LANG' =>"EN", |
* 'TRACE' =>"", |
* 'GETSSO2'=> true |
* ) |
* </pre> |
* |
* @param array array of options. |
* @return void |
*/ |
function Auth_Container_SAP($options) |
{ |
$saprfc_loaded = PEAR::loadExtension('saprfc'); |
if (!$saprfc_loaded) { |
return PEAR::raiseError('Cannot use SAP authentication, ' |
.'SAPRFC extension not loaded!'); |
} |
if (empty($options['R3NAME']) && empty($options['ASHOST'])) { |
return PEAR::raiseError('R3NAME or ASHOST required for authentication'); |
} |
$this->options = array_merge($this->options, $options); |
} |
// }}} |
// {{{ fetchData() |
/** |
* Performs username and password check |
* |
* @param string Username |
* @param string Password |
* @return boolean TRUE on success (valid user), FALSE otherwise |
*/ |
function fetchData($username, $password) |
{ |
$connection_options = $this->options; |
$connection_options['USER'] = $username; |
$connection_options['PASSWD'] = $password; |
$rfc = saprfc_open($connection_options); |
if (!$rfc) { |
$message = "Couldn't connect to the SAP system."; |
$error = $this->getError(); |
if ($error['message']) { |
$message .= ': ' . $error['message']; |
} |
PEAR::raiseError($message, null, null, null, @$erorr['all']); |
return false; |
} else { |
if (!empty($this->options['GETSSO2'])) { |
if ($ticket = @saprfc_get_ticket($rfc)) { |
$this->options['MYSAPSSO2'] = $ticket; |
unset($this->options['GETSSO2']); |
$this->_auth_obj->setAuthData('sap', $this->options); |
} else { |
PEAR::raiseError("SSO ticket retrieval failed"); |
} |
} |
@saprfc_close($rfc); |
return true; |
} |
} |
// }}} |
// {{{ getError() |
/** |
* Retrieves the last error from the SAP connection |
* and returns it as an array. |
* |
* @return array Array of error information |
*/ |
function getError() |
{ |
$error = array(); |
$sap_error = saprfc_error(); |
if (empty($err)) { |
return $error; |
} |
$err = explode("n", $sap_error); |
foreach ($err AS $line) { |
$item = split(':', $line); |
$error[strtolower(trim($item[0]))] = trim($item[1]); |
} |
$error['all'] = $sap_error; |
return $error; |
} |
// }}} |
} |
?> |
/branches/livraison_narmer/api/pear/Auth/Container/MDB2.php |
---|
New file |
0,0 → 1,571 |
<?php |
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */ |
/** |
* Storage driver for use against PEAR MDB2 |
* |
* PHP versions 4 and 5 |
* |
* LICENSE: This source file is subject to version 3.01 of the PHP license |
* that is available through the world-wide-web at the following URI: |
* http://www.php.net/license/3_01.txt. If you did not receive a copy of |
* the PHP License and are unable to obtain it through the web, please |
* send a note to license@php.net so we can mail you a copy immediately. |
* |
* @category Authentication |
* @package Auth |
* @author Lorenzo Alberton <l.alberton@quipo.it> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version CVS: $Id: MDB2.php,v 1.1 2006-12-14 15:04:28 jp_milcent Exp $ |
* @link http://pear.php.net/package/Auth |
* @since File available since Release 1.3.0 |
*/ |
/** |
* Include Auth_Container base class |
*/ |
require_once 'Auth/Container.php'; |
/** |
* Include PEAR MDB2 package |
*/ |
require_once 'MDB2.php'; |
/** |
* Storage driver for fetching login data from a database |
* |
* This storage driver can use all databases which are supported |
* by the PEAR MDB2 abstraction layer to fetch login data. |
* |
* @category Authentication |
* @package Auth |
* @author Lorenzo Alberton <l.alberton@quipo.it> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version Release: 1.4.3 File: $Revision: 1.1 $ |
* @link http://pear.php.net/package/Auth |
* @since Class available since Release 1.3.0 |
*/ |
class Auth_Container_MDB2 extends Auth_Container |
{ |
// {{{ properties |
/** |
* Additional options for the storage container |
* @var array |
*/ |
var $options = array(); |
/** |
* MDB object |
* @var object |
*/ |
var $db = null; |
var $dsn = ''; |
/** |
* User that is currently selected from the DB. |
* @var string |
*/ |
var $activeUser = ''; |
// }}} |
// {{{ Auth_Container_MDB2() [constructor] |
/** |
* Constructor of the container class |
* |
* Initate connection to the database via PEAR::MDB2 |
* |
* @param string Connection data or MDB2 object |
* @return object Returns an error object if something went wrong |
*/ |
function Auth_Container_MDB2($dsn) |
{ |
$this->_setDefaults(); |
if (is_array($dsn)) { |
$this->_parseOptions($dsn); |
if (empty($this->options['dsn'])) { |
PEAR::raiseError('No connection parameters specified!'); |
} |
} else { |
$this->options['dsn'] = $dsn; |
} |
} |
// }}} |
// {{{ _connect() |
/** |
* Connect to database by using the given DSN string |
* |
* @access private |
* @param mixed DSN string | array | mdb object |
* @return mixed Object on error, otherwise bool |
*/ |
function _connect($dsn) |
{ |
if (is_string($dsn) || is_array($dsn)) { |
$this->db =& MDB2::connect($dsn, $this->options['db_options']); |
} elseif (is_subclass_of($dsn, 'MDB2_Driver_Common')) { |
$this->db = $dsn; |
} elseif (is_object($dsn) && MDB2::isError($dsn)) { |
return PEAR::raiseError($dsn->getMessage(), $dsn->code); |
} else { |
return PEAR::raiseError('The given dsn was not valid in file ' . __FILE__ . ' at line ' . __LINE__, |
41, |
PEAR_ERROR_RETURN, |
null, |
null |
); |
} |
if (MDB2::isError($this->db) || PEAR::isError($this->db)) { |
return PEAR::raiseError($this->db->getMessage(), $this->db->code); |
} |
if ($this->options['auto_quote']) { |
$this->options['final_table'] = $this->db->quoteIdentifier($this->options['table'], true); |
$this->options['final_usernamecol'] = $this->db->quoteIdentifier($this->options['usernamecol'], true); |
$this->options['final_passwordcol'] = $this->db->quoteIdentifier($this->options['passwordcol'], true); |
} else { |
$this->options['final_table'] = $this->options['table']; |
$this->options['final_usernamecol'] = $this->options['usernamecol']; |
$this->options['final_passwordcol'] = $this->options['passwordcol']; |
} |
return true; |
} |
// }}} |
// {{{ _prepare() |
/** |
* Prepare database connection |
* |
* This function checks if we have already opened a connection to |
* the database. If that's not the case, a new connection is opened. |
* |
* @access private |
* @return mixed True or a MDB error object. |
*/ |
function _prepare() |
{ |
if (is_subclass_of($this->db, 'MDB2_Driver_Common')) { |
return true; |
} |
return $this->_connect($this->options['dsn']); |
} |
// }}} |
// {{{ query() |
/** |
* Prepare query to the database |
* |
* This function checks if we have already opened a connection to |
* the database. If that's not the case, a new connection is opened. |
* After that the query is passed to the database. |
* |
* @access public |
* @param string Query string |
* @return mixed a MDB_result object or MDB_OK on success, a MDB |
* or PEAR error on failure |
*/ |
function query($query) |
{ |
$err = $this->_prepare(); |
if ($err !== true) { |
return $err; |
} |
return $this->db->exec($query); |
} |
// }}} |
// {{{ _setDefaults() |
/** |
* Set some default options |
* |
* @access private |
* @return void |
*/ |
function _setDefaults() |
{ |
$this->options['table'] = 'auth'; |
$this->options['usernamecol'] = 'username'; |
$this->options['passwordcol'] = 'password'; |
$this->options['dsn'] = ''; |
$this->options['db_fields'] = ''; |
$this->options['cryptType'] = 'md5'; |
$this->options['db_options'] = array(); |
$this->options['auto_quote'] = true; |
} |
// }}} |
// {{{ _parseOptions() |
/** |
* Parse options passed to the container class |
* |
* @access private |
* @param array |
*/ |
function _parseOptions($array) |
{ |
foreach ($array as $key => $value) { |
if (isset($this->options[$key])) { |
$this->options[$key] = $value; |
} |
} |
} |
// }}} |
// {{{ _quoteDBFields() |
/** |
* Quote the db_fields option to avoid the possibility of SQL injection. |
* |
* @access private |
* @return string A properly quoted string that can be concatenated into a |
* SELECT clause. |
*/ |
function _quoteDBFields() |
{ |
if (isset($this->options['db_fields'])) { |
if (is_array($this->options['db_fields'])) { |
if ($this->options['auto_quote']) { |
$fields = array(); |
foreach ($this->options['db_fields'] as $field) { |
$fields[] = $this->db->quoteIdentifier($field, true); |
} |
return implode(', ', $fields); |
} else { |
return implode(', ', $this->options['db_fields']); |
} |
} else { |
if (strlen($this->options['db_fields']) > 0) { |
if ($this->options['auto_quote']) { |
return $this->db->quoteIdentifier($this->options['db_fields'], true); |
} else { |
return $this->options['db_fields']; |
} |
} |
} |
} |
return ''; |
} |
// }}} |
// {{{ fetchData() |
/** |
* Get user information from database |
* |
* This function uses the given username to fetch |
* the corresponding login data from the database |
* table. If an account that matches the passed username |
* and password is found, the function returns true. |
* Otherwise it returns false. |
* |
* @param string Username |
* @param string Password |
* @param boolean If true password is secured using a md5 hash |
* the frontend and auth are responsible for making sure the container supports |
* challenge response password authentication |
* @return mixed Error object or boolean |
*/ |
function fetchData($username, $password, $isChallengeResponse=false) |
{ |
// Prepare for a database query |
$err = $this->_prepare(); |
if ($err !== true) { |
return PEAR::raiseError($err->getMessage(), $err->getCode()); |
} |
//Check if db_fields contains a *, if so assume all columns are selected |
if (is_string($this->options['db_fields']) |
&& strstr($this->options['db_fields'], '*')) { |
$sql_from = '*'; |
} else { |
$sql_from = $this->options['final_usernamecol']. |
", ".$this->options['final_passwordcol']; |
if (strlen($fields = $this->_quoteDBFields()) > 0) { |
$sql_from .= ', '.$fields; |
} |
} |
$query = sprintf("SELECT %s FROM %s WHERE %s = %s", |
$sql_from, |
$this->options['final_table'], |
$this->options['final_usernamecol'], |
$this->db->quote($username, 'text') |
); |
$res = $this->db->queryRow($query, null, MDB2_FETCHMODE_ASSOC); |
if (MDB2::isError($res) || PEAR::isError($res)) { |
return PEAR::raiseError($res->getMessage(), $res->getCode()); |
} |
if (!is_array($res)) { |
$this->activeUser = ''; |
return false; |
} |
// Perform trimming here before the hashing |
$password = trim($password, "\r\n"); |
$res[$this->options['passwordcol']] = trim($res[$this->options['passwordcol']], "\r\n"); |
// If using Challenge Response md5 the pass with the secret |
if ($isChallengeResponse) { |
$res[$this->options['passwordcol']] = |
md5($res[$this->options['passwordcol']].$this->_auth_obj->session['loginchallenege']); |
// UGLY cannot avoid without modifying verifyPassword |
if ($this->options['cryptType'] == 'md5') { |
$res[$this->options['passwordcol']] = md5($res[$this->options['passwordcol']]); |
} |
} |
if ($this->verifyPassword($password, |
$res[$this->options['passwordcol']], |
$this->options['cryptType'])) { |
// Store additional field values in the session |
foreach ($res as $key => $value) { |
if ($key == $this->options['passwordcol'] || |
$key == $this->options['usernamecol']) { |
continue; |
} |
// Use reference to the auth object if exists |
// This is because the auth session variable can change so a static call to setAuthData does not make sense |
$this->_auth_obj->setAuthData($key, $value); |
} |
return true; |
} |
$this->activeUser = $res[$this->options['usernamecol']]; |
return false; |
} |
// }}} |
// {{{ listUsers() |
/** |
* Returns a list of users from the container |
* |
* @return mixed array|PEAR_Error |
* @access public |
*/ |
function listUsers() |
{ |
$err = $this->_prepare(); |
if ($err !== true) { |
return PEAR::raiseError($err->getMessage(), $err->getCode()); |
} |
$retVal = array(); |
//Check if db_fields contains a *, if so assume all columns are selected |
if ( is_string($this->options['db_fields']) |
&& strstr($this->options['db_fields'], '*')) { |
$sql_from = '*'; |
} else { |
$sql_from = $this->options['final_usernamecol']. |
", ".$this->options['final_passwordcol']; |
if (strlen($fields = $this->_quoteDBFields()) > 0) { |
$sql_from .= ', '.$fields; |
} |
} |
$query = sprintf('SELECT %s FROM %s', |
$sql_from, |
$this->options['final_table'] |
); |
$res = $this->db->queryAll($query, null, MDB2_FETCHMODE_ASSOC); |
if (MDB2::isError($res)) { |
return PEAR::raiseError($res->getMessage(), $res->getCode()); |
} else { |
foreach ($res as $user) { |
$user['username'] = $user[$this->options['usernamecol']]; |
$retVal[] = $user; |
} |
} |
return $retVal; |
} |
// }}} |
// {{{ addUser() |
/** |
* Add user to the storage container |
* |
* @access public |
* @param string Username |
* @param string Password |
* @param mixed Additional information that are stored in the DB |
* |
* @return mixed True on success, otherwise error object |
*/ |
function addUser($username, $password, $additional = "") |
{ |
// Prepare for a database query |
$err = $this->_prepare(); |
if ($err !== true) { |
return PEAR::raiseError($err->getMessage(), $err->getCode()); |
} |
if (isset($this->options['cryptType']) && $this->options['cryptType'] == 'none') { |
$cryptFunction = 'strval'; |
} elseif (isset($this->options['cryptType']) && function_exists($this->options['cryptType'])) { |
$cryptFunction = $this->options['cryptType']; |
} else { |
$cryptFunction = 'md5'; |
} |
$password = $cryptFunction($password); |
$additional_key = ''; |
$additional_value = ''; |
if (is_array($additional)) { |
foreach ($additional as $key => $value) { |
if ($this->options['auto_quote']) { |
$additional_key .= ', ' . $this->db->quoteIdentifier($key, true); |
} else { |
$additional_key .= ', ' . $key; |
} |
$additional_value .= ', ' . $this->db->quote($value, 'text'); |
} |
} |
$query = sprintf("INSERT INTO %s (%s, %s%s) VALUES (%s, %s%s)", |
$this->options['final_table'], |
$this->options['final_usernamecol'], |
$this->options['final_passwordcol'], |
$additional_key, |
$this->db->quote($username, 'text'), |
$this->db->quote($password, 'text'), |
$additional_value |
); |
$res = $this->query($query); |
if (MDB2::isError($res)) { |
return PEAR::raiseError($res->getMessage(), $res->code); |
} |
return true; |
} |
// }}} |
// {{{ removeUser() |
/** |
* Remove user from the storage container |
* |
* @access public |
* @param string Username |
* |
* @return mixed True on success, otherwise error object |
*/ |
function removeUser($username) |
{ |
// Prepare for a database query |
$err = $this->_prepare(); |
if ($err !== true) { |
return PEAR::raiseError($err->getMessage(), $err->getCode()); |
} |
$query = sprintf("DELETE FROM %s WHERE %s = %s", |
$this->options['final_table'], |
$this->options['final_usernamecol'], |
$this->db->quote($username, 'text') |
); |
$res = $this->query($query); |
if (MDB2::isError($res)) { |
return PEAR::raiseError($res->getMessage(), $res->code); |
} |
return true; |
} |
// }}} |
// {{{ changePassword() |
/** |
* Change password for user in the storage container |
* |
* @param string Username |
* @param string The new password (plain text) |
*/ |
function changePassword($username, $password) |
{ |
// Prepare for a database query |
$err = $this->_prepare(); |
if ($err !== true) { |
return PEAR::raiseError($err->getMessage(), $err->getCode()); |
} |
if (isset($this->options['cryptType']) && $this->options['cryptType'] == 'none') { |
$cryptFunction = 'strval'; |
} elseif (isset($this->options['cryptType']) && function_exists($this->options['cryptType'])) { |
$cryptFunction = $this->options['cryptType']; |
} else { |
$cryptFunction = 'md5'; |
} |
$password = $cryptFunction($password); |
$query = sprintf("UPDATE %s SET %s = %s WHERE %s = %s", |
$this->options['final_table'], |
$this->options['final_passwordcol'], |
$this->db->quote($password, 'text'), |
$this->options['final_usernamecol'], |
$this->db->quote($username, 'text') |
); |
$res = $this->query($query); |
if (MDB2::isError($res)) { |
return PEAR::raiseError($res->getMessage(), $res->code); |
} |
return true; |
} |
// }}} |
// {{{ supportsChallengeResponse() |
/** |
* Determine if this container supports |
* password authentication with challenge response |
* |
* @return bool |
* @access public |
*/ |
function supportsChallengeResponse() |
{ |
return in_array($this->options['cryptType'], array('md5', 'none', '')); |
} |
// }}} |
// {{{ getCryptType() |
/** |
* Returns the selected crypt type for this container |
* |
* @return string Function used to crypt the password |
*/ |
function getCryptType() |
{ |
return $this->options['cryptType']; |
} |
// }}} |
} |
?> |
/branches/livraison_narmer/api/pear/Auth/Container/DB.php |
---|
New file |
0,0 → 1,578 |
<?php |
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */ |
/** |
* Storage driver for use against PEAR DB |
* |
* PHP versions 4 and 5 |
* |
* LICENSE: This source file is subject to version 3.01 of the PHP license |
* that is available through the world-wide-web at the following URI: |
* http://www.php.net/license/3_01.txt. If you did not receive a copy of |
* the PHP License and are unable to obtain it through the web, please |
* send a note to license@php.net so we can mail you a copy immediately. |
* |
* @category Authentication |
* @package Auth |
* @author Martin Jansen <mj@php.net> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version CVS: $Id: DB.php,v 1.2 2006-12-14 15:04:28 jp_milcent Exp $ |
* @link http://pear.php.net/package/Auth |
*/ |
/** |
* Include Auth_Container base class |
*/ |
require_once 'Auth/Container.php'; |
/** |
* Include PEAR DB |
*/ |
require_once 'DB.php'; |
/** |
* Storage driver for fetching login data from a database |
* |
* This storage driver can use all databases which are supported |
* by the PEAR DB abstraction layer to fetch login data. |
* |
* @category Authentication |
* @package Auth |
* @author Martin Jansen <mj@php.net> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version Release: 1.4.3 File: $Revision: 1.2 $ |
* @link http://pear.php.net/package/Auth |
*/ |
class Auth_Container_DB extends Auth_Container |
{ |
// {{{ properties |
/** |
* Additional options for the storage container |
* @var array |
*/ |
var $options = array(); |
/** |
* DB object |
* @var object |
*/ |
var $db = null; |
var $dsn = ''; |
/** |
* User that is currently selected from the DB. |
* @var string |
*/ |
var $activeUser = ''; |
// }}} |
// {{{ Auth_Container_DB [constructor] |
/** |
* Constructor of the container class |
* |
* Save the initial options passed to the container. Initiation of the DB |
* connection is no longer performed here and is only done when needed. |
* |
* @param string Connection data or DB object |
* @return object Returns an error object if something went wrong |
*/ |
function Auth_Container_DB($dsn) |
{ |
$this->_setDefaults(); |
if (is_array($dsn)) { |
$this->_parseOptions($dsn); |
if (empty($this->options['dsn'])) { |
PEAR::raiseError('No connection parameters specified!'); |
} |
} else { |
$this->options['dsn'] = $dsn; |
} |
} |
// }}} |
// {{{ _connect() |
/** |
* Connect to database by using the given DSN string |
* |
* @access private |
* @param string DSN string |
* @return mixed Object on error, otherwise bool |
*/ |
function _connect($dsn) |
{ |
if (is_string($dsn) || is_array($dsn)) { |
$this->db = DB::Connect($dsn, $this->options['db_options']); |
} elseif (is_subclass_of($dsn, 'db_common')) { |
$this->db = $dsn; |
} elseif (DB::isError($dsn)) { |
return PEAR::raiseError($dsn->getMessage(), $dsn->getCode()); |
} else { |
return PEAR::raiseError('The given dsn was not valid in file ' . __FILE__ . ' at line ' . __LINE__, |
41, |
PEAR_ERROR_RETURN, |
null, |
null |
); |
} |
if (DB::isError($this->db) || PEAR::isError($this->db)) { |
return PEAR::raiseError($this->db->getMessage(), $this->db->getCode()); |
} else { |
return true; |
} |
} |
// }}} |
// {{{ _prepare() |
/** |
* Prepare database connection |
* |
* This function checks if we have already opened a connection to |
* the database. If that's not the case, a new connection is opened. |
* |
* @access private |
* @return mixed True or a DB error object. |
*/ |
function _prepare() |
{ |
if (!DB::isConnection($this->db)) { |
$res = $this->_connect($this->options['dsn']); |
if (DB::isError($res) || PEAR::isError($res)) { |
return $res; |
} |
} |
if ($this->options['auto_quote'] && $this->db->dsn['phptype'] != 'sqlite') { |
$this->options['final_table'] = $this->db->quoteIdentifier($this->options['table']); |
$this->options['final_usernamecol'] = $this->db->quoteIdentifier($this->options['usernamecol']); |
$this->options['final_passwordcol'] = $this->db->quoteIdentifier($this->options['passwordcol']); |
} else { |
$this->options['final_table'] = $this->options['table']; |
$this->options['final_usernamecol'] = $this->options['usernamecol']; |
$this->options['final_passwordcol'] = $this->options['passwordcol']; |
} |
return true; |
} |
// }}} |
// {{{ query() |
/** |
* Prepare query to the database |
* |
* This function checks if we have already opened a connection to |
* the database. If that's not the case, a new connection is opened. |
* After that the query is passed to the database. |
* |
* @access public |
* @param string Query string |
* @return mixed a DB_result object or DB_OK on success, a DB |
* or PEAR error on failure |
*/ |
function query($query) |
{ |
$err = $this->_prepare(); |
if ($err !== true) { |
return $err; |
} |
return $this->db->query($query); |
} |
// }}} |
// {{{ _setDefaults() |
/** |
* Set some default options |
* |
* @access private |
* @return void |
*/ |
function _setDefaults() |
{ |
$this->options['table'] = 'auth'; |
$this->options['usernamecol'] = 'username'; |
$this->options['passwordcol'] = 'password'; |
$this->options['dsn'] = ''; |
$this->options['db_fields'] = ''; |
$this->options['cryptType'] = 'md5'; |
$this->options['db_options'] = array(); |
$this->options['auto_quote'] = true; |
} |
// }}} |
// {{{ _parseOptions() |
/** |
* Parse options passed to the container class |
* |
* @access private |
* @param array |
*/ |
function _parseOptions($array) |
{ |
foreach ($array as $key => $value) { |
if (isset($this->options[$key])) { |
$this->options[$key] = $value; |
} |
} |
} |
// }}} |
// {{{ _quoteDBFields() |
/** |
* Quote the db_fields option to avoid the possibility of SQL injection. |
* |
* @access private |
* @return string A properly quoted string that can be concatenated into a |
* SELECT clause. |
*/ |
function _quoteDBFields() |
{ |
if (isset($this->options['db_fields'])) { |
if (is_array($this->options['db_fields'])) { |
if ($this->options['auto_quote']) { |
$fields = array(); |
foreach ($this->options['db_fields'] as $field) { |
$fields[] = $this->db->quoteIdentifier($field); |
} |
return implode(', ', $fields); |
} else { |
return implode(', ', $this->options['db_fields']); |
} |
} else { |
if (strlen($this->options['db_fields']) > 0) { |
if ($this->options['auto_quote']) { |
return $this->db->quoteIdentifier($this->options['db_fields']); |
} else { |
return $this->options['db_fields']; |
} |
} |
} |
} |
return ''; |
} |
// }}} |
// {{{ fetchData() |
/** |
* Get user information from database |
* |
* This function uses the given username to fetch |
* the corresponding login data from the database |
* table. If an account that matches the passed username |
* and password is found, the function returns true. |
* Otherwise it returns false. |
* |
* @param string Username |
* @param string Password |
* @param boolean If true password is secured using a md5 hash |
* the frontend and auth are responsible for making sure the container supports |
* challenge response password authentication |
* @return mixed Error object or boolean |
*/ |
function fetchData($username, $password, $isChallengeResponse=false) |
{ |
// Prepare for a database query |
$err = $this->_prepare(); |
if ($err !== true) { |
return PEAR::raiseError($err->getMessage(), $err->getCode()); |
} |
// Find if db_fields contains a *, if so assume all columns are selected |
if (is_string($this->options['db_fields']) |
&& strstr($this->options['db_fields'], '*')) { |
$sql_from = "*"; |
} else { |
$sql_from = $this->options['final_usernamecol']. |
", ".$this->options['final_passwordcol']; |
if (strlen($fields = $this->_quoteDBFields()) > 0) { |
$sql_from .= ', '.$fields; |
} |
} |
$query = "SELECT ".$sql_from. |
" FROM ".$this->options['final_table']. |
" WHERE ".$this->options['final_usernamecol']." = ".$this->db->quoteSmart($username); |
$res = $this->db->getRow($query, null, DB_FETCHMODE_ASSOC); |
if (DB::isError($res)) { |
return PEAR::raiseError($res->getMessage(), $res->getCode()); |
} |
if (!is_array($res)) { |
$this->activeUser = ''; |
return false; |
} |
// Perform trimming here before the hashihg |
$password = trim($password, "\r\n"); |
$res[$this->options['passwordcol']] = trim($res[$this->options['passwordcol']], "\r\n"); |
// If using Challenge Response md5 the pass with the secret |
if ($isChallengeResponse) { |
$res[$this->options['passwordcol']] = md5($res[$this->options['passwordcol']] |
.$this->_auth_obj->session['loginchallenege']); |
// UGLY cannot avoid without modifying verifyPassword |
if ($this->options['cryptType'] == 'md5') { |
$res[$this->options['passwordcol']] = md5($res[$this->options['passwordcol']]); |
} |
//print " Hashed Password [{$res[$this->options['passwordcol']]}]<br/>\n"; |
} |
if ($this->verifyPassword($password, |
$res[$this->options['passwordcol']], |
$this->options['cryptType'])) { |
// Store additional field values in the session |
foreach ($res as $key => $value) { |
if ($key == $this->options['passwordcol'] || |
$key == $this->options['usernamecol']) { |
continue; |
} |
// Use reference to the auth object if exists |
// This is because the auth session variable can change so a |
// static call to setAuthData does not make sence |
$this->_auth_obj->setAuthData($key, $value); |
} |
return true; |
} |
$this->activeUser = $res[$this->options['usernamecol']]; |
return false; |
} |
// }}} |
// {{{ listUsers() |
/** |
* Returns a list of users from the container |
* |
* @return mixed |
* @access public |
*/ |
function listUsers() |
{ |
$err = $this->_prepare(); |
if ($err !== true) { |
return PEAR::raiseError($err->getMessage(), $err->getCode()); |
} |
$retVal = array(); |
// Find if db_fields contains a *, if so assume all col are selected |
if ( is_string($this->options['db_fields']) |
&& strstr($this->options['db_fields'], '*')) { |
$sql_from = "*"; |
} else { |
$sql_from = $this->options['final_usernamecol']. |
", ".$this->options['final_passwordcol']; |
if (strlen($fields = $this->_quoteDBFields()) > 0) { |
$sql_from .= ', '.$fields; |
} |
} |
$query = sprintf("SELECT %s FROM %s", |
$sql_from, |
$this->options['final_table'] |
); |
$res = $this->db->getAll($query, null, DB_FETCHMODE_ASSOC); |
if (DB::isError($res)) { |
return PEAR::raiseError($res->getMessage(), $res->getCode()); |
} else { |
foreach ($res as $user) { |
$user['username'] = $user[$this->options['usernamecol']]; |
$retVal[] = $user; |
} |
} |
return $retVal; |
} |
// }}} |
// {{{ addUser() |
/** |
* Add user to the storage container |
* |
* @access public |
* @param string Username |
* @param string Password |
* @param mixed Additional information that are stored in the DB |
* |
* @return mixed True on success, otherwise error object |
*/ |
function addUser($username, $password, $additional = "") |
{ |
$err = $this->_prepare(); |
if ($err !== true) { |
return PEAR::raiseError($err->getMessage(), $err->getCode()); |
} |
if ( isset($this->options['cryptType']) |
&& $this->options['cryptType'] == 'none') { |
$cryptFunction = 'strval'; |
} elseif ( isset($this->options['cryptType']) |
&& function_exists($this->options['cryptType'])) { |
$cryptFunction = $this->options['cryptType']; |
} else { |
$cryptFunction = 'md5'; |
} |
$password = $cryptFunction($password); |
$additional_key = ''; |
$additional_value = ''; |
if (is_array($additional)) { |
foreach ($additional as $key => $value) { |
if ($this->options['auto_quote']) { |
$additional_key .= ', ' . $this->db->quoteIdentifier($key); |
} else { |
$additional_key .= ', ' . $key; |
} |
$additional_value .= ", " . $this->db->quoteSmart($value); |
} |
} |
$query = sprintf("INSERT INTO %s (%s, %s%s) VALUES (%s, %s%s)", |
$this->options['final_table'], |
$this->options['final_usernamecol'], |
$this->options['final_passwordcol'], |
$additional_key, |
$this->db->quoteSmart($username), |
$this->db->quoteSmart($password), |
$additional_value |
); |
$res = $this->query($query); |
if (DB::isError($res)) { |
return PEAR::raiseError($res->getMessage(), $res->getCode()); |
} else { |
return true; |
} |
} |
// }}} |
// {{{ removeUser() |
/** |
* Remove user from the storage container |
* |
* @access public |
* @param string Username |
* |
* @return mixed True on success, otherwise error object |
*/ |
function removeUser($username) |
{ |
$err = $this->_prepare(); |
if ($err !== true) { |
return PEAR::raiseError($err->getMessage(), $err->getCode()); |
} |
$query = sprintf("DELETE FROM %s WHERE %s = %s", |
$this->options['final_table'], |
$this->options['final_usernamecol'], |
$this->db->quoteSmart($username) |
); |
$res = $this->query($query); |
if (DB::isError($res)) { |
return PEAR::raiseError($res->getMessage(), $res->getCode()); |
} else { |
return true; |
} |
} |
// }}} |
// {{{ changePassword() |
/** |
* Change password for user in the storage container |
* |
* @param string Username |
* @param string The new password (plain text) |
*/ |
function changePassword($username, $password) |
{ |
$err = $this->_prepare(); |
if ($err !== true) { |
return PEAR::raiseError($err->getMessage(), $err->getCode()); |
} |
if ( isset($this->options['cryptType']) |
&& $this->options['cryptType'] == 'none') { |
$cryptFunction = 'strval'; |
} elseif ( isset($this->options['cryptType']) |
&& function_exists($this->options['cryptType'])) { |
$cryptFunction = $this->options['cryptType']; |
} else { |
$cryptFunction = 'md5'; |
} |
$password = $cryptFunction($password); |
$query = sprintf("UPDATE %s SET %s = %s WHERE %s = %s", |
$this->options['final_table'], |
$this->options['final_passwordcol'], |
$this->db->quoteSmart($password), |
$this->options['final_usernamecol'], |
$this->db->quoteSmart($username) |
); |
$res = $this->query($query); |
if (DB::isError($res)) { |
return PEAR::raiseError($res->getMessage(), $res->getCode()); |
} else { |
return true; |
} |
} |
// }}} |
// {{{ supportsChallengeResponse() |
/** |
* Determine if this container supports |
* password authentication with challenge response |
* |
* @return bool |
* @access public |
*/ |
function supportsChallengeResponse() |
{ |
return in_array($this->options['cryptType'], array('md5', 'none', '')); |
} |
// }}} |
// {{{ getCryptType() |
/** |
* Returns the selected crypt type for this container |
*/ |
function getCryptType() |
{ |
return($this->options['cryptType']); |
} |
// }}} |
} |
?> |
/branches/livraison_narmer/api/pear/Auth/Container/IMAP.php |
---|
New file |
0,0 → 1,206 |
<?php |
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */ |
/** |
* Storage driver for use against IMAP servers |
* |
* PHP versions 4 and 5 |
* |
* LICENSE: This source file is subject to version 3.01 of the PHP license |
* that is available through the world-wide-web at the following URI: |
* http://www.php.net/license/3_01.txt. If you did not receive a copy of |
* the PHP License and are unable to obtain it through the web, please |
* send a note to license@php.net so we can mail you a copy immediately. |
* |
* @category Authentication |
* @package Auth |
* @author Jeroen Houben <jeroen@terena.nl> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version CVS: $Id: IMAP.php,v 1.2 2006-12-14 15:04:28 jp_milcent Exp $ |
* @link http://pear.php.net/package/Auth |
* @since File available since Release 1.2.0 |
*/ |
/** |
* Include Auth_Container base class |
*/ |
require_once "Auth/Container.php"; |
/** |
* Include PEAR class for error handling |
*/ |
require_once "PEAR.php"; |
/** |
* Storage driver for fetching login data from an IMAP server |
* |
* This class is based on LDAP containers, but it very simple. |
* By default it connects to localhost:143 |
* The constructor will first check if the host:port combination is |
* actually reachable. This behaviour can be disabled. |
* It then tries to create an IMAP stream (without opening a mailbox) |
* If you wish to pass extended options to the connections, you may |
* do so by specifying protocol options. |
* |
* To use this storage containers, you have to use the |
* following syntax: |
* |
* <?php |
* ... |
* $params = array( |
* 'host' => 'mail.example.com', |
* 'port' => 143, |
* ); |
* $myAuth = new Auth('IMAP', $params); |
* ... |
* |
* By default we connect without any protocol options set. However, some |
* servers require you to connect with the notls or norsh options set. |
* To do this you need to add the following value to the params array: |
* 'baseDSN' => '/imap/notls/norsh' |
* |
* To connect to an SSL IMAP server: |
* 'baseDSN' => '/imap/ssl' |
* |
* To connect to an SSL IMAP server with a self-signed certificate: |
* 'baseDSN' => '/imap/ssl/novalidate-cert' |
* |
* Further options may be available and can be found on the php site at |
* http://www.php.net/manual/function.imap-open.php |
* |
* @category Authentication |
* @package Auth |
* @author Jeroen Houben <jeroen@terena.nl> |
* @author Cipriano Groenendal <cipri@campai.nl> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version Release: 1.4.3 File: $Revision: 1.2 $ |
* @link http://pear.php.net/package/Auth |
* @since Class available since Release 1.2.0 |
*/ |
class Auth_Container_IMAP extends Auth_Container |
{ |
// {{{ properties |
/** |
* Options for the class |
* @var array |
*/ |
var $options = array(); |
// }}} |
// {{{ Auth_Container_IMAP() [constructor] |
/** |
* Constructor of the container class |
* |
* @param $params associative array with host, port, baseDSN, checkServer |
* and userattr key |
* @return object Returns an error object if something went wrong |
* @todo Use PEAR Net_IMAP if IMAP extension not loaded |
*/ |
function Auth_Container_IMAP($params) |
{ |
if (!extension_loaded('imap')) { |
return PEAR::raiseError('Cannot use IMAP authentication, ' |
.'IMAP extension not loaded!', 41, PEAR_ERROR_DIE); |
} |
$this->_setDefaults(); |
// set parameters (if any) |
if (is_array($params)) { |
$this->_parseOptions($params); |
} |
if ($this->options['checkServer']) { |
$this->_checkServer($this->options['timeout']); |
} |
return true; |
} |
// }}} |
// {{{ _setDefaults() |
/** |
* Set some default options |
* |
* @access private |
*/ |
function _setDefaults() |
{ |
$this->options['host'] = 'localhost'; |
$this->options['port'] = 143; |
$this->options['baseDSN'] = ''; |
$this->options['checkServer'] = true; |
$this->options['timeout'] = 20; |
} |
// }}} |
// {{{ _checkServer() |
/** |
* Check if the given server and port are reachable |
* |
* @access private |
*/ |
function _checkServer() { |
$fp = @fsockopen ($this->options['host'], $this->options['port'], |
$errno, $errstr, $this->options['timeout']); |
if (is_resource($fp)) { |
@fclose($fp); |
} else { |
$message = "Error connecting to IMAP server " |
. $this->options['host'] |
. ":" . $this->options['port']; |
return PEAR::raiseError($message, 41); |
} |
} |
// }}} |
// {{{ _parseOptions() |
/** |
* Parse options passed to the container class |
* |
* @access private |
* @param array |
*/ |
function _parseOptions($array) |
{ |
foreach ($array as $key => $value) { |
$this->options[$key] = $value; |
} |
} |
// }}} |
// {{{ fetchData() |
/** |
* Try to open a IMAP stream using $username / $password |
* |
* @param string Username |
* @param string Password |
* @return boolean |
*/ |
function fetchData($username, $password) |
{ |
$dsn = '{'.$this->options['host'].':'.$this->options['port'].$this->options['baseDSN'].'}'; |
$conn = @imap_open ($dsn, $username, $password, OP_HALFOPEN); |
if (is_resource($conn)) { |
$this->activeUser = $username; |
@imap_close($conn); |
return true; |
} else { |
$this->activeUser = ''; |
return false; |
} |
} |
// }}} |
} |
?> |
/branches/livraison_narmer/api/pear/Auth/Container/PEAR.php |
---|
New file |
0,0 → 1,103 |
<?php |
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */ |
/** |
* Storage driver for use against PEAR website |
* |
* PHP versions 4 and 5 |
* |
* LICENSE: This source file is subject to version 3.01 of the PHP license |
* that is available through the world-wide-web at the following URI: |
* http://www.php.net/license/3_01.txt. If you did not receive a copy of |
* the PHP License and are unable to obtain it through the web, please |
* send a note to license@php.net so we can mail you a copy immediately. |
* |
* @category Authentication |
* @package Auth |
* @author Yavor Shahpasov <yavo@netsmart.com.cy> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version CVS: $Id: PEAR.php,v 1.1 2006-12-14 15:04:28 jp_milcent Exp $ |
* @link http://pear.php.net/package/Auth |
* @since File available since Release 1.3.0 |
*/ |
/** |
* Include Auth_Container base class |
*/ |
require_once 'Auth/Container.php'; |
/** |
* Include PEAR XML_RPC |
*/ |
require_once 'XML/RPC.php'; |
/** |
* Storage driver for authenticating against PEAR website |
* |
* This driver provides a method for authenticating against the pear.php.net |
* authentication system. |
* |
* @category Authentication |
* @package Auth |
* @author Yavor Shahpasov <yavo@netsmart.com.cy> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version Release: 1.4.3 File: $Revision: 1.1 $ |
* @link http://pear.php.net/package/Auth |
* @since Class available since Release 1.3.0 |
*/ |
class Auth_Container_Pear extends Auth_Container |
{ |
// {{{ Auth_Container_Pear() [constructor] |
/** |
* Constructor |
* |
* Currently does nothing |
* |
* @return void |
*/ |
function Auth_Container_Pear() |
{ |
} |
// }}} |
// {{{ fetchData() |
/** |
* Get user information from pear.php.net |
* |
* This function uses the given username and password to authenticate |
* against the pear.php.net website |
* |
* @param string Username |
* @param string Password |
* @return mixed Error object or boolean |
*/ |
function fetchData($username, $password) |
{ |
$rpc = new XML_RPC_Client('/xmlrpc.php', 'pear.php.net'); |
$rpc_message = new XML_RPC_Message("user.info", array(new XML_RPC_Value($username, "string")) ); |
// Error Checking howto ??? |
$result = $rpc->send($rpc_message); |
$value = $result->value(); |
$userinfo = xml_rpc_decode($value); |
if ($userinfo['password'] == md5($password)) { |
$this->activeUser = $userinfo['handle']; |
foreach ($userinfo as $uk=>$uv) { |
$this->_auth_obj->setAuthData($uk, $uv); |
} |
return true; |
} |
return false; |
} |
// }}} |
} |
?> |
/branches/livraison_narmer/api/pear/Auth/Container/RADIUS.php |
---|
New file |
0,0 → 1,180 |
<?php |
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */ |
/** |
* Storage driver for use against RADIUS servers |
* |
* PHP versions 4 and 5 |
* |
* LICENSE: This source file is subject to version 3.01 of the PHP license |
* that is available through the world-wide-web at the following URI: |
* http://www.php.net/license/3_01.txt. If you did not receive a copy of |
* the PHP License and are unable to obtain it through the web, please |
* send a note to license@php.net so we can mail you a copy immediately. |
* |
* @category Authentication |
* @package Auth |
* @author Michael Bretterklieber <michael@bretterklieber.com> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version CVS: $Id: RADIUS.php,v 1.2 2006-12-14 15:04:28 jp_milcent Exp $ |
* @link http://pear.php.net/package/Auth |
* @since File available since Release 1.2.0 |
*/ |
/** |
* Include Auth_Container base class |
*/ |
require_once "Auth/Container.php"; |
/** |
* Include PEAR Auth_RADIUS package |
*/ |
require_once "Auth/RADIUS.php"; |
/** |
* Storage driver for authenticating users against RADIUS servers. |
* |
* @category Authentication |
* @package Auth |
* @author Michael Bretterklieber <michael@bretterklieber.com> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version Release: 1.4.3 File: $Revision: 1.2 $ |
* @link http://pear.php.net/package/Auth |
* @since Class available since Release 1.2.0 |
*/ |
class Auth_Container_RADIUS extends Auth_Container |
{ |
// {{{ properties |
/** |
* Contains a RADIUS object |
* @var object |
*/ |
var $radius; |
/** |
* Contains the authentication type |
* @var string |
*/ |
var $authtype; |
// }}} |
// {{{ Auth_Container_RADIUS() [constructor] |
/** |
* Constructor of the container class. |
* |
* $options can have these keys: |
* 'servers' an array containing an array: servername, port, |
* sharedsecret, timeout, maxtries |
* 'configfile' The filename of the configuration file |
* 'authtype' The type of authentication, one of: PAP, CHAP_MD5, |
* MSCHAPv1, MSCHAPv2, default is PAP |
* |
* @param $options associative array |
* @return object Returns an error object if something went wrong |
*/ |
function Auth_Container_RADIUS($options) |
{ |
$this->authtype = 'PAP'; |
if (isset($options['authtype'])) { |
$this->authtype = $options['authtype']; |
} |
$classname = 'Auth_RADIUS_' . $this->authtype; |
if (!class_exists($classname)) { |
PEAR::raiseError("Unknown Authtype, please use one of: " |
."PAP, CHAP_MD5, MSCHAPv1, MSCHAPv2!", 41, PEAR_ERROR_DIE); |
} |
$this->radius = new $classname; |
if (isset($options['configfile'])) { |
$this->radius->setConfigfile($options['configfile']); |
} |
$servers = $options['servers']; |
if (is_array($servers)) { |
foreach ($servers as $server) { |
$servername = $server[0]; |
$port = isset($server[1]) ? $server[1] : 0; |
$sharedsecret = isset($server[2]) ? $server[2] : 'testing123'; |
$timeout = isset($server[3]) ? $server[3] : 3; |
$maxtries = isset($server[4]) ? $server[4] : 3; |
$this->radius->addServer($servername, $port, $sharedsecret, $timeout, $maxtries); |
} |
} |
if (!$this->radius->start()) { |
PEAR::raiseError($this->radius->getError(), 41, PEAR_ERROR_DIE); |
} |
} |
// }}} |
// {{{ fetchData() |
/** |
* Authenticate |
* |
* @param string Username |
* @param string Password |
* @return bool true on success, false on reject |
*/ |
function fetchData($username, $password, $challenge = null) |
{ |
switch($this->authtype) { |
case 'CHAP_MD5': |
case 'MSCHAPv1': |
if (isset($challenge)) { |
$this->radius->challenge = $challenge; |
$this->radius->chapid = 1; |
$this->radius->response = pack('H*', $password); |
} else { |
require_once 'Crypt/CHAP.php'; |
$classname = 'Crypt_' . $this->authtype; |
$crpt = new $classname; |
$crpt->password = $password; |
$this->radius->challenge = $crpt->challenge; |
$this->radius->chapid = $crpt->chapid; |
$this->radius->response = $crpt->challengeResponse(); |
break; |
} |
case 'MSCHAPv2': |
require_once 'Crypt/CHAP.php'; |
$crpt = new Crypt_MSCHAPv2; |
$crpt->username = $username; |
$crpt->password = $password; |
$this->radius->challenge = $crpt->authChallenge; |
$this->radius->peerChallenge = $crpt->peerChallenge; |
$this->radius->chapid = $crpt->chapid; |
$this->radius->response = $crpt->challengeResponse(); |
break; |
default: |
$this->radius->password = $password; |
break; |
} |
$this->radius->username = $username; |
$this->radius->putAuthAttributes(); |
$result = $this->radius->send(); |
if (PEAR::isError($result)) { |
return false; |
} |
$this->radius->getAttributes(); |
// just for debugging |
// $this->radius->dumpAttributes(); |
return $result; |
} |
// }}} |
} |
?> |
/branches/livraison_narmer/api/pear/Auth/Container/SOAP5.php |
---|
New file |
0,0 → 1,267 |
<?php |
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */ |
/** |
* Storage driver for use against a SOAP service using PHP5 SoapClient |
* |
* PHP version 5 |
* |
* LICENSE: This source file is subject to version 3.01 of the PHP license |
* that is available through the world-wide-web at the following URI: |
* http://www.php.net/license/3_01.txt. If you did not receive a copy of |
* the PHP License and are unable to obtain it through the web, please |
* send a note to license@php.net so we can mail you a copy immediately. |
* |
* @category Authentication |
* @package Auth |
* @author Based upon Auth_Container_SOAP by Bruno Pedro <bpedro@co.sapo.pt> |
* @author Marcel Oelke <puRe@rednoize.com> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version CVS: $Id: SOAP5.php,v 1.1 2006-12-14 15:04:28 jp_milcent Exp $ |
* @since File available since Release 1.4.0 |
*/ |
/** |
* Include Auth_Container base class |
*/ |
require_once "Auth/Container.php"; |
/** |
* Include PEAR package for error handling |
*/ |
require_once "PEAR.php"; |
/** |
* Storage driver for fetching login data from SOAP using the PHP5 Builtin SOAP |
* functions. This is a modification of the SOAP Storage driver from Bruno Pedro |
* thats using the PEAR SOAP Package. |
* |
* This class takes one parameter (options), where |
* you specify the following fields: |
* * location and uri, or wsdl file |
* * method to call on the SOAP service |
* * usernamefield, the name of the parameter where the username is supplied |
* * passwordfield, the name of the parameter where the password is supplied |
* * matchpassword, whether to look for the password in the response from |
* the function call or assume that no errors means user |
* authenticated. |
* |
* See http://www.php.net/manual/en/ref.soap.php for further details |
* on options for the PHP5 SoapClient which are passed through. |
* |
* Example usage without WSDL: |
* |
* <?php |
* |
* $options = array ( |
* 'wsdl' => NULL, |
* 'location' => 'http://your.soap.service/endpoint', |
* 'uri' => 'urn:/Your/Namespace', |
* 'method' => 'checkAuth', |
* 'usernamefield' => 'username', |
* 'passwordfield' => 'password', |
* 'matchpasswords' => false, |
* '_features' => array ( |
* 'extra_parameter' => 'example_value', |
* 'another_parameter' => 'foobar' |
* ) |
* ); |
* |
* $auth = new Auth('SOAP5', $options); |
* $auth->start(); |
* |
* ?> |
* |
* Example usage with WSDL: |
* |
* <?php |
* |
* $options = array ( |
* 'wsdl' => 'http://your.soap.service/wsdl', |
* 'method' => 'checkAuth', |
* 'usernamefield' => 'username', |
* 'passwordfield' => 'password', |
* 'matchpasswords' => false, |
* '_features' => array ( |
* 'extra_parameter' => 'example_value', |
* 'another_parameter' => 'foobar' |
* ) |
* ); |
* |
* $auth = new Auth('SOAP5', $options); |
* $auth->start(); |
* |
* ?> |
* |
* @category Authentication |
* @package Auth |
* @author Based upon Auth_Container_SOAP by Bruno Pedro <bpedro@co.sapo.pt> |
* @author Marcel Oelke <puRe@rednoize.com> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version Release: 1.4.3 File: $Revision: 1.1 $ |
* @since Class available since Release 1.4.0 |
*/ |
class Auth_Container_SOAP5 extends Auth_Container |
{ |
// {{{ properties |
/** |
* Required options for the class |
* @var array |
* @access private |
*/ |
var $_requiredOptions = array( |
'location', |
'uri', |
'method', |
'usernamefield', |
'passwordfield', |
'wsdl', |
); |
/** |
* Options for the class |
* @var array |
* @access private |
*/ |
var $_options = array(); |
/** |
* Optional SOAP features |
* @var array |
* @access private |
*/ |
var $_features = array(); |
/** |
* The SOAP response |
* @var array |
* @access public |
*/ |
var $soapResponse = array(); |
// }}} |
// {{{ Auth_Container_SOAP5() |
/** |
* Constructor of the container class |
* |
* @param $options, associative array with endpoint, namespace, method, |
* usernamefield, passwordfield and optional features |
*/ |
function Auth_Container_SOAP5($options) |
{ |
$this->_setDefaults(); |
foreach ($options as $name => $value) { |
$this->_options[$name] = $value; |
} |
if (!empty($this->_options['_features'])) { |
$this->_features = $this->_options['_features']; |
unset($this->_options['_features']); |
} |
} |
// }}} |
// {{{ fetchData() |
/** |
* Fetch data from SOAP service |
* |
* Requests the SOAP service for the given username/password |
* combination. |
* |
* @param string Username |
* @param string Password |
* @return mixed Returns the SOAP response or false if something went wrong |
*/ |
function fetchData($username, $password) |
{ |
$result = $this->_validateOptions(); |
if (PEAR::isError($result)) |
return $result; |
// create a SOAP client |
$soapClient = new SoapClient($this->_options["wsdl"], $this->_options); |
$params = array(); |
// first, assign the optional features |
foreach ($this->_features as $fieldName => $fieldValue) { |
$params[$fieldName] = $fieldValue; |
} |
// assign username and password ... |
$params[$this->_options['usernamefield']] = $username; |
$params[$this->_options['passwordfield']] = $password; |
try { |
$this->soapResponse = $soapClient->__soapCall($this->_options['method'], $params); |
if ($this->_options['matchpasswords']) { |
// check if passwords match |
if ($password == $this->soapResponse[$this->_options['passwordfield']]) { |
return true; |
} else { |
return false; |
} |
} else { |
return true; |
} |
} catch (SoapFault $e) { |
return PEAR::raiseError("Error retrieving authentication data. Received SOAP Fault: ".$e->faultstring, $e->faultcode); |
} |
} |
// }}} |
// {{{ _validateOptions() |
/** |
* Validate that the options passed to the container class are enough for us to proceed |
* |
* @access private |
* @param array |
*/ |
function _validateOptions($array) |
{ |
if ( ( is_null($this->options['wsdl']) |
&& is_null($this->options['location']) |
&& is_null($this->options['uri'])) |
|| ( is_null($this->options['wsdl']) |
&& ( is_null($this->options['location']) |
|| is_null($this->options['uri'])))) { |
return PEAR::raiseError('Either a WSDL file or a location/uri pair must be specified.'); |
} |
if (is_null($this->options['method'])) { |
return PEAR::raiseError('A method to call on the soap service must be specified.'); |
} |
return true; |
} |
// }}} |
// {{{ _setDefaults() |
/** |
* Set some default options |
* |
* @access private |
* @return void |
*/ |
function _setDefaults() |
{ |
$this->options['wsdl'] = null; |
$this->options['location'] = null; |
$this->options['uri'] = null; |
$this->options['method'] = null; |
$this->options['usernamefield'] = 'username'; |
$this->options['passwordfield'] = 'password'; |
$this->options['matchpasswords'] = true; |
} |
// }}} |
} |
?> |
/branches/livraison_narmer/api/pear/Auth/Container/vpopmail.php |
---|
New file |
0,0 → 1,87 |
<?php |
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */ |
/** |
* Storage driver for use against vpopmail setups |
* |
* PHP versions 4 and 5 |
* |
* LICENSE: This source file is subject to version 3.01 of the PHP license |
* that is available through the world-wide-web at the following URI: |
* http://www.php.net/license/3_01.txt. If you did not receive a copy of |
* the PHP License and are unable to obtain it through the web, please |
* send a note to license@php.net so we can mail you a copy immediately. |
* |
* @category Authentication |
* @package Auth |
* @author Stanislav Grozev <tacho@orbitel.bg> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version CVS: $Id: vpopmail.php,v 1.2 2006-12-14 15:04:28 jp_milcent Exp $ |
* @link http://pear.php.net/package/Auth |
* @since File available since Release 1.2.0 |
*/ |
/** |
* Include Auth_Container base class |
*/ |
require_once "Auth/Container.php"; |
/** |
* Include PEAR package for error handling |
*/ |
require_once "PEAR.php"; |
/** |
* Storage driver for fetching login data from vpopmail |
* |
* @category Authentication |
* @package Auth |
* @author Stanislav Grozev <tacho@orbitel.bg> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version Release: 1.4.3 File: $Revision: 1.2 $ |
* @link http://pear.php.net/package/Auth |
* @since Class available since Release 1.2.0 |
*/ |
class Auth_Container_vpopmail extends Auth_Container { |
// {{{ Constructor |
/** |
* Constructor of the container class |
* |
* @return void |
*/ |
function Auth_Container_vpopmail() |
{ |
if (!extension_loaded('vpopmail')) { |
return PEAR::raiseError('Cannot use VPOPMail authentication, ' |
.'VPOPMail extension not loaded!', 41, PEAR_ERROR_DIE); |
} |
} |
// }}} |
// {{{ fetchData() |
/** |
* Get user information from vpopmail |
* |
* @param string Username - has to be valid email address |
* @param string Password |
* @return boolean |
*/ |
function fetchData($username, $password) |
{ |
$userdata = array(); |
$userdata = preg_split("/@/", $username, 2); |
$result = @vpopmail_auth_user($userdata[0], $userdata[1], $password); |
return $result; |
} |
// }}} |
} |
?> |
/branches/livraison_narmer/api/pear/Auth/Container/KADM5.php |
---|
New file |
0,0 → 1,170 |
<?php |
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */ |
/** |
* Storage driver for Authentication on a Kerberos V server. |
* |
* PHP versions 4 and 5 |
* |
* LICENSE: This source file is subject to version 3.01 of the PHP license |
* that is available through the world-wide-web at the following URI: |
* http://www.php.net/license/3_01.txt. If you did not receive a copy of |
* the PHP License and are unable to obtain it through the web, please |
* send a note to license@php.net so we can mail you a copy immediately. |
* |
* @category Authentication |
* @package Auth |
* @author Andrew Teixeira <ateixeira@gmail.com> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version CVS: $Id: KADM5.php,v 1.1 2006-12-14 15:04:28 jp_milcent Exp $ |
* @link http://pear.php.net/package/Auth |
* @since File available since Release 1.4.0 |
*/ |
/** |
* Include Auth_Container base class |
*/ |
require_once 'Auth/Container.php'; |
/** |
* Include PEAR for error handling |
*/ |
require_once 'PEAR.php'; |
/** |
* Storage driver for Authentication on a Kerberos V server. |
* |
* Available options: |
* hostname: The hostname of the kerberos server |
* realm: The Kerberos V realm |
* timeout: The timeout for checking the server |
* checkServer: Set to true to check if the server is running when |
* constructing the object |
* |
* @category Authentication |
* @package Auth |
* @author Andrew Teixeira <ateixeira@gmail.com> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version Release: 1.4.3 File: $Revision: 1.1 $ |
* @link http://pear.php.net/package/Auth |
* @since Class available since Release 1.4.0 |
*/ |
class Auth_Container_KADM5 extends Auth_Container { |
// {{{ properties |
/** |
* Options for the class |
* @var string |
*/ |
var $options = array(); |
// }}} |
// {{{ Auth_Container_KADM5() |
/** |
* Constructor of the container class |
* |
* $options can have these keys: |
* 'hostname' The hostname of the kerberos server |
* 'realm' The Kerberos V realm |
* 'timeout' The timeout for checking the server |
* 'checkServer' Set to true to check if the server is running when |
* constructing the object |
* |
* @param $options associative array |
* @return object Returns an error object if something went wrong |
*/ |
function Auth_Container_KADM5($options) { |
if (!extension_loaded('kadm5')) { |
return PEAR::raiseError("Cannot use Kerberos V authentication, KADM5 extension not loaded!", 41, PEAR_ERROR_DIE); |
} |
$this->_setDefaults(); |
if (isset($options['hostname'])) { |
$this->options['hostname'] = $options['hostname']; |
} |
if (isset($options['realm'])) { |
$this->options['realm'] = $options['realm']; |
} |
if (isset($options['timeout'])) { |
$this->options['timeout'] = $options['timeout']; |
} |
if (isset($options['checkServer'])) { |
$this->options['checkServer'] = $options['checkServer']; |
} |
if ($this->options['checkServer']) { |
$this->_checkServer(); |
} |
} |
// }}} |
// {{{ fetchData() |
/** |
* Try to login to the KADM5 server |
* |
* @param string Username |
* @param string Password |
* @return boolean |
*/ |
function fetchData($username, $password) { |
if ( ($username == NULL) || ($password == NULL) ) { |
return false; |
} |
$server = $this->options['hostname']; |
$realm = $this->options['realm']; |
$check = @kadm5_init_with_password($server, $realm, $username, $password); |
if ($check == false) { |
return false; |
} else { |
return true; |
} |
} |
// }}} |
// {{{ _setDefaults() |
/** |
* Set some default options |
* |
* @access private |
*/ |
function _setDefaults() { |
$this->options['hostname'] = 'localhost'; |
$this->options['realm'] = NULL; |
$this->options['timeout'] = 10; |
$this->options['checkServer'] = false; |
} |
// }}} |
// {{{ _checkServer() |
/** |
* Check if the given server and port are reachable |
* |
* @access private |
*/ |
function _checkServer() { |
$fp = @fsockopen ($this->options['hostname'], 88, $errno, $errstr, $this->options['timeout']); |
if (is_resource($fp)) { |
@fclose($fp); |
} else { |
$message = "Error connecting to Kerberos V server " |
.$this->options['hostname'].":".$this->options['port']; |
return PEAR::raiseError($message, 41, PEAR_ERROR_DIE); |
} |
} |
// }}} |
} |
?> |
/branches/livraison_narmer/api/pear/Auth/Container/MDB.php |
---|
New file |
0,0 → 1,573 |
<?php |
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */ |
/** |
* Storage driver for use against PEAR MDB |
* |
* PHP versions 4 and 5 |
* |
* LICENSE: This source file is subject to version 3.01 of the PHP license |
* that is available through the world-wide-web at the following URI: |
* http://www.php.net/license/3_01.txt. If you did not receive a copy of |
* the PHP License and are unable to obtain it through the web, please |
* send a note to license@php.net so we can mail you a copy immediately. |
* |
* @category Authentication |
* @package Auth |
* @author Lorenzo Alberton <l.alberton@quipo.it> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version CVS: $Id: MDB.php,v 1.2 2006-12-14 15:04:28 jp_milcent Exp $ |
* @link http://pear.php.net/package/Auth |
* @since File available since Release 1.2.3 |
*/ |
/** |
* Include Auth_Container base class |
*/ |
require_once 'Auth/Container.php'; |
/** |
* Include PEAR MDB package |
*/ |
require_once 'MDB.php'; |
/** |
* Storage driver for fetching login data from a database |
* |
* This storage driver can use all databases which are supported |
* by the PEAR MDB abstraction layer to fetch login data. |
* |
* @category Authentication |
* @package Auth |
* @author Lorenzo Alberton <l.alberton@quipo.it> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version Release: 1.4.3 File: $Revision: 1.2 $ |
* @link http://pear.php.net/package/Auth |
* @since Class available since Release 1.2.3 |
*/ |
class Auth_Container_MDB extends Auth_Container |
{ |
// {{{ properties |
/** |
* Additional options for the storage container |
* @var array |
*/ |
var $options = array(); |
/** |
* MDB object |
* @var object |
*/ |
var $db = null; |
var $dsn = ''; |
/** |
* User that is currently selected from the DB. |
* @var string |
*/ |
var $activeUser = ''; |
// }}} |
// {{{ Auth_Container_MDB() [constructor] |
/** |
* Constructor of the container class |
* |
* Initate connection to the database via PEAR::MDB |
* |
* @param string Connection data or MDB object |
* @return object Returns an error object if something went wrong |
*/ |
function Auth_Container_MDB($dsn) |
{ |
$this->_setDefaults(); |
if (is_array($dsn)) { |
$this->_parseOptions($dsn); |
if (empty($this->options['dsn'])) { |
PEAR::raiseError('No connection parameters specified!'); |
} |
} else { |
$this->options['dsn'] = $dsn; |
} |
} |
// }}} |
// {{{ _connect() |
/** |
* Connect to database by using the given DSN string |
* |
* @access private |
* @param mixed DSN string | array | mdb object |
* @return mixed Object on error, otherwise bool |
*/ |
function _connect($dsn) |
{ |
if (is_string($dsn) || is_array($dsn)) { |
$this->db =& MDB::connect($dsn, $this->options['db_options']); |
} elseif (is_subclass_of($dsn, 'mdb_common')) { |
$this->db = $dsn; |
} elseif (is_object($dsn) && MDB::isError($dsn)) { |
return PEAR::raiseError($dsn->getMessage(), $dsn->code); |
} else { |
return PEAR::raiseError('The given dsn was not valid in file ' . __FILE__ . ' at line ' . __LINE__, |
41, |
PEAR_ERROR_RETURN, |
null, |
null |
); |
} |
if (MDB::isError($this->db) || PEAR::isError($this->db)) { |
return PEAR::raiseError($this->db->getMessage(), $this->db->code); |
} |
if ($this->options['auto_quote']) { |
$this->options['final_table'] = $this->db->quoteIdentifier($this->options['table']); |
$this->options['final_usernamecol'] = $this->db->quoteIdentifier($this->options['usernamecol']); |
$this->options['final_passwordcol'] = $this->db->quoteIdentifier($this->options['passwordcol']); |
} else { |
$this->options['final_table'] = $this->options['table']; |
$this->options['final_usernamecol'] = $this->options['usernamecol']; |
$this->options['final_passwordcol'] = $this->options['passwordcol']; |
} |
return true; |
} |
// }}} |
// {{{ _prepare() |
/** |
* Prepare database connection |
* |
* This function checks if we have already opened a connection to |
* the database. If that's not the case, a new connection is opened. |
* |
* @access private |
* @return mixed True or a MDB error object. |
*/ |
function _prepare() |
{ |
if (is_subclass_of($this->db, 'mdb_common')) { |
return true; |
} |
return $this->_connect($this->options['dsn']); |
} |
// }}} |
// {{{ query() |
/** |
* Prepare query to the database |
* |
* This function checks if we have already opened a connection to |
* the database. If that's not the case, a new connection is opened. |
* After that the query is passed to the database. |
* |
* @access public |
* @param string Query string |
* @return mixed a MDB_result object or MDB_OK on success, a MDB |
* or PEAR error on failure |
*/ |
function query($query) |
{ |
$err = $this->_prepare(); |
if ($err !== true) { |
return $err; |
} |
return $this->db->query($query); |
} |
// }}} |
// {{{ _setDefaults() |
/** |
* Set some default options |
* |
* @access private |
* @return void |
*/ |
function _setDefaults() |
{ |
$this->options['table'] = 'auth'; |
$this->options['usernamecol'] = 'username'; |
$this->options['passwordcol'] = 'password'; |
$this->options['dsn'] = ''; |
$this->options['db_fields'] = ''; |
$this->options['cryptType'] = 'md5'; |
$this->options['db_options'] = array(); |
$this->options['auto_quote'] = true; |
} |
// }}} |
// {{{ _parseOptions() |
/** |
* Parse options passed to the container class |
* |
* @access private |
* @param array |
*/ |
function _parseOptions($array) |
{ |
foreach ($array as $key => $value) { |
if (isset($this->options[$key])) { |
$this->options[$key] = $value; |
} |
} |
} |
// }}} |
// {{{ _quoteDBFields() |
/** |
* Quote the db_fields option to avoid the possibility of SQL injection. |
* |
* @access private |
* @return string A properly quoted string that can be concatenated into a |
* SELECT clause. |
*/ |
function _quoteDBFields() |
{ |
if (isset($this->options['db_fields'])) { |
if (is_array($this->options['db_fields'])) { |
if ($this->options['auto_quote']) { |
$fields = array(); |
foreach ($this->options['db_fields'] as $field) { |
$fields[] = $this->db->quoteIdentifier($field); |
} |
return implode(', ', $fields); |
} else { |
return implode(', ', $this->options['db_fields']); |
} |
} else { |
if (strlen($this->options['db_fields']) > 0) { |
if ($this->options['auto_quote']) { |
return $this->db->quoteIdentifier($this->options['db_fields']); |
} else { |
return $this->options['db_fields']; |
} |
} |
} |
} |
return ''; |
} |
// }}} |
// {{{ fetchData() |
/** |
* Get user information from database |
* |
* This function uses the given username to fetch |
* the corresponding login data from the database |
* table. If an account that matches the passed username |
* and password is found, the function returns true. |
* Otherwise it returns false. |
* |
* @param string Username |
* @param string Password |
* @param boolean If true password is secured using a md5 hash |
* the frontend and auth are responsible for making sure the container supports |
* challenge response password authentication |
* @return mixed Error object or boolean |
*/ |
function fetchData($username, $password, $isChallengeResponse=false) |
{ |
// Prepare for a database query |
$err = $this->_prepare(); |
if ($err !== true) { |
return PEAR::raiseError($err->getMessage(), $err->getCode()); |
} |
//Check if db_fields contains a *, if so assume all columns are selected |
if (is_string($this->options['db_fields']) |
&& strstr($this->options['db_fields'], '*')) { |
$sql_from = '*'; |
} else { |
$sql_from = $this->options['final_usernamecol']. |
", ".$this->options['final_passwordcol']; |
if (strlen($fields = $this->_quoteDBFields()) > 0) { |
$sql_from .= ', '.$fields; |
} |
} |
$query = sprintf("SELECT %s FROM %s WHERE %s = %s", |
$sql_from, |
$this->options['final_table'], |
$this->options['final_usernamecol'], |
$this->db->getTextValue($username) |
); |
$res = $this->db->getRow($query, null, null, null, MDB_FETCHMODE_ASSOC); |
if (MDB::isError($res) || PEAR::isError($res)) { |
return PEAR::raiseError($res->getMessage(), $res->getCode()); |
} |
if (!is_array($res)) { |
$this->activeUser = ''; |
return false; |
} |
// Perform trimming here before the hashing |
$password = trim($password, "\r\n"); |
$res[$this->options['passwordcol']] = trim($res[$this->options['passwordcol']], "\r\n"); |
// If using Challenge Response md5 the pass with the secret |
if ($isChallengeResponse) { |
$res[$this->options['passwordcol']] = |
md5($res[$this->options['passwordcol']].$this->_auth_obj->session['loginchallenege']); |
// UGLY cannot avoid without modifying verifyPassword |
if ($this->options['cryptType'] == 'md5') { |
$res[$this->options['passwordcol']] = md5($res[$this->options['passwordcol']]); |
} |
} |
if ($this->verifyPassword($password, |
$res[$this->options['passwordcol']], |
$this->options['cryptType'])) { |
// Store additional field values in the session |
foreach ($res as $key => $value) { |
if ($key == $this->options['passwordcol'] || |
$key == $this->options['usernamecol']) { |
continue; |
} |
// Use reference to the auth object if exists |
// This is because the auth session variable can change so a static |
// call to setAuthData does not make sense |
$this->_auth_obj->setAuthData($key, $value); |
} |
return true; |
} |
$this->activeUser = $res[$this->options['usernamecol']]; |
return false; |
} |
// }}} |
// {{{ listUsers() |
/** |
* Returns a list of users from the container |
* |
* @return mixed array|PEAR_Error |
* @access public |
*/ |
function listUsers() |
{ |
$err = $this->_prepare(); |
if ($err !== true) { |
return PEAR::raiseError($err->getMessage(), $err->getCode()); |
} |
$retVal = array(); |
//Check if db_fields contains a *, if so assume all columns are selected |
if ( is_string($this->options['db_fields']) |
&& strstr($this->options['db_fields'], '*')) { |
$sql_from = '*'; |
} else { |
$sql_from = $this->options['final_usernamecol'] |
.', '.$this->options['final_passwordcol']; |
if (strlen($fields = $this->_quoteDBFields()) > 0) { |
$sql_from .= ', '.$fields; |
} |
} |
$query = sprintf('SELECT %s FROM %s', |
$sql_from, |
$this->options['final_table'] |
); |
$res = $this->db->getAll($query, null, null, null, MDB_FETCHMODE_ASSOC); |
if (MDB::isError($res)) { |
return PEAR::raiseError($res->getMessage(), $res->getCode()); |
} else { |
foreach ($res as $user) { |
$user['username'] = $user[$this->options['usernamecol']]; |
$retVal[] = $user; |
} |
} |
return $retVal; |
} |
// }}} |
// {{{ addUser() |
/** |
* Add user to the storage container |
* |
* @access public |
* @param string Username |
* @param string Password |
* @param mixed Additional information that are stored in the DB |
* |
* @return mixed True on success, otherwise error object |
*/ |
function addUser($username, $password, $additional = "") |
{ |
$err = $this->_prepare(); |
if ($err !== true) { |
return PEAR::raiseError($err->getMessage(), $err->getCode()); |
} |
if (isset($this->options['cryptType']) && $this->options['cryptType'] == 'none') { |
$cryptFunction = 'strval'; |
} elseif (isset($this->options['cryptType']) && function_exists($this->options['cryptType'])) { |
$cryptFunction = $this->options['cryptType']; |
} else { |
$cryptFunction = 'md5'; |
} |
$password = $cryptFunction($password); |
$additional_key = ''; |
$additional_value = ''; |
if (is_array($additional)) { |
foreach ($additional as $key => $value) { |
if ($this->options['auto_quote']) { |
$additional_key .= ', ' . $this->db->quoteIdentifier($key); |
} else { |
$additional_key .= ', ' . $key; |
} |
$additional_value .= ', ' . $this->db->getTextValue($value); |
} |
} |
$query = sprintf("INSERT INTO %s (%s, %s%s) VALUES (%s, %s%s)", |
$this->options['final_table'], |
$this->options['final_usernamecol'], |
$this->options['final_passwordcol'], |
$additional_key, |
$this->db->getTextValue($username), |
$this->db->getTextValue($password), |
$additional_value |
); |
$res = $this->query($query); |
if (MDB::isError($res)) { |
return PEAR::raiseError($res->getMessage(), $res->code); |
} |
return true; |
} |
// }}} |
// {{{ removeUser() |
/** |
* Remove user from the storage container |
* |
* @access public |
* @param string Username |
* |
* @return mixed True on success, otherwise error object |
*/ |
function removeUser($username) |
{ |
$err = $this->_prepare(); |
if ($err !== true) { |
return PEAR::raiseError($err->getMessage(), $err->getCode()); |
} |
$query = sprintf("DELETE FROM %s WHERE %s = %s", |
$this->options['final_table'], |
$this->options['final_usernamecol'], |
$this->db->getTextValue($username) |
); |
$res = $this->query($query); |
if (MDB::isError($res)) { |
return PEAR::raiseError($res->getMessage(), $res->code); |
} |
return true; |
} |
// }}} |
// {{{ changePassword() |
/** |
* Change password for user in the storage container |
* |
* @param string Username |
* @param string The new password (plain text) |
*/ |
function changePassword($username, $password) |
{ |
$err = $this->_prepare(); |
if ($err !== true) { |
return PEAR::raiseError($err->getMessage(), $err->getCode()); |
} |
if (isset($this->options['cryptType']) && $this->options['cryptType'] == 'none') { |
$cryptFunction = 'strval'; |
} elseif (isset($this->options['cryptType']) && function_exists($this->options['cryptType'])) { |
$cryptFunction = $this->options['cryptType']; |
} else { |
$cryptFunction = 'md5'; |
} |
$password = $cryptFunction($password); |
$query = sprintf("UPDATE %s SET %s = %s WHERE %s = %s", |
$this->options['final_table'], |
$this->options['final_passwordcol'], |
$this->db->getTextValue($password), |
$this->options['final_usernamecol'], |
$this->db->getTextValue($username) |
); |
$res = $this->query($query); |
if (MDB::isError($res)) { |
return PEAR::raiseError($res->getMessage(), $res->code); |
} |
return true; |
} |
// }}} |
// {{{ supportsChallengeResponse() |
/** |
* Determine if this container supports |
* password authentication with challenge response |
* |
* @return bool |
* @access public |
*/ |
function supportsChallengeResponse() |
{ |
return in_array($this->options['cryptType'], array('md5', 'none', '')); |
} |
// }}} |
// {{{ getCryptType() |
/** |
* Returns the selected crypt type for this container |
* |
* @return string Function used to crypt the password |
*/ |
function getCryptType() |
{ |
return $this->options['cryptType']; |
} |
// }}} |
} |
?> |
/branches/livraison_narmer/api/pear/Auth/Container/SOAP.php |
---|
New file |
0,0 → 1,228 |
<?php |
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */ |
/** |
* Storage driver for use against a SOAP service |
* |
* PHP versions 4 and 5 |
* |
* LICENSE: This source file is subject to version 3.01 of the PHP license |
* that is available through the world-wide-web at the following URI: |
* http://www.php.net/license/3_01.txt. If you did not receive a copy of |
* the PHP License and are unable to obtain it through the web, please |
* send a note to license@php.net so we can mail you a copy immediately. |
* |
* @category Authentication |
* @package Auth |
* @author Bruno Pedro <bpedro@co.sapo.pt> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version CVS: $Id: SOAP.php,v 1.2 2006-12-14 15:04:28 jp_milcent Exp $ |
* @link http://pear.php.net/package/Auth |
* @since File available since Release 1.2.0 |
*/ |
/** |
* Include Auth_Container base class |
*/ |
require_once "Auth/Container.php"; |
/** |
* Include PEAR package for error handling |
*/ |
require_once "PEAR.php"; |
/** |
* Include PEAR SOAP_Client |
*/ |
require_once 'SOAP/Client.php'; |
/** |
* Storage driver for fetching login data from SOAP |
* |
* This class takes one parameter (options), where |
* you specify the following fields: endpoint, namespace, |
* method, encoding, usernamefield and passwordfield. |
* |
* You can use specify features of your SOAP service |
* by providing its parameters in an associative manner by |
* using the '_features' array through the options parameter. |
* |
* The 'matchpassword' option should be set to false if your |
* webservice doesn't return (username,password) pairs, but |
* instead returns error when the login is invalid. |
* |
* Example usage: |
* |
* <?php |
* |
* ... |
* |
* $options = array ( |
* 'endpoint' => 'http://your.soap.service/endpoint', |
* 'namespace' => 'urn:/Your/Namespace', |
* 'method' => 'get', |
* 'encoding' => 'UTF-8', |
* 'usernamefield' => 'login', |
* 'passwordfield' => 'password', |
* 'matchpasswords' => false, |
* '_features' => array ( |
* 'example_feature' => 'example_value', |
* 'another_example' => '' |
* ) |
* ); |
* $auth = new Auth('SOAP', $options, 'loginFunction'); |
* $auth->start(); |
* |
* ... |
* |
* ?> |
* |
* @category Authentication |
* @package Auth |
* @author Bruno Pedro <bpedro@co.sapo.pt> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version Release: 1.4.3 File: $Revision: 1.2 $ |
* @link http://pear.php.net/package/Auth |
* @since Class available since Release 1.2.0 |
*/ |
class Auth_Container_SOAP extends Auth_Container |
{ |
// {{{ properties |
/** |
* Required options for the class |
* @var array |
* @access private |
*/ |
var $_requiredOptions = array( |
'endpoint', |
'namespace', |
'method', |
'encoding', |
'usernamefield', |
'passwordfield', |
); |
/** |
* Options for the class |
* @var array |
* @access private |
*/ |
var $_options = array(); |
/** |
* Optional SOAP features |
* @var array |
* @access private |
*/ |
var $_features = array(); |
/** |
* The SOAP response |
* @var array |
* @access public |
*/ |
var $soapResponse = array(); |
/** |
* The SOAP client |
* @var mixed |
* @access public |
*/ |
var $soapClient = null; |
// }}} |
// {{{ Auth_Container_SOAP() [constructor] |
/** |
* Constructor of the container class |
* |
* @param $options, associative array with endpoint, namespace, method, |
* usernamefield, passwordfield and optional features |
*/ |
function Auth_Container_SOAP($options) |
{ |
$this->_options = $options; |
if (!isset($this->_options['matchpasswords'])) { |
$this->_options['matchpasswords'] = true; |
} |
if (!empty($this->_options['_features'])) { |
$this->_features = $this->_options['_features']; |
unset($this->_options['_features']); |
} |
} |
// }}} |
// {{{ fetchData() |
/** |
* Fetch data from SOAP service |
* |
* Requests the SOAP service for the given username/password |
* combination. |
* |
* @param string Username |
* @param string Password |
* @return mixed Returns the SOAP response or false if something went wrong |
*/ |
function fetchData($username, $password) |
{ |
// check if all required options are set |
if (array_intersect($this->_requiredOptions, array_keys($this->_options)) != $this->_requiredOptions) { |
return false; |
} else { |
// create a SOAP client and set encoding |
$this->soapClient = new SOAP_Client($this->_options['endpoint']); |
$this->soapClient->setEncoding($this->_options['encoding']); |
} |
// set the trace option if requested |
if (isset($this->_options['trace'])) { |
$this->soapClient->__options['trace'] = true; |
} |
// set the timeout option if requested |
if (isset($this->_options['timeout'])) { |
$this->soapClient->__options['timeout'] = $this->_options['timeout']; |
} |
// assign username and password fields |
$usernameField = new SOAP_Value($this->_options['usernamefield'],'string', $username); |
$passwordField = new SOAP_Value($this->_options['passwordfield'],'string', $password); |
$SOAPParams = array($usernameField, $passwordField); |
// assign optional features |
foreach ($this->_features as $fieldName => $fieldValue) { |
$SOAPParams[] = new SOAP_Value($fieldName, 'string', $fieldValue); |
} |
// make SOAP call |
$this->soapResponse = $this->soapClient->call( |
$this->_options['method'], |
$SOAPParams, |
array('namespace' => $this->_options['namespace']) |
); |
if (!PEAR::isError($this->soapResponse)) { |
if ($this->_options['matchpasswords']) { |
// check if passwords match |
if ($password == $this->soapResponse->{$this->_options['passwordfield']}) { |
return true; |
} else { |
return false; |
} |
} else { |
return true; |
} |
} else { |
return false; |
} |
} |
// }}} |
} |
?> |
/branches/livraison_narmer/api/pear/Auth/Container/DBLite.php |
---|
New file |
0,0 → 1,298 |
<?php |
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */ |
/** |
* Reduced storage driver for use against PEAR DB |
* |
* PHP versions 4 and 5 |
* |
* LICENSE: This source file is subject to version 3.01 of the PHP license |
* that is available through the world-wide-web at the following URI: |
* http://www.php.net/license/3_01.txt. If you did not receive a copy of |
* the PHP License and are unable to obtain it through the web, please |
* send a note to license@php.net so we can mail you a copy immediately. |
* |
* @category Authentication |
* @package Auth |
* @author Martin Jansen <mj@php.net> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version CVS: $Id: DBLite.php,v 1.1 2006-12-14 15:04:28 jp_milcent Exp $ |
* @link http://pear.php.net/package/Auth |
* @since File available since Release 1.3.0 |
*/ |
/** |
* Include Auth_Container base class |
*/ |
require_once 'Auth/Container.php'; |
/** |
* Include PEAR DB package |
*/ |
require_once 'DB.php'; |
/** |
* A lighter storage driver for fetching login data from a database |
* |
* This driver is derived from the DB storage container but |
* with the user manipulation function removed for smaller file size |
* by the PEAR DB abstraction layer to fetch login data. |
* |
* @category Authentication |
* @package Auth |
* @author Martin Jansen <mj@php.net> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version Release: 1.4.3 File: $Revision: 1.1 $ |
* @link http://pear.php.net/package/Auth |
* @since Class available since Release 1.3.0 |
*/ |
class Auth_Container_DBLite extends Auth_Container |
{ |
// {{{ properties |
/** |
* Additional options for the storage container |
* @var array |
*/ |
var $options = array(); |
/** |
* DB object |
* @var object |
*/ |
var $db = null; |
var $dsn = ''; |
/** |
* User that is currently selected from the DB. |
* @var string |
*/ |
var $activeUser = ''; |
// }}} |
// {{{ Auth_Container_DBLite() [constructor] |
/** |
* Constructor of the container class |
* |
* Initate connection to the database via PEAR::DB |
* |
* @param string Connection data or DB object |
* @return object Returns an error object if something went wrong |
*/ |
function Auth_Container_DBLite($dsn) |
{ |
$this->options['table'] = 'auth'; |
$this->options['usernamecol'] = 'username'; |
$this->options['passwordcol'] = 'password'; |
$this->options['dsn'] = ''; |
$this->options['db_fields'] = ''; |
$this->options['cryptType'] = 'md5'; |
$this->options['db_options'] = array(); |
$this->options['auto_quote'] = true; |
if (is_array($dsn)) { |
$this->_parseOptions($dsn); |
if (empty($this->options['dsn'])) { |
PEAR::raiseError('No connection parameters specified!'); |
} |
} else { |
$this->options['dsn'] = $dsn; |
} |
} |
// }}} |
// {{{ _connect() |
/** |
* Connect to database by using the given DSN string |
* |
* @access private |
* @param string DSN string |
* @return mixed Object on error, otherwise bool |
*/ |
function _connect(&$dsn) |
{ |
if (is_string($dsn) || is_array($dsn)) { |
$this->db =& DB::connect($dsn, $this->options['db_options']); |
} elseif (is_subclass_of($dsn, "db_common")) { |
$this->db =& $dsn; |
} else { |
return PEAR::raiseError("Invalid dsn or db object given"); |
} |
if (DB::isError($this->db) || PEAR::isError($this->db)) { |
return PEAR::raiseError($this->db->getMessage(), $this->db->getCode()); |
} else { |
return true; |
} |
} |
// }}} |
// {{{ _prepare() |
/** |
* Prepare database connection |
* |
* This function checks if we have already opened a connection to |
* the database. If that's not the case, a new connection is opened. |
* |
* @access private |
* @return mixed True or a DB error object. |
*/ |
function _prepare() |
{ |
if (!DB::isConnection($this->db)) { |
$res = $this->_connect($this->options['dsn']); |
if (DB::isError($res) || PEAR::isError($res)) { |
return $res; |
} |
} |
if ($this->options['auto_quote'] && $this->db->dsn['phptype'] != 'sqlite') { |
$this->options['final_table'] = $this->db->quoteIdentifier($this->options['table']); |
$this->options['final_usernamecol'] = $this->db->quoteIdentifier($this->options['usernamecol']); |
$this->options['final_passwordcol'] = $this->db->quoteIdentifier($this->options['passwordcol']); |
} else { |
$this->options['final_table'] = $this->options['table']; |
$this->options['final_usernamecol'] = $this->options['usernamecol']; |
$this->options['final_passwordcol'] = $this->options['passwordcol']; |
} |
return true; |
} |
// }}} |
// {{{ _parseOptions() |
/** |
* Parse options passed to the container class |
* |
* @access private |
* @param array |
*/ |
function _parseOptions($array) |
{ |
foreach ($array as $key => $value) { |
if (isset($this->options[$key])) { |
$this->options[$key] = $value; |
} |
} |
} |
// }}} |
// {{{ _quoteDBFields() |
/** |
* Quote the db_fields option to avoid the possibility of SQL injection. |
* |
* @access private |
* @return string A properly quoted string that can be concatenated into a |
* SELECT clause. |
*/ |
function _quoteDBFields() |
{ |
if (isset($this->options['db_fields'])) { |
if (is_array($this->options['db_fields'])) { |
if ($this->options['auto_quote']) { |
$fields = array(); |
foreach ($this->options['db_fields'] as $field) { |
$fields[] = $this->db->quoteIdentifier($field); |
} |
return implode(', ', $fields); |
} else { |
return implode(', ', $this->options['db_fields']); |
} |
} else { |
if (strlen($this->options['db_fields']) > 0) { |
if ($this->options['auto_quote']) { |
return $this->db->quoteIdentifier($this->options['db_fields']); |
} else { |
$this->options['db_fields']; |
} |
} |
} |
} |
return ''; |
} |
// }}} |
// {{{ fetchData() |
/** |
* Get user information from database |
* |
* This function uses the given username to fetch |
* the corresponding login data from the database |
* table. If an account that matches the passed username |
* and password is found, the function returns true. |
* Otherwise it returns false. |
* |
* @param string Username |
* @param string Password |
* @return mixed Error object or boolean |
*/ |
function fetchData($username, $password) |
{ |
// Prepare for a database query |
$err = $this->_prepare(); |
if ($err !== true) { |
return PEAR::raiseError($err->getMessage(), $err->getCode()); |
} |
// Find if db_fields contains a *, if so assume all col are selected |
if (is_string($this->options['db_fields']) |
&& strstr($this->options['db_fields'], '*')) { |
$sql_from = "*"; |
} else { |
$sql_from = $this->options['final_usernamecol']. |
", ".$this->options['final_passwordcol']; |
if (strlen($fields = $this->_quoteDBFields()) > 0) { |
$sql_from .= ', '.$fields; |
} |
} |
$query = "SELECT ".$sql_from. |
" FROM ".$this->options['final_table']. |
" WHERE ".$this->options['final_usernamecol']." = ".$this->db->quoteSmart($username); |
$res = $this->db->getRow($query, null, DB_FETCHMODE_ASSOC); |
if (DB::isError($res)) { |
return PEAR::raiseError($res->getMessage(), $res->getCode()); |
} |
if (!is_array($res)) { |
$this->activeUser = ''; |
return false; |
} |
if ($this->verifyPassword(trim($password, "\r\n"), |
trim($res[$this->options['passwordcol']], "\r\n"), |
$this->options['cryptType'])) { |
// Store additional field values in the session |
foreach ($res as $key => $value) { |
if ($key == $this->options['passwordcol'] || |
$key == $this->options['usernamecol']) { |
continue; |
} |
// Use reference to the auth object if exists |
// This is because the auth session variable can change so a static call to setAuthData does not make sence |
if (is_object($this->_auth_obj)) { |
$this->_auth_obj->setAuthData($key, $value); |
} else { |
Auth::setAuthData($key, $value); |
} |
} |
$this->activeUser = $res[$this->options['usernamecol']]; |
return true; |
} |
$this->activeUser = $res[$this->options['usernamecol']]; |
return false; |
} |
// }}} |
} |
?> |
/branches/livraison_narmer/api/pear/Auth/Container/SMBPasswd.php |
---|
New file |
0,0 → 1,177 |
<?php |
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */ |
/** |
* Storage driver for use against Samba password files |
* |
* PHP versions 4 and 5 |
* |
* LICENSE: This source file is subject to version 3.01 of the PHP license |
* that is available through the world-wide-web at the following URI: |
* http://www.php.net/license/3_01.txt. If you did not receive a copy of |
* the PHP License and are unable to obtain it through the web, please |
* send a note to license@php.net so we can mail you a copy immediately. |
* |
* @category Authentication |
* @package Auth |
* @author Michael Bretterklieber <michael@bretterklieber.com> |
* @author Adam Ashley <aashley@php.net> |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version CVS: $Id: SMBPasswd.php,v 1.2 2006-12-14 15:04:28 jp_milcent Exp $ |
* @link http://pear.php.net/package/Auth |
* @since File available since Release 1.2.3 |
*/ |
/** |
* Include PEAR File_SMBPasswd |
*/ |
require_once "File/SMBPasswd.php"; |
/** |
* Include Auth_Container Base file |
*/ |
require_once "Auth/Container.php"; |
/** |
* Include PEAR class for error handling |
*/ |
require_once "PEAR.php"; |
/** |
* Storage driver for fetching login data from an SAMBA smbpasswd file. |
* |
* This storage container can handle SAMBA smbpasswd files. |
* |
* Example: |
* $a = new Auth("SMBPasswd", '/usr/local/private/smbpasswd'); |
* $a->start(); |
* if ($a->getAuth()) { |
* printf ("AUTH OK<br>\n"); |
* $a->logout(); |
* } |
* |
* @category Authentication |
* @package Auth |
* @author Michael Bretterklieber <michael@bretterklieber.com> |
* @author Adam Ashley <aashley@php.net> |
* @package Auth |
* @copyright 2001-2006 The PHP Group |
* @license http://www.php.net/license/3_01.txt PHP License 3.01 |
* @version Release: 1.4.3 File: $Revision: 1.2 $ |
* @link http://pear.php.net/package/Auth |
* @since Class available since Release 1.2.3 |
*/ |
class Auth_Container_SMBPasswd extends Auth_Container |
{ |
// {{{ properties |
/** |
* File_SMBPasswd object |
* @var object |
*/ |
var $pwfile; |
// }}} |
// {{{ Auth_Container_SMBPasswd() [constructor] |
/** |
* Constructor of the container class |
* |
* @param $filename string filename for a passwd type file |
* @return object Returns an error object if something went wrong |
*/ |
function Auth_Container_SMBPasswd($filename) |
{ |
$this->pwfile = new File_SMBPasswd($filename,0); |
if (!$this->pwfile->load()) { |
PEAR::raiseError("Error while reading file contents.", 41, PEAR_ERROR_DIE); |
return; |
} |
} |
// }}} |
// {{{ fetchData() |
/** |
* Get user information from pwfile |
* |
* @param string Username |
* @param string Password |
* @return boolean |
*/ |
function fetchData($username, $password) |
{ |
return $this->pwfile->verifyAccount($username, $password); |
} |
// }}} |
// {{{ listUsers() |
function listUsers() |
{ |
return $this->pwfile->getAccounts(); |
} |
// }}} |
// {{{ addUser() |
/** |
* Add a new user to the storage container |
* |
* @param string Username |
* @param string Password |
* @param array Additional information |
* |
* @return boolean |
*/ |
function addUser($username, $password, $additional = '') |
{ |
$res = $this->pwfile->addUser($user, $additional['userid'], $pass); |
if ($res === true) { |
return $this->pwfile->save(); |
} |
return $res; |
} |
// }}} |
// {{{ removeUser() |
/** |
* Remove user from the storage container |
* |
* @param string Username |
*/ |
function removeUser($username) |
{ |
$res = $this->pwfile->delUser($username); |
if ($res === true) { |
return $this->pwfile->save(); |
} |
return $res; |
} |
// }}} |
// {{{ changePassword() |
/** |
* Change password for user in the storage container |
* |
* @param string Username |
* @param string The new password |
*/ |
function changePassword($username, $password) |
{ |
$res = $this->pwfile->modUser($username, '', $password); |
if ($res === true) { |
return $this->pwfile->save(); |
} |
return $res; |
} |
// }}} |
} |
?> |
/branches/livraison_narmer/api/pear/Auth/SASL/DigestMD5.php |
---|
New file |
0,0 → 1,194 |
<?php |
// +-----------------------------------------------------------------------+ |
// | Copyright (c) 2002-2003 Richard Heyes | |
// | All rights reserved. | |
// | | |
// | Redistribution and use in source and binary forms, with or without | |
// | modification, are permitted provided that the following conditions | |
// | are met: | |
// | | |
// | o Redistributions of source code must retain the above copyright | |
// | notice, this list of conditions and the following disclaimer. | |
// | o Redistributions in binary form must reproduce the above copyright | |
// | notice, this list of conditions and the following disclaimer in the | |
// | documentation and/or other materials provided with the distribution.| |
// | o The names of the authors may not be used to endorse or promote | |
// | products derived from this software without specific prior written | |
// | permission. | |
// | | |
// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | |
// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | |
// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | |
// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | |
// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | |
// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | |
// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | |
// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | |
// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | |
// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
// | | |
// +-----------------------------------------------------------------------+ |
// | Author: Richard Heyes <richard@php.net> | |
// +-----------------------------------------------------------------------+ |
// |
// $Id: DigestMD5.php,v 1.1 2006-12-14 15:04:29 jp_milcent Exp $ |
/** |
* Implmentation of DIGEST-MD5 SASL mechanism |
* |
* @author Richard Heyes <richard@php.net> |
* @access public |
* @version 1.0 |
* @package Auth_SASL |
*/ |
require_once('Auth/SASL/Common.php'); |
class Auth_SASL_DigestMD5 extends Auth_SASL_Common |
{ |
/** |
* Provides the (main) client response for DIGEST-MD5 |
* requires a few extra parameters than the other |
* mechanisms, which are unavoidable. |
* |
* @param string $authcid Authentication id (username) |
* @param string $pass Password |
* @param string $challenge The digest challenge sent by the server |
* @param string $hostname The hostname of the machine you're connecting to |
* @param string $service The servicename (eg. imap, pop, acap etc) |
* @param string $authzid Authorization id (username to proxy as) |
* @return string The digest response (NOT base64 encoded) |
* @access public |
*/ |
function getResponse($authcid, $pass, $challenge, $hostname, $service, $authzid = '') |
{ |
$challenge = $this->_parseChallenge($challenge); |
$authzid_string = ''; |
if ($authzid != '') { |
$authzid_string = ',authzid="' . $authzid . '"'; |
} |
if (!empty($challenge)) { |
$cnonce = $this->_getCnonce(); |
$digest_uri = sprintf('%s/%s', $service, $hostname); |
$response_value = $this->_getResponseValue($authcid, $pass, $challenge['realm'], $challenge['nonce'], $cnonce, $digest_uri, $authzid); |
return sprintf('username="%s",realm="%s"' . $authzid_string . ',nonce="%s",cnonce="%s",nc="00000001",qop=auth,digest-uri="%s",response=%s,%d', $authcid, $challenge['realm'], $challenge['nonce'], $cnonce, $digest_uri, $response_value, $challenge['maxbuf']); |
} else { |
return PEAR::raiseError('Invalid digest challenge'); |
} |
} |
/** |
* Parses and verifies the digest challenge* |
* |
* @param string $challenge The digest challenge |
* @return array The parsed challenge as an assoc |
* array in the form "directive => value". |
* @access private |
*/ |
function _parseChallenge($challenge) |
{ |
$tokens = array(); |
while (preg_match('/^([a-z-]+)=("[^"]+(?<!\\\)"|[^,]+)/i', $challenge, $matches)) { |
// Ignore these as per rfc2831 |
if ($matches[1] == 'opaque' OR $matches[1] == 'domain') { |
$challenge = substr($challenge, strlen($matches[0]) + 1); |
continue; |
} |
// Allowed multiple "realm" and "auth-param" |
if (!empty($tokens[$matches[1]]) AND ($matches[1] == 'realm' OR $matches[1] == 'auth-param')) { |
if (is_array($tokens[$matches[1]])) { |
$tokens[$matches[1]][] = preg_replace('/^"(.*)"$/', '\\1', $matches[2]); |
} else { |
$tokens[$matches[1]] = array($tokens[$matches[1]], preg_replace('/^"(.*)"$/', '\\1', $matches[2])); |
} |
// Any other multiple instance = failure |
} elseif (!empty($tokens[$matches[1]])) { |
$tokens = array(); |
break; |
} else { |
$tokens[$matches[1]] = preg_replace('/^"(.*)"$/', '\\1', $matches[2]); |
} |
// Remove the just parsed directive from the challenge |
$challenge = substr($challenge, strlen($matches[0]) + 1); |
} |
/** |
* Defaults and required directives |
*/ |
// Realm |
if (empty($tokens['realm'])) { |
$uname = posix_uname(); |
$tokens['realm'] = $uname['nodename']; |
} |
// Maxbuf |
if (empty($tokens['maxbuf'])) { |
$tokens['maxbuf'] = 65536; |
} |
// Required: nonce, algorithm |
if (empty($tokens['nonce']) OR empty($tokens['algorithm'])) { |
return array(); |
} |
return $tokens; |
} |
/** |
* Creates the response= part of the digest response |
* |
* @param string $authcid Authentication id (username) |
* @param string $pass Password |
* @param string $realm Realm as provided by the server |
* @param string $nonce Nonce as provided by the server |
* @param string $cnonce Client nonce |
* @param string $digest_uri The digest-uri= value part of the response |
* @param string $authzid Authorization id |
* @return string The response= part of the digest response |
* @access private |
*/ |
function _getResponseValue($authcid, $pass, $realm, $nonce, $cnonce, $digest_uri, $authzid = '') |
{ |
if ($authzid == '') { |
$A1 = sprintf('%s:%s:%s', pack('H32', md5(sprintf('%s:%s:%s', $authcid, $realm, $pass))), $nonce, $cnonce); |
} else { |
$A1 = sprintf('%s:%s:%s:%s', pack('H32', md5(sprintf('%s:%s:%s', $authcid, $realm, $pass))), $nonce, $cnonce, $authzid); |
} |
$A2 = 'AUTHENTICATE:' . $digest_uri; |
return md5(sprintf('%s:%s:00000001:%s:auth:%s', md5($A1), $nonce, $cnonce, md5($A2))); |
} |
/** |
* Creates the client nonce for the response |
* |
* @return string The cnonce value |
* @access private |
*/ |
function _getCnonce() |
{ |
if (file_exists('/dev/urandom')) { |
return base64_encode(fread(fopen('/dev/urandom', 'r'), 32)); |
} elseif (file_exists('/dev/random')) { |
return base64_encode(fread(fopen('/dev/random', 'r'), 32)); |
} else { |
$str = ''; |
mt_srand((double)microtime()*10000000); |
for ($i=0; $i<32; $i++) { |
$str .= chr(mt_rand(0, 255)); |
} |
return base64_encode($str); |
} |
} |
} |
?> |
/branches/livraison_narmer/api/pear/Auth/SASL/Anonymous.php |
---|
New file |
0,0 → 1,71 |
<?php |
// +-----------------------------------------------------------------------+ |
// | Copyright (c) 2002-2003 Richard Heyes | |
// | All rights reserved. | |
// | | |
// | Redistribution and use in source and binary forms, with or without | |
// | modification, are permitted provided that the following conditions | |
// | are met: | |
// | | |
// | o Redistributions of source code must retain the above copyright | |
// | notice, this list of conditions and the following disclaimer. | |
// | o Redistributions in binary form must reproduce the above copyright | |
// | notice, this list of conditions and the following disclaimer in the | |
// | documentation and/or other materials provided with the distribution.| |
// | o The names of the authors may not be used to endorse or promote | |
// | products derived from this software without specific prior written | |
// | permission. | |
// | | |
// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | |
// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | |
// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | |
// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | |
// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | |
// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | |
// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | |
// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | |
// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | |
// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
// | | |
// +-----------------------------------------------------------------------+ |
// | Author: Richard Heyes <richard@php.net> | |
// +-----------------------------------------------------------------------+ |
// |
// $Id: Anonymous.php,v 1.1 2006-12-14 15:04:29 jp_milcent Exp $ |
/** |
* Implmentation of ANONYMOUS SASL mechanism |
* |
* @author Richard Heyes <richard@php.net> |
* @access public |
* @version 1.0 |
* @package Auth_SASL |
*/ |
require_once('Auth/SASL/Common.php'); |
class Auth_SASL_Anonymous extends Auth_SASL_Common |
{ |
/** |
* Not much to do here except return the token supplied. |
* No encoding, hashing or encryption takes place for this |
* mechanism, simply one of: |
* o An email address |
* o An opaque string not containing "@" that can be interpreted |
* by the sysadmin |
* o Nothing |
* |
* We could have some logic here for the second option, but this |
* would by no means create something interpretable. |
* |
* @param string $token Optional email address or string to provide |
* as trace information. |
* @return string The unaltered input token |
*/ |
function getResponse($token = '') |
{ |
return $token; |
} |
} |
?> |
/branches/livraison_narmer/api/pear/Auth/SASL/Common.php |
---|
New file |
0,0 → 1,74 |
<?php |
// +-----------------------------------------------------------------------+ |
// | Copyright (c) 2002-2003 Richard Heyes | |
// | All rights reserved. | |
// | | |
// | Redistribution and use in source and binary forms, with or without | |
// | modification, are permitted provided that the following conditions | |
// | are met: | |
// | | |
// | o Redistributions of source code must retain the above copyright | |
// | notice, this list of conditions and the following disclaimer. | |
// | o Redistributions in binary form must reproduce the above copyright | |
// | notice, this list of conditions and the following disclaimer in the | |
// | documentation and/or other materials provided with the distribution.| |
// | o The names of the authors may not be used to endorse or promote | |
// | products derived from this software without specific prior written | |
// | permission. | |
// | | |
// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | |
// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | |
// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | |
// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | |
// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | |
// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | |
// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | |
// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | |
// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | |
// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
// | | |
// +-----------------------------------------------------------------------+ |
// | Author: Richard Heyes <richard@php.net> | |
// +-----------------------------------------------------------------------+ |
// |
// $Id: Common.php,v 1.1 2006-12-14 15:04:29 jp_milcent Exp $ |
/** |
* Common functionality to SASL mechanisms |
* |
* @author Richard Heyes <richard@php.net> |
* @access public |
* @version 1.0 |
* @package Auth_SASL |
*/ |
class Auth_SASL_Common |
{ |
/** |
* Function which implements HMAC MD5 digest |
* |
* @param string $key The secret key |
* @param string $data The data to protect |
* @return string The HMAC MD5 digest |
*/ |
function _HMAC_MD5($key, $data) |
{ |
if (strlen($key) > 64) { |
$key = pack('H32', md5($key)); |
} |
if (strlen($key) < 64) { |
$key = str_pad($key, 64, chr(0)); |
} |
$k_ipad = substr($key, 0, 64) ^ str_repeat(chr(0x36), 64); |
$k_opad = substr($key, 0, 64) ^ str_repeat(chr(0x5C), 64); |
$inner = pack('H32', md5($k_ipad . $data)); |
$digest = md5($k_opad . $inner); |
return $digest; |
} |
} |
?> |
/branches/livraison_narmer/api/pear/Auth/SASL/CramMD5.php |
---|
New file |
0,0 → 1,68 |
<?php |
// +-----------------------------------------------------------------------+ |
// | Copyright (c) 2002-2003 Richard Heyes | |
// | All rights reserved. | |
// | | |
// | Redistribution and use in source and binary forms, with or without | |
// | modification, are permitted provided that the following conditions | |
// | are met: | |
// | | |
// | o Redistributions of source code must retain the above copyright | |
// | notice, this list of conditions and the following disclaimer. | |
// | o Redistributions in binary form must reproduce the above copyright | |
// | notice, this list of conditions and the following disclaimer in the | |
// | documentation and/or other materials provided with the distribution.| |
// | o The names of the authors may not be used to endorse or promote | |
// | products derived from this software without specific prior written | |
// | permission. | |
// | | |
// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | |
// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | |
// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | |
// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | |
// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | |
// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | |
// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | |
// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | |
// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | |
// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
// | | |
// +-----------------------------------------------------------------------+ |
// | Author: Richard Heyes <richard@php.net> | |
// +-----------------------------------------------------------------------+ |
// |
// $Id: CramMD5.php,v 1.1 2006-12-14 15:04:29 jp_milcent Exp $ |
/** |
* Implmentation of CRAM-MD5 SASL mechanism |
* |
* @author Richard Heyes <richard@php.net> |
* @access public |
* @version 1.0 |
* @package Auth_SASL |
*/ |
require_once('Auth/SASL/Common.php'); |
class Auth_SASL_CramMD5 extends Auth_SASL_Common |
{ |
/** |
* Implements the CRAM-MD5 SASL mechanism |
* This DOES NOT base64 encode the return value, |
* you will need to do that yourself. |
* |
* @param string $user Username |
* @param string $pass Password |
* @param string $challenge The challenge supplied by the server. |
* this should be already base64_decoded. |
* |
* @return string The string to pass back to the server, of the form |
* "<user> <digest>". This is NOT base64_encoded. |
*/ |
function getResponse($user, $pass, $challenge) |
{ |
return $user . ' ' . $this->_HMAC_MD5($pass, $challenge); |
} |
} |
?> |
/branches/livraison_narmer/api/pear/Auth/SASL/Login.php |
---|
New file |
0,0 → 1,65 |
<?php |
// +-----------------------------------------------------------------------+ |
// | Copyright (c) 2002-2003 Richard Heyes | |
// | All rights reserved. | |
// | | |
// | Redistribution and use in source and binary forms, with or without | |
// | modification, are permitted provided that the following conditions | |
// | are met: | |
// | | |
// | o Redistributions of source code must retain the above copyright | |
// | notice, this list of conditions and the following disclaimer. | |
// | o Redistributions in binary form must reproduce the above copyright | |
// | notice, this list of conditions and the following disclaimer in the | |
// | documentation and/or other materials provided with the distribution.| |
// | o The names of the authors may not be used to endorse or promote | |
// | products derived from this software without specific prior written | |
// | permission. | |
// | | |
// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | |
// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | |
// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | |
// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | |
// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | |
// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | |
// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | |
// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | |
// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | |
// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
// | | |
// +-----------------------------------------------------------------------+ |
// | Author: Richard Heyes <richard@php.net> | |
// +-----------------------------------------------------------------------+ |
// |
// $Id: Login.php,v 1.1 2006-12-14 15:04:29 jp_milcent Exp $ |
/** |
* This is technically not a SASL mechanism, however |
* it's used by Net_Sieve, Net_Cyrus and potentially |
* other protocols , so here is a good place to abstract |
* it. |
* |
* @author Richard Heyes <richard@php.net> |
* @access public |
* @version 1.0 |
* @package Auth_SASL |
*/ |
require_once('Auth/SASL/Common.php'); |
class Auth_SASL_Login extends Auth_SASL_Common |
{ |
/** |
* Pseudo SASL LOGIN mechanism |
* |
* @param string $user Username |
* @param string $pass Password |
* @return string LOGIN string |
*/ |
function getResponse($user, $pass) |
{ |
return sprintf('LOGIN %s %s', $user, $pass); |
} |
} |
?> |
/branches/livraison_narmer/api/pear/Auth/SASL/Plain.php |
---|
New file |
0,0 → 1,63 |
<?php |
// +-----------------------------------------------------------------------+ |
// | Copyright (c) 2002-2003 Richard Heyes | |
// | All rights reserved. | |
// | | |
// | Redistribution and use in source and binary forms, with or without | |
// | modification, are permitted provided that the following conditions | |
// | are met: | |
// | | |
// | o Redistributions of source code must retain the above copyright | |
// | notice, this list of conditions and the following disclaimer. | |
// | o Redistributions in binary form must reproduce the above copyright | |
// | notice, this list of conditions and the following disclaimer in the | |
// | documentation and/or other materials provided with the distribution.| |
// | o The names of the authors may not be used to endorse or promote | |
// | products derived from this software without specific prior written | |
// | permission. | |
// | | |
// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | |
// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | |
// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | |
// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | |
// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | |
// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | |
// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | |
// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | |
// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | |
// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
// | | |
// +-----------------------------------------------------------------------+ |
// | Author: Richard Heyes <richard@php.net> | |
// +-----------------------------------------------------------------------+ |
// |
// $Id: Plain.php,v 1.1 2006-12-14 15:04:29 jp_milcent Exp $ |
/** |
* Implmentation of PLAIN SASL mechanism |
* |
* @author Richard Heyes <richard@php.net> |
* @access public |
* @version 1.0 |
* @package Auth_SASL |
*/ |
require_once('Auth/SASL/Common.php'); |
class Auth_SASL_Plain extends Auth_SASL_Common |
{ |
/** |
* Returns PLAIN response |
* |
* @param string $authcid Authentication id (username) |
* @param string $pass Password |
* @param string $authzid Autorization id |
* @return string PLAIN Response |
*/ |
function getResponse($authcid, $pass, $authzid = '') |
{ |
return $authzid . chr(0) . $authcid . chr(0) . $pass; |
} |
} |
?> |