This topic is locked

LDAP III - The questions

11/16/2006 7:10:56 AM
PHPRunner General questions
G
gdude66 author

Ok - after working with the sofa I had the following code working to authenticate LDAP in PHPR 3.0

################################################################################


LDAP AUTHENTICATION MODIFICATION #

################################################################################




//include the class

include ("ldap/adLDAP.php");
//create the LDAP connection

$adldap = new adLDAP();

$ldap_auth = 0;

$ldap_group ="usergroup"; # Specified group for group authentication
// Authenticate

if (($adldap -> authenticate($strlUsername,$strlPassword))){

if ($adldap -> user_ingroup($strlUsername,$ldap_group)){ # Group Authentication Only

$ldap_auth = 1;
// Check if user exists

$sql = "Select from ".AddTableWrappers($cLoginTable)." Where ".AddFieldWrappers($cUserNameField)." = \"$strlUsername\"";

$rs = mysql_query($sql,$conn) or die("USER QUERY FAILED.");
// Update DB for new users

if (mysql_num_rows($rs) < 1) {

$info=$adldap->user_info($strlUsername,array("givenname","sn"));

$strldapfirstname = $info[0][givenname][0]; #sets firstname value from AD

$strldaplastname = $info[0][sn][0]; #sets lastname value from AD

$sql = "INSERT INTO ".AddTableWrappers($cLoginTable)." ( ".AddFieldWrappers($cUserNameField).", firstname, lastname, level)";

$sql .= " SELECT ";

$sql .= "\"$strlUsername\" AS Expr1, "; #adds username to database

$sql .= "\"$strldapfirstname\" AS Expr2, "; #adds firstname to database

$sql .= "\"$strldaplastname\" AS Expr3, "; #adds lastname to database

$sql .= "1 AS Expr4;"; #adds level to database

$result = mysql_query($sql,$conn);

}
// Generate Query

$strSQL = "select
from ".AddTableWrappers($cLoginTable)." where ".AddFieldWrappers($cUserNameField).

"=\"".$strlUsername."\"";

} #Group Authentication Only

}
// Catch failed logins

if ($ldap_auth == 0) $strSQL = "select * from ".AddTableWrappers($cLoginTable)." where ".AddFieldWrappers($cUserNameField)."=\"xxxxx\"";
################################################################################


END OF MODIFICATION #

################################################################################



Does anyone know why this doesn't work in 3.1???

Sergey Kornilov admin 11/16/2006

Any error messages?

G
gdude66 author 11/16/2006

Any error messages?



See the following

PHP error happened
Technical information

Error type 2048

Error description var: Deprecated. Please use the public/private/protected modifiers

URL www.domain.com/login.php?

Error file F:\wwwroot\ldap\adLDAP.php

Error line 76
select * from `staff` where `username`='xxxxxxxx' and `surname`='lxxxxxxx'
As I used username field as the username and surname as the initial password

I can post the modded login.php if necessary and the original to see the difference

Sergey Kornilov admin 11/16/2006

What is the line 76 in adLDAP.php file?

G
gdude66 author 11/16/2006

What is the line 76 in adLDAP.php file?



line 75 // You will need to edit these variables to suit your installation

line 76 var $_account_suffix="@domain.local";

line 77 var $_base_dn = "DC=domain,DC=local";



line 75 // You will need to edit these variables to suit your installation

line 76 var $_account_suffix="@domain.local";

line 77 var $_base_dn = "DC=domain,DC=local";



Full file is

<?php

/*

PHP LDAP CLASS FOR MANIPULATING ACTIVE DIRECTORY

Version 1.5
Written by Scott Barnett

email: scott@wiggumworld.com

http://adldap.sourceforge.net/
Copyright © 2006 Scott Barnett
I'd appreciate any improvements or additions to be submitted back

to benefit the entire community <img src='https://asprunner.com/forums/file.php?topicimage=1&fieldname=reply&id=12923&image=1&table=forumreplies' class='bbc_emoticon' alt=':)' />
Works with both PHP 4 and PHP 5
The examples should be pretty self explanatory. If you require more

information, please visit http://adldap.sourceforge.net/
This library is free software; you can redistribute it and/or

modify it under the terms of the GNU Lesser General Public

License as published by the Free Software Foundation; either

version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,

but WITHOUT ANY WARRANTY; without even the implied warranty of

MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU

Lesser General Public License for more details.
****

Something to keep in mind is that Active Directory is a permissions

based directory. If you bind as a domain user, you can't fetch as

much information on other users as you could as a domain admin.

****
FUNCTIONS:
authenticate($username,$password)

Authenticate to the directory with a specific username and password
user_info($user,$fields=NULL)

Returns an array of information for a specific user
user_groups($user,$recursive=NULL)

Returns an array of groups that a user is a member off
user_ingroup($user,$group,$recursive=NULL)

Returns true if the user is a member of the group
group_info($group)

Returns an array of information for a specific group
all_users($include_desc = false, $search = "", $sorted = true)

Returns all AD users (expensive on resources)
all_groups($include_desc = false, $search = "
", $sorted = true)

Returns all AD groups (expensive on resources)
*/
// Different type of accounts in AD

define ('ADLDAP_NORMAL_ACCOUNT', 805306368);

