<?php

/*
 *	W-AGORA 4.1
 *	-----------
 *	$Id: http_user.php,v 1.7 2006/01/10 10:19:15 mdruilhe Exp $
 *	Usage:	HTTP Basic (apache) style authentication
 *	Author:	Marc Druilhe <mdruilhe@w-agora.net>
 */	

if (!defined('_GLOBALS')) {
	die('Hacking attempt');
}

if (!defined("_AUTH")) {
	include ("$inc_dir/auth.$ext");
}

class http_user_source extends wa_Auth {

  # -------------------------------------------------------------------------------------------
  # These methods define how to pull out the informations (profile) of the authenticated user. 
  # The getUsername and getUseraddress functions may be modified to fit to your needs.
  # -------------------------------------------------------------------------------------------

 /**
  * Return the user's name if available
  */
  function getUsername($userid) {

    return $userid;
  }

 /**
  * Return the user's email address if available
  *
  * Usually, its simply concatenate the useid with the domain name (pulled out from $ADMIN_ADDRESS)
  */
  function getUseraddress($userid) {

	if (! @empty($_SERVER['SERVER_ADMIN'])) {
		list ($user,$domain) = split('@', $_SERVER["SERVER_ADMIN"]);
	} elseif (isset($_SERVER['SERVER_NAME'])) {
		$domain = $_SERVER['SERVER_NAME'];
	} else {
		$domain = "localhost.localdomain";
	}

	return "$userid@$domain";
  }

  #
  # API methods
  #

 /**
  * Return the "edit user profile" page 
  *    => Use the default behaviour.
  */
  function getEditProfileURL() {
    return;			# use default
  }


 /**
  * Return the "forgot password?" page
  *   => disabled
  */
  function getForgotPasswordURL() {
    return "";			# disabled
  }
 

 /**
  * Return the "change password" page
  *   => disabled
  */
  function getChangePasswordURL() {
    return "";		# disabled
  }
 

 /**
  * Return the "Login" page
  */
  function getLoginURL() {
    global $ext, $site, $bn;

    return "";	# disabled	
  }


 /**
  * Return the form for registration
  *   => Use the default behaviour
  */
  function getRegisterURL() {
	return;
  }

 /**
  * Encrypt the password
  *
  * This function encrypts passwords for this user source.
  * The result is stored in a cookie (by agora) and is passed to 
  * authenticateUser() below.  The minimum behaviour would 
  * returning $password (unencrypted).
  */
  function encryptPassword($password) {
    return md5($password);
  }
 
 /**
  * Returns Login information
  *
  * This function returns the login information. The information is
  * computed from the Apache/PHP environment variables.
  * If the user has never accessed this site, s/he is automaticaly
  * registered. A random password is supplied. It is never needed
  * directly by the user himself, but carried on through the
  * Agora cookies.
  */
  function getLoginInfo () {
    global $db, $site;

	# Check that we're authentified thru apache authentication
	# REMOTE_USER should be set in any case (IIS or apache)
	# --------------------------------------------------------
	if (! isset($_SERVER['REMOTE_USER'])) {
		return false;
	}

	# Pick userid and password from PHP/apache authentication
	# assuming REMOTE_USER is set both by Apache and IIS
	# -------------------------------------------------------
	$remote_user = strip_magic_quotes($_SERVER['REMOTE_USER']);

	if (preg_match	('/\\\\/', $remote_user)) {
		// strip the domain ("NT-DOMAIN1\NT-USER" => "NT-USER")
		list($domain, $userid) = preg_split("/\\\\/", $remote_user, 2);
	} else {
		$userid = $remote_user;
	}

	if (isset($_SERVER['PHP_AUTH_PW'])) {
		# Gets the password from PHP/apache authentication
		$clearpw = $_SERVER['PHP_AUTH_PW'];
	} elseif (isset($_SERVER['AUTH_PASSWORD'])) {
		# IIS set $AUTH_PASSWORD if AUTH_TYPE is 'Basic'
		$clearpw = $_SERVER['AUTH_PASSWORD'];
	} else {
		# generate a random password
		$clearpw  = $this->genPassword();
	}

	$encryptedpw = md5($clearpw);

	# Check if this user is already registered
	# ----------------------------------------
    $userdb = $db->getUser($site, $userid);


	# No. Create this user :
	# - allocate a new random password
	# - fill the name and email address
	if (! is_array($userdb)) {
		unset($this->user);
		$userdb = array(
			"userid" => $userid,
			"password" => $encryptedpw,
			"username" => $this->getUsername($userid),
			"useraddress" => $this->getUseraddress($userid),
			"userpriv" => 'user',
			"mailok" => 'Y',
			"unixdate" => time()
		);

		if ($GLOBALS['bn_registration_mode'] == REG_ADMIN_APPROVAL) {
			$userdb["state"] = 'P';		// pending
		} else {
			$userdb["state"] = '1';		// Active
		}

		$db->insertUser($site, $userdb);
    }
      
    # return the authentication information
    return array("userid" => $userid, "clearpw" => $clearpw, "encryptedpw" => $encryptedpw);
  }
 
 /**
  * Authenticate the user
  *
  * This function retrieves the user from the source using
  * the given (encrypted) password. It must fills in the local associative array 
  * $this->user with as many of the following fields as possible:
  * 	"userid",		# login             REQUIRED
  * 	"password",		# password
  * 	"username",		# Name + firstname  REQUIRED
  * 	"name",			# User name
  * 	"firstname",	# First name
  * 	"useraddress",	# email				REQUIRED
  * 	"homepage",		# Home Page URL
  * 	"details",		# About me
  * 	"mailok"		# Is it ok to mail user?
  *
  *  @return	false if the user has never been registered 
  *				or if the supplied encrypted password does 
  *				not match the one stored in the database.
  */
  function authenticateUser($site, $userid, $encryptedpw) {
    global $db;

    # Get the information about this user
    $this->user = $db->getUser($site, $userid);

    # The user should be registered at this stage
    if (! is_array($this->user)) {
		return false;
    }

# We assume that password verification is externally done by the WEB server 
# since $REMOTE_USER is set.
# We can't verify the password here since it could have been generated randomly 
# if it's the first user login

/*
	if ($encryptedpw != $this->user["password"]) {
		unset($this->user);
		return false;
    }
*/
    return true;
  }

}; // end class
