<?php
// Initialize session
session_start();

function authenticate($user, $password) {
	if(empty($user) || empty($password)) return false;

	// Active Directory server
	$ldap_host = "192.168.200.251";

	// Active Directory DN
	$ldap_dn = "OU=RCIG,DC=domain,DC=rcig,DC=net";

	// Active Directory user group
	$ldap_user_group = "Chat";

	// Active Directory manager group
	$ldap_manager_group = "Systems";

	// Domain, for purposes of constructing $user
	$ldap_usr_dom = '@domain.rcig.net';

	// connect to active directory
	$ldap = ldap_connect($ldap_host);

	// verify user and password
	if($bind = @ldap_bind($ldap, $user.$ldap_usr_dom, $password)) {
		// valid
		// check presence in groups
		$filter = "(sAMAccountName=".$user.")";
		$attr = array("memberof","displayname");
		$result = ldap_search($ldap, $ldap_dn, $filter, $attr) or exit("Unable to search LDAP server");
		$entries = ldap_get_entries($ldap, $result);
		$displayname = $entries[0]['displayname'][0];
		ldap_unbind($ldap);

		// check groups
		foreach($entries[0]['memberof'] as $grps) {
			// is manager, break loop
			if(strpos($grps, $ldap_manager_group)) { $access = "2"; break; }

			// is user
			if(strpos($grps, $ldap_user_group)) $access = "1";
		}

		if($access != 0) {
			// establish session variables
			$_SESSION['user'] = $user;
			$_SESSION['access'] = $access;
			$_SESSION['displayname'] = $displayname;
			return true;
		} else {
			// user has no rights
			return false;
		}

	} else {
		// invalid name or password
		return false;
	}
}
?>