define ('ADLDAP_WORKSTATION_TRUST', 805306369);

define ('ADLDAP_INTERDOMAIN_TRUST', 805306370);

define ('ADLDAP_SECURITY_GLOBAL_GROUP', 268435456);

define ('ADLDAP_DISTRIBUTION_GROUP', 268435457);

define ('ADLDAP_SECURITY_LOCAL_GROUP', 536870912);

define ('ADLDAP_DISTRIBUTION_LOCAL_GROUP', 536870913);
class adLDAP {

// BEFORE YOU ASK A QUESTION, PLEASE READ THE FAQ

// http://adldap.sourceforge.net/faq.php
// You will need to edit these variables to suit your installation

var $_account_suffix="@domain.local";

var $_base_dn = "DC=domain,DC=local";
// An array of domain controllers. Specify multiple controllers if you

// would like the class to balance the LDAP queries amongst multiple servers

var $_domain_controllers = array ("dc.domain.local");
// optional account with higher privileges for searching

var $_ad_username="account";

var $_ad_password="password";
// AD does not return the primary group. http://support.microsoft.com/?kbid=321360

// This tweak will resolve the real primary group, but may be resource intensive.

// Setting to false will fudge "Domain Users" and is much faster. Keep in mind though that if

// someone's primary group is NOT domain users, this is obviously going to bollocks the results

var $_real_primarygroup=true;
// When querying group memberships, do it recursively

// eg. User Fred is a member of Group A, which is a member of Group B, which is a member of Group C

// user_ingroup("Fred","C") will returns true with this option turned on, false if turned off

var $_recursive_groups=true;
// You should not need to edit anything below this line

//****

**
//other variables

var $_user_dn;

var $_user_pass;

var $_conn;

var $_bind;
// default constructor

function adLDAP(){

//connect to the LDAP server as the username/password

$this->_conn = ldap_connect($this->random_controller());

ldap_set_option($this->_conn, LDAP_OPT_PROTOCOL_VERSION, 3);

ldap_set_option($this->_conn, LDAP_OPT_REFERRALS, 0); //disable plain text passwords

return true;

}
// default destructor

function __destruct(){ ldap_close ($this->_conn); }
function random_controller(){

//select a random domain controller

mt_srand(doubleval(microtime()) 100000000);

return ($this->_domain_controllers[array_rand($this->_domain_controllers)]);

}
// authenticate($username,$password)

// Authenticate to the directory with a specific username and password

// Extremely useful for validating login credentials

function authenticate($username,$password){

//validate a users login credentials

$returnval=false;
if ($username!=NULL && $password!=NULL){ //prevent null bind

$this->_user_dn=$username.$this->_account_suffix;

$this->_user_pass=$password;
$this->_bind = @ldap_bind($this->_conn,$this->_user_dn,$this->_user_pass);

if ($this->_bind){ $returnval=true; }

}

return ($returnval);

}
// rebind()

// Binds to the directory with the default search username and password

// specified above.

function rebind(){

//connect with another account to search with if necessary

$ad_dn=$this->_ad_username.$this->_account_suffix;

$this->_bind = @ldap_bind($this->_conn,$ad_dn,$this->_ad_password);

if ($this->_bind){ return (true); }

return (false);

}
// user_info($user,$fields)

// Returns an array of information for a specific user

function user_info($user,$fields=NULL){

if ($user!=NULL){

if ($this->_ad_username!=NULL){ $this->rebind(); } //bind as a another account if necessary
if ($this->_bind){ //perform the search and grab all their details

$filter="samaccountname=".$user;

if ($fields==NULL){

$fields=array("samaccountname","mail","memberof","department","displayname","telephonenumber","primarygroupid");

//$fields=array("
");

}

$sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);

$entries = ldap_get_entries($this->_conn, $sr);
// AD does not return the primary group in the ldap query, we may need to fudge it

if ($this->_real_primarygroup){

$entries[0]["memberof"][]=$this->group_cn($entries[0]["primarygroupid"][0]);

} else {

$entries[0]["memberof"][]="CN=Domain Users,CN=Users,".$this->_base_dn;

}
//echo ("<pre>"); print_r($entries);
$entries[0]["memberof"]["count"]++;

return ($entries);

}

}
return (false);

}
// user_groups($user)

// Returns an array of groups that a user is a member off

function user_groups($user,$recursive=NULL){

if ($this->_ad_username!=NULL){ $this->rebind(); } //bind as a another account if necessary

if ($recursive==NULL){ $recursive=$this->_recursive_groups; }
if ($this->_bind){

//search the directory for their information

$info=@$this->user_info($user,array("memberof"));

//echo ("<pre>"); print_r($info);

$groups=$info[0]["memberof"]; //presuming the entry returned is our guy (unique usernames)
$group_array=$this->nice_names($groups);
if ($recursive){

foreach ($group_array as $id => $group_name){

$extra_groups=$this->recursive_groups($group_name);

$group_array=array_merge($group_array,$extra_groups);

}

}
return ($group_array);

}

return (false);

}
// user_ingroup($user,$group)

// Returns true if the user is a member of the group

