Showing paste #7Vsc:

<?php

class ldap {
	/*https://stackoverflow.com/questions/2689629/how-do-i-solve-ldap-start-tls-unable-to-start-tls-connect-error-in-php
	 * 
	 * 
	 * https://www.novell.com/coolsolutions/tip/5838.html
	 * ACHTUNG SSL mit SELFSIGN braucht C:\openldap\sysconf\ldap.conf
	 * TLS_REQCERT never
	 * 
	 * 
	 * PHP 7.0? 7.1
	 * ldap_set_option($con, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_NEVER);
	 * https://gist.github.com/heiglandreas/8a299a6f47a13ba463c3f2da41c679f7
	 * 
	 */

	var $host;
	var $port; //ssl 636, default 389
	var $basedn;
	var $username;
	var $password;
	
	var $hwdLdap;
	var $hwdBind;
	var $hwdSearch;
	var $autoconnect;
	var $intCount;
	var $arrAllRows;
	var $intCurrentRow;
	var $realPrimaryGroup;
	
	var $persistent;
	var $ssl;
		
	public function __construct(){
		$this->host = "";
		$this->port = 0;
		$this->basedn = "";
		$this->username = "";
		$this->password = "";
		
		$this->hwdLdap = 0;
		$this->hwdBind = false;
		$this->hwdSearch = 0;
		$this->autoconnect = false;
		$this->intCount = 0;
		$this->arrAllRows = array();
		$this->intCurrentRow = 0;
		$this->realPrimaryGroup = true;

		$this->persistent = false;
		$this->ssl = true; 
	}

	function setconfig($username = "read", $password = "readpass", $base= "O=Folder", $host = "192.168.0.246", $ssl = false, $port = "0"){
		$this->username = $username;
		$this->password = $password;
		$this->basedn = $base;
		$this->host = $host;
		$this->port = $port;	
		$this->ssl = $ssl;
	}
	
	function connect() {
	    //ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7);
	    //putenv('LDAPTLS_REQCERT=never');
		if (($this->host == "")) return false;
		if ($this->hwdLdap){
			$this->close();
		}
		if ($this->port == 0){
		    if ($this->ssl) $this->port = 636;
		      else $this->port = 389;
		}
		if ($this->ssl){
		    if (strpos($this->host, 'ldaps:') === false) $this->host = 'ldaps://'.$this->host;        
		}
		$this->hwdLdap = ldap_connect($this->host, $this->port);
		if ($this->hwdLdap)
			if (ldap_set_option($this->hwdLdap, LDAP_OPT_PROTOCOL_VERSION, 3))
		      if (ldap_set_option($this->hwdLdap, LDAP_OPT_REFERRALS, 0)) 
		          return $this->hwdLdap;
	    $this->close();
		return false;
	}
	
	function bind(){
		if (!$this->hwdLdap) $this->connect();
		if ($this->hwdLdap){
			$this->hwdBind = @ldap_bind($this->hwdLdap,$this->username,$this->password);
			if ($this->hwdBind) {
				return $this->hwdBind;
			}
		}
		return false;
	}
	
	function close() {
		if ($this->hwdLdap){
			ldap_close($this->hwdLdap);
			$this->hwdLdap = 0;
			$this->hwdBind = 0;
			$this->hwdSearch = 0;
			$this->autoconnect = false;				
			return true;
		}
		return false;
	}	
	
	function query($string){
		if (strlen($string) <= 0) return false;
		$this->autoconnect = false;
		if (!$this->hwdBind) {
			$this->bind();
			$this->autoconnect = true;
		}
		if ($this->hwdBind) {
			$this->intCount = -1;
			$this->intCurrentRow = 0;
			$this->hwdSearch = ldap_search($this->hwdLdap, $this->basedn, $string);
			$this->arrAllRows = @ldap_get_entries($this->hwdLdap, $this->hwdSearch);
			
			$this->intCount = $this->arrAllRows["count"];		
			if ($this->autoconnect) $this->close();
			if ($this->intCount > -1) return $this->intCount;
		}		
		return false;
	}
	
    function getRootDse($attributes = array("*", "+")) {
    	$this->autoconnect = false;
		if (!$this->hwdBind) {
			$this->bind();
			$this->autoconnect = true;
		}
		if ($this->hwdBind) {
        
        	$sr = @ldap_read($this->hwdLdap, NULL, 'objectClass=*', $attributes);
        	$entries = @ldap_get_entries($this->hwdLdap, $sr);
        	if ($this->autoconnect) $this->close();
        	return $entries;
		}
    }	

	function get_result() {
		if (is_array($this->arrAllRows) && $this->intCount > -1) {
			if ($this->intCurrentRow < $this->intCount)	{
				$this->intCurrentRow++;
				$row = array();
				$row['DN'] = $this->arrAllRows[$this->intCurrentRow-1]['dn'];
				for ($i = 0; $i < $this->arrAllRows[$this->intCurrentRow-1]["count"]; $i++) {
					$name = $this->arrAllRows[$this->intCurrentRow-1][$i];
					$row[strtoupper($name.'_count')] = $this->arrAllRows[$this->intCurrentRow-1][$name]['count'];
					for ($j = 0; $j < $this->arrAllRows[$this->intCurrentRow-1][$name]['count']; $j++) {
						//$fname = $this->arrAllRows[$this->intCurrentRow-1][$name][$j].'_'.$j+1;
						$fname = strtoupper($name.'_'.($j+1));
						$row[$fname] = $this->arrAllRows[$this->intCurrentRow-1][$name][$j];												
					}
					
				}
				return $row;
			}
		} 
		return false;
				
	}
	
	function get_count() {
		if (is_array($this->arrAllRows) && $this->intCount > -1) {
			return $this->intCount;
		}
		return 0;
	}	
	
