<?php
// AuthLdap.php
// Copyright P.Kassel, M.Seliger, G.Trietsch, all Rights Reserved
namespace Docuform\Api\Authentication;use Docuform\Database\DbPDO;class AuthLdap{static public function LdapAuthentication(\DI\Container $container,string $username,string $password):bool{$Result=false;if(!empty($username)&&!empty($password)){$database=$container->get('database');$ldapActive=$container->get('ldapactive');if($ldapActive>0){$ldapServer=$database->getDbValue("ACCSYSTEM","sValue","sSection='Ldap' AND sKey='Server'");if(!empty($ldapServer)){$ldapServer=trim($ldapServer);$ldapUser=$username;if(strpos($username,'@')===FALSE){$sDomain=$database->getDbValue("ACCSYSTEM","sValue","sSection='Ldap' AND sKey='Domain'");if(!empty($sDomain)){$ldapUser=$username.'@'.$sDomain;}}if(!empty($ldapUser)){$servers=explode(",",$ldapServer);if(count($servers)<2)$servers=explode(' ',$ldapServer);$Result=self::LdapBindUser($ldapUser,$password,$servers,$ldapActive);}}}}return $Result;}private static function LdapBindUser(string $username,string $password,array $servers,int $ldapActive):bool{$bResult=false;if(count($servers)){$iSrvIdx=0;do{$ldapServer=(($ldapActive==2)?"ldaps":"ldap").'://'.$servers[$iSrvIdx++].':'.(($ldapActive==2)?636:389);$ldapConn=ldap_connect($ldapServer);if($ldapConn){$Success=ldap_set_option($ldapConn,LDAP_OPT_PROTOCOL_VERSION,3);$ErrMsg=error_reporting(1);if($Success)$bResult=ldap_bind($ldapConn,$username,$password);error_reporting($ErrMsg);ldap_close($ldapConn);}}while($bResult==false&&$iSrvIdx<count($servers));}return $bResult;}}