function user_ingroup($user,$group,$recursive=NULL){

if ($recursive==NULL){ $recursive=$this->_recursive_groups; }
if (($user!=NULL) && ($group!=NULL)){

if ($this->_ad_username!=NULL){ $this->rebind(); } //bind as a another account if necessary
if ($this->_bind){

$groups=$this->user_groups($user,array("memberof"),$recursive);

if (in_array($group,$groups)){ return (true); }

}

}

return (false);

}
function recursive_groups($group){

$ret_groups=array();
$groups=$this->group_info($group,array("memberof"));

$groups=$groups[0]["memberof"];
if ($groups){

$group_names=$this->nice_names($groups);

$ret_groups=array_merge($ret_groups,$group_names); //final groups to return
foreach ($group_names as $id => $group_name){

$child_groups=$this->recursive_groups($group_name);

$ret_groups=array_merge($ret_groups,$child_groups);

}
}
return ($ret_groups);

}
// take an ldap query and return the nice names, without all the LDAP prefixes (eg. CN, DN)

function nice_names($groups){
$group_array=array();

for ($i=0; $i<$groups["count"]; $i++){ //for each group

$line=$groups[$i];
if (strlen($line)>0){

//more presumptions, they're all prefixed with CN=

//so we ditch the first three characters and the group

//name goes up to the first comma

$bits=explode(",",$line);

$group_array[]=substr($bits[0],3,(strlen($bits[0])-3));

}

}

return ($group_array);

}
function group_cn($gid){

if ($this->_ad_username!=NULL){ $this->rebind(); } //bind as a another account if necessary
// coping with AD not returning the primary group

// http://support.microsoft.com/?kbid=321360

// for some reason it's not possible to search on primarygrouptoken=XXX

// if someone can show otherwise, I'd like to know about it <img src='https://asprunner.com/forums/file.php?topicimage=1&fieldname=reply&id=12923&image=2&table=forumreplies' class='bbc_emoticon' alt=':)' />

// this way is resource intensive and generally a pain in the @#%^
$r=false;
if ($this->_bind){

$filter="(&(objectCategory=group)(samaccounttype=". ADLDAP_SECURITY_GLOBAL_GROUP ."))";

$fields=array("primarygrouptoken","samaccountname","distinguishedname");

$sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);

$entries = ldap_get_entries($this->_conn, $sr);
for ($i=0; $i<$entries["count"]; $i++){

if ($entries[$i]["primarygrouptoken"][0]==$gid){

$r=$entries[$i]["distinguishedname"][0];

$i=$entries["count"];

}

}

}

return ($r);

}
// group_info($group_name,$fields=NULL)

// Returns an array of information for a specified group

function group_info($group_name,$fields=NULL){

if ($this->_ad_username!=NULL){ $this->rebind(); } //bind as a another account if necessary
if ($this->_bind){

//escape brackets

$group_name=str_replace("(","\(",$group_name);

$group_name=str_replace(")","\)",$group_name);
$filter="(&(objectCategory=group)(name=".$group_name."))";

//echo ($filter."
");

if ($fields==NULL){ $fields=array("member","memberof","cn","description","distinguishedname","objectcategory","samaccountname"); }

$sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);

$entries = ldap_get_entries($this->_conn, $sr);

//print_r($entries);

return ($entries);

}

return (false);

}
function all_users($include_desc = false, $search = "", $sorted = true){

// Returns all AD users

if ($this->_ad_username!=NULL){ $this->rebind(); } //bind as a another account if necessary
if ($this->_bind){

$users_array = array();
//perform the search and grab all their details

$filter = "(&(objectClass=user)(samaccounttype=". ADLDAP_NORMAL_ACCOUNT .")(objectCategory=person)(cn=$search))";

$fields=array("samaccountname","displayname");

$sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);

$entries = ldap_get_entries($this->_conn, $sr);
for ($i=0; $i<$entries["count"]; $i++){

if( $include_desc && strlen($entries[$i]["displayname"][0]) > 0 )

$users_array[ $entries[$i]["samaccountname"][0] ] = $entries[$i]["displayname"][0];

else if( $include_desc )

$users_array[ $entries[$i]["samaccountname"][0] ] = $entries[$i]["samaccountname"][0];

else

array_push($users_array, $entries[$i]["samaccountname"][0]);

}

if( $sorted ){ asort($users_array); }

return ($users_array);

}

return (false);

}
function all_groups($include_desc = false, $search = "
", $sorted = true){

// Returns all AD groups

if ($this->_ad_username!=NULL){ $this->rebind(); } //bind as a another account if necessary
if ($this->_bind){

$groups_array = array();
//perform the search and grab all their details

$filter = "(&(objectCategory=group)(samaccounttype=". ADLDAP_SECURITY_GLOBAL_GROUP .")(cn=$search))";

$fields=array("samaccountname","description");

$sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);

$entries = ldap_get_entries($this->_conn, $sr);
for ($i=0; $i<$entries["count"]; $i++){

if( $include_desc && strlen($entries[$i]["description"][0]) > 0 )

$groups_array[ $entries[$i]["samaccountname"][0] ] = $entries[$i]["description"][0];

else if( $include_desc )

$groups_array[ $entries[$i]["samaccountname"][0] ] = $entries[$i]["samaccountname"][0];

else
array_push($groups_array, $entries[$i]["samaccountname"][0]);

}

if( $sorted ){ asort($groups_array); }

return ($groups_array);

}