	function get_error() {
		if ($this->hwdLdap) return @ldap_error($this->hwdLdap);
	}	

    /**
    * Groups the user is a member of
    * 
    * @param string $username The username to query
    * @param bool $recursive Recursive list of groups
    * @param bool $isGUID Is the username passed a GUID or a samAccountName
    * @return array
    */
    function groups($username, $recursive = NULL) {
    	$this->autoconnect = false;
		if (!$this->hwdBind) {
			$this->bind();
			$this->autoconnect = true;
		}
		if ($this->hwdBind && $username !== NULL) {    	
     	           	// Search the directory for their information
        	$info = @$this->info($username, array("memberof", "primarygroupid"));
        	$groups = $this->niceNames($info[0]["memberof"]); // Presuming the entry returned is our guy (unique usernames)

        	if ($recursive === true){
            	foreach ($groups as $id => $groupName){
                	$extraGroups = $this->adldap->group()->recursiveGroups($groupName);
                	$groups = array_merge($groups, $extraGroups);
            	}
        	}
        	if ($this->autoconnect) $this->close();
        	return $groups;
		}
        
        return false;
    }
    
    /**
    * Find information about the users. Returned in a raw array format from AD
    * 
    * @param string $username The username to query
    * @param array $fields Array of parameters to query
    * @param bool $isGUID Is the username passed a GUID or a samAccountName
    * @return array
    */
    function info($username, $fields = NULL) {
        $this->autoconnect = false;
		if (!$this->hwdBind) {
			$this->bind();
			$this->autoconnect = true;
		}
		if ($this->hwdBind && $username !== NULL) {   

        	if (strstr($username, "@")) {
             	$filter = "userPrincipalName=" . $username;
        	} else {
             	$filter = "samaccountname=" . $username;
        	}
        	$filter = "(&(objectCategory=person)({$filter}))";
        	if ($fields === NULL) { 
            	$fields = array("samaccountname","mail","memberof","department","displayname","telephonenumber","primarygroupid","objectsid"); 
        	}
        	if (!in_array("objectsid", $fields)) {
            	$fields[] = "objectsid";
        	}
        	$sr = ldap_search($this->hwdLdap, $this->basedn, $filter, $fields);
        	$entries = ldap_get_entries($this->hwdLdap, $sr);
        
        	if (isset($entries[0])) {
            	if ($entries[0]['count'] >= 1) {
                	if (in_array("memberof", $fields)) {
                    	// AD does not return the primary group in the ldap query, we may need to fudge it
                    	if ($this->realPrimaryGroup && isset($entries[0]["primarygroupid"][0]) && isset($entries[0]["objectsid"][0])){
                        	//$entries[0]["memberof"][]=$this->group_cn($entries[0]["primarygroupid"][0]);
                        	$entries[0]["memberof"][] = $this->getPrimaryGroup($entries[0]["primarygroupid"][0], $entries[0]["objectsid"][0]);
                    	}/* else {
                        	$entries[0]["memberof"][] = "CN=Domain Users,CN=Users," . $this->basedn;
                    	}*/
                    	if (!isset($entries[0]["memberof"]["count"])) {
                        	$entries[0]["memberof"]["count"] = 0;
                    	}
                   	 $entries[0]["memberof"]["count"]++;
                   	 
                   	 
                   	 $entries[0]["memberofnice"] = $this->niceNames($entries[0]["memberof"]);
                   	 $entries[0]["memberofnice"]["count"] =  $entries[0]["memberof"]["count"];
                	}
            	}
            	if ($this->autoconnect) $this->close();
            	return $entries;
        	}
        	if ($this->autoconnect) $this->close();
		}
        return false;
    }
    
    function niceNames($groups) {
    
    	$groupArray = 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);
    			$groupArray[] = utf8_decode(substr($bits[0], 3, (strlen($bits[0])-3)));
    		}
    	}
    	return $groupArray;
    }

    function getPrimaryGroup($gid, $usersid)
    {
    	if ($gid === NULL || $usersid === NULL) {
    		return false;
    	}
    	$r = false;
    
    	$gsid = substr_replace($usersid, pack('V',$gid), strlen($usersid)-4,4);
    	$filter = '(objectsid=' . $this->getTextSID($gsid).')';
    	$fields = array("samaccountname","distinguishedname");
    	$sr = ldap_search($this->getLdapConnection(), $this->getBaseDn(), $filter, $fields);
    	$entries = ldap_get_entries($this->getLdapConnection(), $sr);
    
    	return $entries[0]['distinguishedname'][0];
    }
    
    function getTextSID($binsid) {
    	$hex_sid = bin2hex($binsid);
    	$rev = hexdec(substr($hex_sid, 0, 2));
    	$subcount = hexdec(substr($hex_sid, 2, 2));
    	$auth = hexdec(substr($hex_sid, 4, 12));
    	$result = "$rev-$auth";
    
    	for ($x=0;$x < $subcount; $x++) {
    		$subauth[$x] =
    		hexdec($this->littleEndian(substr($hex_sid, 16 + ($x * 8), 8)));
    		$result .= "-" . $subauth[$x];
    	}
    
    	// Cheat by tacking on the S-
    	return 'S-' . $result;
    }
    
    function littleEndian($hex)
    {
    	$result = '';
    	for ($x = strlen($hex) - 2; $x >= 0; $x = $x - 2) {
    		$result .= substr($hex, $x, 2);
    	}
    	return $result;
    }
    
    function getLdapConnection() {
    	if ($this->hwdLdap) {
    		return $this->hwdLdap;
    	}
    	return false;
    }
    	
    function getBaseDn() {
    	return $this->basedn;
    }
}

?>
Make a new paste