return (false);

}

} // End class
?>



and the fully modded login.php looks like this

<?php

ini_set("display_errors","1");

ini_set("display_startup_errors","1");

set_magic_quotes_runtime(0);
include("include/dbcommon.php");
if(@$_POST["a"]=="logout" || @$_GET["a"]=="logout")

{

session_unset();

setcookie("username","",time()-365144060);

setcookie("password","",time()-365144060);

header("Location: login.php");

exit();

}

if(!@$_SESSION["MyURL"])

session_unset();
include('libs/Smarty.class.php');

$smarty = new Smarty();
$myurl=@$_SESSION["MyURL"];

unset($_SESSION["MyURL"]);
$defaulturl="";

$defaulturl="menu.php";
$strMessage="";
if(@$_COOKIE["username"] || @$_COOKIE["password"])

$smarty->assign("checked"," checked");
if (@$_POST["btnSubmit"] == "Login")

{

if(@$_POST["remember_password"] == 1)

{

setcookie("username",@$_POST["username"],time()+365144060);

setcookie("password",@$_POST["password"],time()+365144060);

$smarty->assign("checked"," checked");

}

else

{

setcookie("username","",time()-365144060);

setcookie("password","",time()-365144060);

$smarty->assign("checked","");

}

// username and password are stored in the database

$conn=db_connect();

$strlUsername = (string)@$_POST["username"];

$strlPassword = (string)@$_POST["password"];

$strUsername = (string)@$_POST["username"];

$strPassword = (string)@$_POST["password"];

$sUsername=$strlUsername;

$sPassword=$strlPassword;

$rstemp=db_query("select from `staff` where 1=0",$conn);
if(FieldNeedQuotes($rstemp,$cUserNameField))

$strUsername="'".db_addslashes($strUsername)."'";

else

$strUsername=(0+$strUsername);

if(FieldNeedQuotes($rstemp,$cPasswordField))

$strPassword="'".db_addslashes($strPassword)."'";

else

$strPassword=(0+$strPassword);

$strSQL = "select
from `staff` where ".AddFieldWrappers($cUserNameField).

"=".$strUsername." and ".AddFieldWrappers($cPasswordField).

"=".$strPassword;
################################################################################


LDAP AUTHENTICATION MODIFICATION #

################################################################################




//include the class

include ("ldap/adLDAP.php");
//create the LDAP connection

$adldap = new adLDAP();

$ldap_auth = 0;

$ldap_group ="usergroup"; # Specified group for group authentication
// Authenticate

if (($adldap -> authenticate($strlUsername,$strlPassword))){

if ($adldap -> user_ingroup($strlUsername,$ldap_group)){ # Group Authentication Only

$ldap_auth = 1;
// Check if user exists

$sql = "Select from ".AddTableWrappers($cLoginTable)." Where ".AddFieldWrappers($cUserNameField)." = \"$strlUsername\"";

$rs = mysql_query($sql,$conn) or die("USER QUERY FAILED.");
// Update DB for new users

if (mysql_num_rows($rs) < 1) {

$info=$adldap->user_info($strlUsername,array("givenname","sn"));

$strldapfirstname = $info[0][givenname][0]; #sets firstname value from AD

$strldaplastname = $info[0][sn][0]; #sets lastname value from AD

$sql = "INSERT INTO ".AddTableWrappers($cLoginTable)." ( ".AddFieldWrappers($cUserNameField).", firstname, lastname, level)";

$sql .= " SELECT ";

$sql .= "\"$strlUsername\" AS Expr1, "; #adds username to database

$sql .= "\"$strldapfirstname\" AS Expr2, "; #adds firstname to database

$sql .= "\"$strldaplastname\" AS Expr3, "; #adds lastname to database

$sql .= "1 AS Expr4;"; #adds level to database

$result = mysql_query($sql,$conn);

}
// Generate Query

$strSQL = "select
from ".AddTableWrappers($cLoginTable)." where ".AddFieldWrappers($cUserNameField).

"=\"".$strlUsername."\"";

} #Group Authentication Only

}
// Catch failed logins

if ($ldap_auth == 0) $strSQL = "select * from ".AddTableWrappers($cLoginTable)." where ".AddFieldWrappers($cUserNameField)."=\"xxxxx\"";
################################################################################


END OF MODIFICATION #

################################################################################




if(function_exists("BeforeLogin"))

if(!BeforeLogin(postvalue("username"),postvalue("password")))

$strSQL="select * from `staff` where 1<0";
$rs=db_query($strSQL,$conn);

$data=db_fetch_array($rs);

if($data && @$data[$cUserNameField]==$sUsername && @$data[$cPasswordField]==$sPassword)

{

$_SESSION["UserID"] = @$_POST["username"];

$_SESSION["AccessLevel"] = ACCESS_LEVEL_USER;

$_SESSION["OwnerID"] = $data["idstaff"];

$_SESSION["GroupID"] = $data["Access"];

if(function_exists("AfterSuccessfulLogin"))

AfterSuccessfulLogin();

if($myurl)

header("Location: ".$myurl);

else

header("Location: ".$defaulturl);

return;

}

else

{

if(function_exists("AfterUnsuccessfulLogin"))

AfterUnsuccessfulLogin();

$strMessage = "Invalid Login";

}

}
$_SESSION["MyURL"]=$myurl;

if($myurl)

$smarty->assign("url",$myurl);

else

$smarty->assign("url",$defaulturl);
if(@$_POST["username"] || @$_GET["username"])

$smarty->assign("value_username","value=\"".htmlspecialchars(@$_POST["username"])."\"");

else

$smarty->assign("value_username","value=\"".htmlspecialchars(refine(@$_COOKIE["username"]))."\"");
if(@$_POST["password"])

$smarty->assign("value_password","value=\"".htmlspecialchars(@$_POST["password"])."\"");

else

$smarty->assign("value_password","value=\"".htmlspecialchars(refine(@$_COOKIE["password"]))."\"");
if(@$_GET["message"]=="expired")

$strMessage = "Your session has expired. Please login again.";
$smarty->assign("message",$strMessage);
$smarty->display("login.htm");

?>

Sergey Kornilov admin 11/16/2006

It appears your version of PHP don't understand var keyword.

You can replace all occuriencies of var with public (file adLDAP.php).

G
gdude66 author 11/16/2006

It appears your version of PHP don't understand var keyword.

You can replace all occuriencies of var with public (file adLDAP.php).



It was working with version 3.0 and same php version.

Is this ADLDAP or is it 3.1 that is causing the problem?

Sergey Kornilov admin 11/16/2006

I guess I know what's happening.
PHPRunner 3.1 uses Smarty template engine which modifies default error reporting level.

The same error in PHPRunner 3.0 was suppressed and you didn't see it.
So you can either follow my suggestion replacing var with public or add a call to error_reporting function in the beginning of adLDAP.php that sets lower error reporting level. Also you can check if newer version of adLDAP.php is available.
More info on error_reporting function:

http://us2.php.net/manual/en/function.error-reporting.php

G
gdude66 author 11/17/2006

OK thanks Sergy used public instead var m

Finally got it working here are modded files

  1. Login.php
    <?php

    ini_set("display_errors","1");

    ini_set("display_startup_errors","1");

    set_magic_quotes_runtime(0);
    include("include/dbcommon.php");
    if(@$_POST["a"]=="logout" || @$_GET["a"]=="logout")

    {

    session_unset();

    setcookie("username","",time()-365144060);

    setcookie("password","",time()-365144060);

    header("Location: login.php");

    exit();

    }

    if(!@$_SESSION["MyURL"])

    session_unset();
    include('libs/Smarty.class.php');

    $smarty = new Smarty();
    $myurl=@$_SESSION["MyURL"];

    unset($_SESSION["MyURL"]);
    $defaulturl="";

    $defaulturl="menu.php";
    $strMessage="";
    if(@$_COOKIE["username"] || @$_COOKIE["password"])

    $smarty->assign("checked"," checked");
    if (@$_POST["btnSubmit"] == "Login")

    {

    if(@$_POST["remember_password"] == 1)

    {

    setcookie("username",@$_POST["username"],time()+365144060);

    setcookie("password",@$_POST["password"],time()+365144060);

    $smarty->assign("checked"," checked");

    }

    else

    {

    setcookie("username","",time()-365144060);

    setcookie("password","",time()-365144060);

    $smarty->assign("checked","");

    }

    // username and password are stored in the database

    $conn=db_connect();

    $strlUsername = (string)@$_POST["username"];

    $strlPassword = (string)@$_POST["password"];

    $strUsername = (string)@$_POST["username"];

    $strPassword = (string)@$_POST["password"];
    $rstemp=db_query("select from ".AddTableWrappers($cLoginTable)." where 1=0",$conn);
    if(NeedQuotes(db_fieldtype($rstemp,$cUserNameField)))

    $strUsername="'".db_addslashes($strUsername)."'";

    else

    $strUsername=(0+$strUsername);

    if(NeedQuotes(db_fieldtype($rstemp,$cPasswordField)))

    $strPassword="'".db_addslashes($strPassword)."'";

    else

    $strPassword=(0+$strPassword);
    $strSQL = "select
    from ".AddTableWrappers($cLoginTable)." where ".AddFieldWrappers($cUserNameField).

    "=".$strUsername." and ".AddFieldWrappers($cPasswordField).

    "=".$strPassword;
    ################################################################################


    LDAP AUTHENTICATION MODIFICATION #

    ################################################################################




    //include the class

    include ("ldap/adLDAP.php");
    //create the LDAP connection

    $adldap = new adLDAP();

    $ldap_auth = 0;

    $ldap_group ="usergroup"; # Specified group for group authentication
    // Authenticate

    if (($adldap -> authenticate($strlUsername,$strlPassword))){

    if ($adldap -> user_ingroup($strlUsername,$ldap_group)){ # Group Authentication Only

    $ldap_auth = 1;
    // Check if user exists

    $sql = "Select from ".AddTableWrappers($cLoginTable)." Where ".AddFieldWrappers($cUserNameField)." = \"$strlUsername\"";

    $rs = mysql_query($sql,$conn) or die("USER QUERY FAILED.");
    // Update DB for new users

    //if (mysql_num_rows($rs) < 1) {

    //$info=$adldap->user_info($strlUsername,array("givenname","sn"));

    //$strldapfirstname = $info[0][givenname][0]; #sets firstname value from AD

    //$strldaplastname = $info[0][sn][0]; #sets lastname value from AD

    //$sql = "INSERT INTO ".AddTableWrappers($cLoginTable)." ( ".AddFieldWrapper($cUserNameField).", //firstname, lastname, level)";

    //$sql .= " SELECT ";

    //$sql .= "\"$strlUsername\" AS Expr1, "; #adds username to database

    //$sql .= "\"$strldapfirstname\" AS Expr2, "; #adds firstname to database

    //$sql .= "\"$strldaplastname\" AS Expr3, "; #adds lastname to database

    //$sql .= "1 AS Expr4;"; #adds level to database

    //$result = mysql_query($sql,$conn);

    //}
    // Generate Query

    $strSQL = "select
    from ".AddTableWrappers($cLoginTable)." where ".AddFieldWrappers($cUserNameField).

    "=\"".$strlUsername."\"";

    } #Group Authentication Only

    }
    // Catch failed logins

    if ($ldap_auth == 0) $strSQL = "select * from ".AddTableWrappers($cLoginTable)." where ".AddFieldWrappers($cUserNameField)."=\"xxxxx\"";
    ################################################################################


    END OF MODIFICATION #

    ################################################################################

    [/color]



    if(function_exists("BeforeLogin"))

    if(!BeforeLogin(postvalue("username"),postvalue("password")))

    $strSQL="select * from `staff` where 1<0";
    $rs=db_query($strSQL,$conn);

    if($data=db_fetch_array($rs))

    // if($data && @$data[$cUserNameField]====$syrPassword) {

    $_SESSION["UserID"] = @$_POST["username"];

    $_SESSION["AccessLevel"] = ACCESS_LEVEL_USER;

    $_SESSION["OwnerID"] = $data["idstaff"];

    $_SESSION["GroupID"] = $data["Access"];

    if(function_exists("AfterSuccessfulLogin"))

    AfterSuccessfulLogin();

    if($myurl)

    header("Location: ".$myurl);

    else

    header("Location: ".$defaulturl);

    return;

    }

    else

    {

    if(function_exists("AfterUnsuccessfulLogin"))

    AfterUnsuccessfulLogin();

    $strMessage = "Invalid Login";

    }

    }
    $_SESSION["MyURL"]=$myurl;

    if($myurl)

    $smarty->assign("url",$myurl);

    else

    $smarty->assign("url",$defaulturl);
    if(@$_POST["username"] || @$_GET["username"])

    $smarty->assign("value_username","value=\"".htmlspecialchars(@$_POST["username"])."\"");

    else

    $smarty->assign("value_username","value=\"".htmlspecialchars(refine(@$_COOKIE["username"]))."\"");
    if(@$_POST["password"])

    $smarty->assign("value_password","value=\"".htmlspecialchars(@$_POST["password"])."\"");

    else

    $smarty->assign("value_password","value=\"".htmlspecialchars(refine(@$_COOKIE["password"]))."\"");
    if(@$_GET["message"]=="expired")

    $strMessage = "Your session has expired. Please login again.";
    $smarty->assign("message",$strMessage);
    $smarty->display("login.htm");

    ?>




and the modded adldap.php file to cope with php 5 not needed for 4

<?php

/*

PHP LDAP CLASS FOR MANIPULATING ACTIVE DIRECTORY

Version 1.5
Written by Scott Barnett

email: scott@wiggumworld.com

http://adldap.sourceforge.net/
Copyright © 2006 Scott Barnett
I'd appreciate any improvements or additions to be submitted back

to benefit the entire community <img src='https://asprunner.com/forums/file.php?topicimage=1&fieldname=reply&id=12957&image=1&table=forumreplies' class='bbc_emoticon' alt=':)' />
Works with both PHP 4 and PHP 5
The examples should be pretty self explanatory. If you require more

information, please visit http://adldap.sourceforge.net/
This library is free software; you can redistribute it and/or

modify it under the terms of the GNU Lesser General Public

License as published by the Free Software Foundation; either

version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,

but WITHOUT ANY WARRANTY; without even the implied warranty of

MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU

Lesser General Public License for more details.
****

Something to keep in mind is that Active Directory is a permissions

based directory. If you bind as a domain user, you can't fetch as

much information on other users as you could as a domain admin.

****
FUNCTIONS:
authenticate($username,$password)

Authenticate to the directory with a specific username and password
user_info($user,$fields=NULL)

Returns an array of information for a specific user
user_groups($user,$recursive=NULL)

Returns an array of groups that a user is a member off
user_ingroup($user,$group,$recursive=NULL)

Returns true if the user is a member of the group
group_info($group)

Returns an array of information for a specific group
all_users($include_desc = false, $search = "", $sorted = true)

Returns all AD users (expensive on resources)
all_groups($include_desc = false, $search = "
", $sorted = true)

Returns all AD groups (expensive on resources)
*/
// Different type of accounts in AD

define ('ADLDAP_NORMAL_ACCOUNT', 805306368);

define ('ADLDAP_WORKSTATION_TRUST', 805306369);

define ('ADLDAP_INTERDOMAIN_TRUST', 805306370);

define ('ADLDAP_SECURITY_GLOBAL_GROUP', 268435456);

define ('ADLDAP_DISTRIBUTION_GROUP', 268435457);

define ('ADLDAP_SECURITY_LOCAL_GROUP', 536870912);

define ('ADLDAP_DISTRIBUTION_LOCAL_GROUP', 536870913);
class adLDAP {

// BEFORE YOU ASK A QUESTION, PLEASE READ THE FAQ

// http://adldap.sourceforge.net/faq.php
// You will need to edit these variables to suit your installation

public $_account_suffix="@domain.local";

public $_base_dn = "DC=domain,DC=local";
// An array of domain controllers. Specify multiple controllers if you

// would like the class to balance the LDAP queries amongst multiple servers

public $_domain_controllers = array ("DC.domain.local");
// optional account with higher privileges for searching

public $_ad_username="account";

public $_ad_password="xxxxxx";
// AD does not return the primary group. http://support.microsoft.com/?kbid=321360

// This tweak will resolve the real primary group, but may be resource intensive.

// Setting to false will fudge "Domain Users" and is much faster. Keep in mind though that if

// someone's primary group is NOT domain users, this is obviously going to bollocks the results

public $_real_primarygroup=true;
// When querying group memberships, do it recursively

// eg. User Fred is a member of Group A, which is a member of Group B, which is a member of Group C

// user_ingroup("Fred","C") will returns true with this option turned on, false if turned off

public $_recursive_groups=true;
// You should not need to edit anything below this line

//****

**
//other variables

public $_user_dn;

public $_user_pass;

public $_conn;

public $_bind;
// default constructor

function adLDAP(){

//connect to the LDAP server as the username/password

$this->_conn = ldap_connect($this->random_controller());

ldap_set_option($this->_conn, LDAP_OPT_PROTOCOL_VERSION, 3);

ldap_set_option($this->_conn, LDAP_OPT_REFERRALS, 0); //disable plain text passwords

return true;

}
// default destructor

function __destruct(){ ldap_close ($this->_conn); }
function random_controller(){

//select a random domain controller

mt_srand(doubleval(microtime()) 100000000);

return ($this->_domain_controllers[array_rand($this->_domain_controllers)]);

}
// authenticate($username,$password)

// Authenticate to the directory with a specific username and password

// Extremely useful for validating login credentials

function authenticate($username,$password){

//validate a users login credentials

$returnval=false;
if ($username!=NULL && $password!=NULL){ //prevent null bind

$this->_user_dn=$username.$this->_account_suffix;

$this->_user_pass=$password;
$this->_bind = @ldap_bind($this->_conn,$this->_user_dn,$this->_user_pass);

if ($this->_bind){ $returnval=true; }

}

return ($returnval);

}
// rebind()

// Binds to the directory with the default search username and password

// specified above.

function rebind(){

//connect with another account to search with if necessary

$ad_dn=$this->_ad_username.$this->_account_suffix;

$this->_bind = @ldap_bind($this->_conn,$ad_dn,$this->_ad_password);

if ($this->_bind){ return (true); }

return (false);

}
// user_info($user,$fields)

// Returns an array of information for a specific user

function user_info($user,$fields=NULL){

if ($user!=NULL){

if ($this->_ad_username!=NULL){ $this->rebind(); } //bind as a another account if necessary
if ($this->_bind){ //perform the search and grab all their details

$filter="samaccountname=".$user;

if ($fields==NULL){

$fields=array("samaccountname","mail","memberof","department","displayname","telephonenumber","primarygroupid");

//$fields=array("
");

}

$sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);

$entries = ldap_get_entries($this->_conn, $sr);
// AD does not return the primary group in the ldap query, we may need to fudge it

if ($this->_real_primarygroup){

$entries[0]["memberof"][]=$this->group_cn($entries[0]["primarygroupid"][0]);

} else {

$entries[0]["memberof"][]="CN=Domain Users,CN=Users,".$this->_base_dn;

}
//echo ("<pre>"); print_r($entries);
$entries[0]["memberof"]["count"]++;

return ($entries);

}

}
return (false);

}
// user_groups($user)

// Returns an array of groups that a user is a member off

function user_groups($user,$recursive=NULL){

if ($this->_ad_username!=NULL){ $this->rebind(); } //bind as a another account if necessary

if ($recursive==NULL){ $recursive=$this->_recursive_groups; }
if ($this->_bind){

//search the directory for their information

$info=@$this->user_info($user,array("memberof"));

//echo ("<pre>"); print_r($info);

$groups=$info[0]["memberof"]; //presuming the entry returned is our guy (unique usernames)
$group_array=$this->nice_names($groups);
if ($recursive){

foreach ($group_array as $id => $group_name){

$extra_groups=$this->recursive_groups($group_name);

$group_array=array_merge($group_array,$extra_groups);

}

}
return ($group_array);

}

return (false);

}
// user_ingroup($user,$group)

// Returns true if the user is a member of the group

function user_ingroup($user,$group,$recursive=NULL){

if ($recursive==NULL){ $recursive=$this->_recursive_groups; }
if (($user!=NULL) && ($group!=NULL)){

if ($this->_ad_username!=NULL){ $this->rebind(); } //bind as a another account if necessary
if ($this->_bind){

$groups=$this->user_groups($user,array("memberof"),$recursive);

if (in_array($group,$groups)){ return (true); }

}

}

return (false);

}
function recursive_groups($group){

$ret_groups=array();
$groups=$this->group_info($group,array("memberof"));

$groups=$groups[0]["memberof"];
if ($groups){

$group_names=$this->nice_names($groups);

$ret_groups=array_merge($ret_groups,$group_names); //final groups to return
foreach ($group_names as $id => $group_name){

$child_groups=$this->recursive_groups($group_name);

$ret_groups=array_merge($ret_groups,$child_groups);

}
}
return ($ret_groups);

}
// take an ldap query and return the nice names, without all the LDAP prefixes (eg. CN, DN)

function nice_names($groups){
$group_array=array();

for ($i=0; $i<$groups["count"]; $i++){ //for each group

$line=$groups[$i];
if (strlen($line)>0){

//more presumptions, they're all prefixed with CN=

//so we ditch the first three characters and the group

//name goes up to the first comma

$bits=explode(",",$line);

$group_array[]=substr($bits[0],3,(strlen($bits[0])-3));

}

}

return ($group_array);

}
function group_cn($gid){

if ($this->_ad_username!=NULL){ $this->rebind(); } //bind as a another account if necessary
// coping with AD not returning the primary group

// http://support.microsoft.com/?kbid=321360

// for some reason it's not possible to search on primarygrouptoken=XXX

// if someone can show otherwise, I'd like to know about it <img src='https://asprunner.com/forums/file.php?topicimage=1&fieldname=reply&id=12957&image=2&table=forumreplies' class='bbc_emoticon' alt=':)' />

// this way is resource intensive and generally a pain in the @#%^
$r=false;
if ($this->_bind){

$filter="(&(objectCategory=group)(samaccounttype=". ADLDAP_SECURITY_GLOBAL_GROUP ."))";

$fields=array("primarygrouptoken","samaccountname","distinguishedname");

$sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);

$entries = ldap_get_entries($this->_conn, $sr);
for ($i=0; $i<$entries["count"]; $i++){

if ($entries[$i]["primarygrouptoken"][0]==$gid){

$r=$entries[$i]["distinguishedname"][0];

$i=$entries["count"];

}

}

}

return ($r);

}
// group_info($group_name,$fields=NULL)

// Returns an array of information for a specified group

function group_info($group_name,$fields=NULL){

if ($this->_ad_username!=NULL){ $this->rebind(); } //bind as a another account if necessary
if ($this->_bind){

//escape brackets

$group_name=str_replace("(","\(",$group_name);

$group_name=str_replace(")","\)",$group_name);
$filter="(&(objectCategory=group)(name=".$group_name."))";

//echo ($filter."
");

if ($fields==NULL){ $fields=array("member","memberof","cn","description","distinguishedname","objectcategory","samaccountname"); }

$sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);

$entries = ldap_get_entries($this->_conn, $sr);

//print_r($entries);

return ($entries);

}

return (false);

}
function all_users($include_desc = false, $search = "", $sorted = true){

// Returns all AD users

if ($this->_ad_username!=NULL){ $this->rebind(); } //bind as a another account if necessary
if ($this->_bind){

$users_array = array();
//perform the search and grab all their details

$filter = "(&(objectClass=user)(samaccounttype=". ADLDAP_NORMAL_ACCOUNT .")(objectCategory=person)(cn=$search))";

$fields=array("samaccountname","displayname");

$sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);

$entries = ldap_get_entries($this->_conn, $sr);
for ($i=0; $i<$entries["count"]; $i++){

if( $include_desc && strlen($entries[$i]["displayname"][0]) > 0 )

$users_array[ $entries[$i]["samaccountname"][0] ] = $entries[$i]["displayname"][0];

else if( $include_desc )

$users_array[ $entries[$i]["samaccountname"][0] ] = $entries[$i]["samaccountname"][0];

else

array_push($users_array, $entries[$i]["samaccountname"][0]);

}

if( $sorted ){ asort($users_array); }

return ($users_array);

}

return (false);

}
function all_groups($include_desc = false, $search = "
", $sorted = true){

// Returns all AD groups

if ($this->_ad_username!=NULL){ $this->rebind(); } //bind as a another account if necessary
if ($this->_bind){

$groups_array = array();
//perform the search and grab all their details

$filter = "(&(objectCategory=group)(samaccounttype=". ADLDAP_SECURITY_GLOBAL_GROUP .")(cn=$search))";

$fields=array("samaccountname","description");

$sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);

$entries = ldap_get_entries($this->_conn, $sr);
for ($i=0; $i<$entries["count"]; $i++){

if( $include_desc && strlen($entries[$i]["description"][0]) > 0 )

$groups_array[ $entries[$i]["samaccountname"][0] ] = $entries[$i]["description"][0];

else if( $include_desc )

$groups_array[ $entries[$i]["samaccountname"][0] ] = $entries[$i]["samaccountname"][0];

else
array_push($groups_array, $entries[$i]["samaccountname"][0]);

}

if( $sorted ){ asort($groups_array); }

return ($groups_array);

}

return (false);

}

} // End class
?>


Thanks again to theSofa, Mark Hall and Sergy

Also this only authenticates against an existing user - I have commented out the section which adds new users.