<?php
//version 2013-08-26

//@2013-05-15 wersja nie nadpisujaca ID uzytkownika - dodaje z LDAPA nowe konto
//@2013-07-22 wersja umozliwia korzystanie z nested-groups na serverze apple

//@2013-08-02 wersja umozliwia ustawianie sharowanych kont dla typu zasobu IMAP_SHARED_MAILBOX ,
//na podstawie struktury zasobow oraz (1 parent). Nr zasobu odczytany z opisu CN [zasob] Opis.
//@2013-08-06 potrafi zle dzialac, jak ktos wpisze login z duzej $ADM_ACCOUNT=strtolower($ADM_ACCOUNT);

//2013-09-13 - inicjalizacja przeniesiona poza funkcje - cos innego musi ja wyzwalac
//funkcja wymaga aby serwer apple mial uprawnienia visudo dla funkcji : 
//visudo : (/etc/sudoers)
//_www    ALL = NOPASSWD: /usr/bin/dscl
//_www    ALL = NOPASSWD: /usr/bin/pwpolicy


function AUTH_LDAP_CLIENT($ADM_ACCOUNT, $ADM_PASSWD) {
global $conn,$LDAP_SERVER_AUTH,$LDAP_SERVER_AUTH_DN,$result ;
$LDAP_OK=false;
$ADM_ACCOUNT=strtolower($ADM_ACCOUNT); //@2013-08-06 potrafi zle dzialac, jak ktos wpisze login z duzej

	if(!$LDAP_SERVER_AUTH) {
		DEBUG_S(-3,'Cannot auth to LDAP server - server not set in config ');
		die();
	}
			//1. proba polaczenia sie po LDAP, jezeli nie dziala, to odpuszczamy
			$dc_arr=explode('.',$LDAP_SERVER_AUTH); settype($dc, "string");
				foreach($dc_arr as $dc_dc) {
					if($dc) $dc.=",dc=".$dc_dc; else $dc="dc=".$dc_dc;
				}
			if(isset($LDAP_SERVER_AUTH_DN)) $dc=$LDAP_SERVER_AUTH_DN;
				
			

			$ldapconn = ldap_connect($LDAP_SERVER_AUTH)
			    or die("Could not connect to LDAP server.");
			if ($ldapconn) {

			 // Set some ldap options for talking to 
			    ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
			    ldap_set_option($ldapconn, LDAP_OPT_REFERRALS, 0);
				if(strstr($ADM_ACCOUNT,'@')) {
					$dn = "cn=users,".$dc; // also tried DC=example,DC=co,DC=uk
			        $filter="(mail=".$ADM_ACCOUNT.")";
			        $RETURN['filter']=$filter;
			        $justthese = array("uid", "cn");
			        $sr=ldap_search($ldapconn, $dn, $filter, $justthese);
			        $info = ldap_get_entries($ldapconn, $sr);
			        $RETURN['REAL_ADM_ACCOUNT']=$info[0]['uid'][0];
			        $ADM_ACCOUNT=$info[0]['uid'][0];
				}
				
				$ldaprdn  = "uid=".$ADM_ACCOUNT.",cn=users,".$dc;     // ldap rdn or dn
			
			
			    // binding anonymously
			    $ldapbind = @ldap_bind($ldapconn,$ldaprdn,$ADM_PASSWD);
			    if ($ldapbind) {
			        $LDAP_OK=true;
			       
			    } else {
			       DEBUG_S(-3,"LDAP authorization failed !!! /BLAD AUTORYZACJI LDAP ! ","Server LDAP: ".$LDAP_SERVER_AUTH."; dn: ".$ldaprdn,__FILE__,__FUNCTION__,__LINE__);
				 //  die();
			    }
			    	//uid=arkadiuszbinder,
			  		$dn = "cn=users,".$dc; // also tried DC=example,DC=co,DC=uk
			  		
			        $filter="(uid=".$ADM_ACCOUNT.")";
			        $justthese = array("uid", "givenName", "mail","*");
			
			        $sr=ldap_search($ldapconn, $dn, $filter, $justthese);
			
			        $info = ldap_get_entries($ldapconn, $sr);

			       DEBUG_S(3,'LDAP AUTH: ',$info,__FILE__,__FUNCTION__,__LINE__);
			    	if($LDAP_OK) { //jezeli jest rekord zwrocony,to nadpisujemy zmienne sesji i nadpisujemy rekord w bazie ADMIN_USERS tymi danymi 
			    	
			    	
//			    		echo "<br> Email to ".$info[0]['mail'][0];
						$_SESSION['AUTHORIZE_USER']=$ADM_ACCOUNT;
			    		$_SESSION['ADM_PASSWD']=$ADM_PASSWD;
						$_SESSION['OTHER_INFO']=$info[0]['mail'][0]; //email
						$_SESSION['ADM_ACCOUNT']=$ADM_ACCOUNT;
//						$_SESSION['ADM_ID']=$info[0]['uidnumber'][0];
						$_SESSION['ADM_NAME']=$info[0]['cn'][0];

					//reszte bierzemy z lokalnej bazy danych
					SEF('ZAP_SQL');
					if(empty($_SESSION['CONFIG']['BILLING_USERS_ADD_TABLE_JOIN'])) $sql="select u.ID from ADMIN_USERS as u  where u.ADM_ACCOUNT='".$_SESSION['AUTHORIZE_USER']."' limit 1";
					else $sql="select u.ID,bua.* from ADMIN_USERS as u ".$_SESSION['CONFIG']['BILLING_USERS_ADD_TABLE_JOIN']." where u.ADM_ACCOUNT='".$_SESSION['AUTHORIZE_USER']."' limit 1";

					DEBUG_S(3,'wyszukanie danych firmy',$sql,__FILE__,__FUNCTION__,__LINE__);
					ZAP_SQL($sql);
						while($h=mysql_fetch_object($result)) {
						 $STARY_ID=$h->ID;
						 $_SESSION['P_NIP']=$h->P_NIP;
						 $_SESSION['ID_BILLING_USERS']=$h->ID_BILLING_USERS; //todo powinien byc wzgelednie array do kilku firm
//						 DEBUG_S(-3,'wynik firmy',$h);
//						 $_SESSION['ID']=$h->ID;
						 //echo " Poprzedni ID :".$STARY_ID." ";
						}
					DEBUG_S(3,'Szukam z lokalnej bazy',"select * from ADMIN_USERS where ADM_ACCOUNT='".$ADM_ACCOUNT."' limit 1",__FILE__,__FUNCTION__,__LINE__);
					ZAP_SQL("select * from ADMIN_USERS where ADM_ACCOUNT='".$ADM_ACCOUNT."' limit 1");	
					if(mysql_num_rows($result)==0) { //updatujemy ID konta jezeli jest
			//	//		ZAP_SQL("delete from  ADMIN_USERS where  ID='".$_SESSION['ADM_ID']."' "); //zly ID kasujemy			
			//	//		ZAP_SQL("update ADMIN_USERS set ID='".$_SESSION['ADM_ID']."' where ADM_ACCOUNT='".$ADM_ACCOUNT."'"); //przenosimy 
			//	//		ZAP_SQL("select * from ADMIN_USERS where ID='".$_SESSION['ADM_ID']."' limit 1");	
			//	//	    ZAP_SQL("update CRM_AUTH_PROFILE set REMOTE_ID='".$_SESSION['ADM_ID']."' where REMOTE_ID='".$STARY_ID."' and REMOTE_TABLE='ADMIN_USERS'"); //przenosimy 
			//	//		ZAP_SQL("update CRM_TESTY set ID_TESTER='".$_SESSION['ADM_ID']."' where ID_TESTER='".$STARY_ID."'"); //przenosimy 

					}
					while($h=mysql_fetch_object($result)) {
						$_SESSION['ADM_ID']=$h->ID;
						//echo " <br> Znalazlem rekord dla ".$_SESSION['ADM_ID']." (".$h->ADM_ADMIN_LEVEL."): ";
						$_SESSION['ADM_AREA']=$h->ADM_AREA;
						$_SESSION['ADM_TECH_WORKER']=$h->ADM_TECH_WORKER;
							if(empty($h->ADM_COMPANY)) $h->ADM_COMPANY='%';
						$_SESSION['ADM_COMPANY']=$h->ADM_COMPANY;
						//echo "<br> Ustawiam adm company na ".$_SESSION['ADM_COMPANY']." ";
						if(!empty($h->ID_BILLING_USERS)) $_SESSION['ID_BILLING_USERS']=$h->ID_BILLING_USERS;				    
						$_SESSION['ADM_ADMIN_LEVEL']=$h->ADM_ADMIN_LEVEL;
						if(!isset($_SESSION['ADM_ADMIN_LEVEL'])) {
						 if(($info[0]['uidnumber'][0]==1000)||($info[0]['uidnumber'][0]==0))
						
							// ! sprawdzam czy jest juz jakis user - jezeli nie ma to daje jednego i daje mu uprawnienia roota!
							ZAP_SQL('select count(*) from ADMIN_USERS');
							while($h=mysql_fetch_array($result)) {
								$ile_jest_userow=$h[0];
							}
							if($ile_jest_userow==0) {
							// $_SESSION['ADM_ADMIN_LEVEL']=0; //1000 ma admin 
							// DEBUG_S(3,'Jednorazowo inicjalizuje uprawnienia do tabeli uzytkownikow dla administratora w celu aktualizaji uprawnien!!!','',__FILE__,__FUNCTION__,__LINE__);
						 	// USERS_COLUMN_INIT2('ADMIN_USERS','','RXWX',''); //inicjalizacja jednorazowa w celu ustawienia poziomow uprawnien i funkcji
							}
						 }
						$_SESSION['ADM_PHONE']="$h->ADM_PHONE";
						$_SESSION['ADM_ADMIN_EXPIRE']="$h->ADM_ADMIN_EXPIRE";
						$_SESSION['ADM_ADMIN_DESC']="$h->ADM_ADMIN_DESC";
						$_SESSION['ADM_ID']=$h->ID;

					}
					 if(strlen($_SESSION['ADM_ADMIN_LEVEL'])==0) {
					echo "<br> Pusty admin level";
					 $_SESSION['ADM_ADMIN_LEVEL']=6;
					 }
					//aktualizujemy ADMIN_USERS tak aby bylo w miare swieze - glowna baza admin users jest baza LDAP!
					ZAP_SQL("insert ignore into ADMIN_USERS (`ID`,`A_STATUS`,`ADM_ACCOUNT`,`ADM_ADMIN_LEVEL`,`ADM_NAME`) values ('".$info[0]['uidnumber'][0]."','NORMAL','".addslashes($ADM_ACCOUNT)."','5','".$info[0]['cn'][0]."')");
					ZAP_SQL("update ADMIN_USERS set ADM_PASSWD=md5('".addslashes($ADM_PASSWD)."'),ADM_OTHER_INFO='".$info[0]['mail'][0]."' , ADM_ACCOUNT='".addslashes($ADM_ACCOUNT)."' , ADM_NAME='".$info[0]['cn'][0]."' where ADM_ACCOUNT='".ADM_ACCOUNT."'");
					
						
						// SQL_WIEV();
						//echo "Inicjalizuje USERS_COLUMN_INIT() dla admin level ".$_SESSION['ADM_ADMIN_LEVEL'];
					//	SEF('USERS_COLUMN_INIT');
					//	USERS_COLUMN_INIT();
				
				   //wyszukuje pelne nazwy uzytkownikow
				    $dn = "cn=users,".$dc; // also tried DC=example,DC=co,DC=uk
			        $filter="objectClass=posixAccount";
			        $justthese = array("uid","cn","apple-generateduid");
			    	$sr=ldap_search($ldapconn, $dn, $filter, $justthese);
			        $info = ldap_get_entries($ldapconn, $sr);
						for($i=0;$i<$info['count'];$i++) {	
							 $_SESSION['AUTH_LDAP_CLIENT__LDAP_USERS_NAMES'][$info[$i]['uid'][0]]=array('apple-generateduid'=>$info[$i]['apple-generateduid'][0],'cn'=>$info[$i]['cn'][0]); 
							 if(ereg("\[[0-9]*\]",$info[$i]['cn'][0])) {
							 	$_SESSION['AUTH_LDAP_CLIENT__LDAP_USERS_NAMES'][$info[$i]['uid'][0]]['ID_ZASOB']=preg_replace('/(.*\[+)([0-9]*+)(\].*+)/i', '\2', $info[$i]['cn'][0]);
							 }
						
						}
					DEBUG_S(3,'Usernames',array($info,$_SESSION['AUTH_LDAP_CLIENT__LDAP_USERS_NAMES']),__FILE__,__FUNCTION__,__LINE__);				
					
					
							    	
			    	//Szukamy jakie sa dostepne grupy w systemie : 
			    	$dn = "cn=groups,".$dc; // also tried DC=example,DC=co,DC=uk
			        $filter="objectClass=posixGroup";
			        $justthese = array("cn","memberUid","apple-group-nestedgroup","apple-generateduid");
			    	
					//$dn = "cn=users,".$dc; // also tried DC=example,DC=co,DC=uk
			    	
			        //$filter="(uid=".$ADM_ACCOUNT.")";
			        //$justthese = array("uid", "givenName", "mail","*");
			    				
			        $sr=ldap_search($ldapconn, $dn, $filter, $justthese);
			        $info = ldap_get_entries($ldapconn, $sr);
			        //dodanie pustej grupy:
			        $_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS'][''][]='';
					 for($i=0;$i<$info['count'];$i++) {	
					 	if($info[$i]['memberuid']['count']==0) {
					 	    $_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS'][$info[$i]['cn'][0]]=array();
					 	    $_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS_NESTED_NAME'][$info[$i]['apple-generateduid'][0]]=$info[$i]['cn'][0]; 
					 	}
						for($member=0;$member<$info[$i]['memberuid']['count'];$member++) {
					       $_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS'][$info[$i]['cn'][0]][]=$info[$i]['memberuid'][$member]; 
					       $_SESSION['AUTH_LDAP_CLIENT__LDAP_USERS'][$info[$i]['memberuid'][$member]][]=$info[$i]['cn'][0]; 
					       $_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS_NESTED_NAME'][$info[$i]['apple-generateduid'][0]]=$info[$i]['cn'][0]; 
							ZAP_SQL("insert ignore into ADMIN_USERS (`ID`,`A_STATUS`,`ADM_ACCOUNT`,`ADM_TECH_WORKER`,`ADM_ADMIN_LEVEL`,`ADM_NAME`) values ('','NORMAL','".addslashes($info[$i]['memberuid'][$member])."','YES' ,'5','".$_SESSION['AUTH_LDAP_CLIENT__LDAP_USERS_NAMES'][$info[$i]['memberuid'][$member]]['cn']."')");
					    }
					    
					    if(isset($info[$i]['apple-group-nestedgroup']['count'])) //errory z braku zmiennej
					    for($member=0;$member<$info[$i]['apple-group-nestedgroup']['count'];$member++) {
					       $_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS_NESTED'][$info[$i]['apple-generateduid'][0]][]=$info[$i]['apple-group-nestedgroup'][$member]; 
					    }


					    }
					
					if(!empty($_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS_NESTED'])) { //jezeli nie jest puste, znaczy, ze sa NESTED_GROUPS bedziemy dodawac dla kazdej nested groups userow do grupy
							foreach($_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS_NESTED'] as $GUID=>$NESTED_A) {
								foreach($NESTED_A as $NESTED) {
									//echo "<br>".$_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS_NESTED_NAME'][$GUID];
									//echo " -- ".$NGUID." looking from ".$_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS_NESTED_NAME'][$NESTED]." (".$NESTED.") ";
										    foreach($_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS'][$_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS_NESTED_NAME'][$NESTED]] as $USERNAME) {
									//echo " -- = ".$USERNAME;										    
										    	if(!in_array($USERNAME,$_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS'][$_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS_NESTED_NAME'][$GUID]]))	$_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS'][$_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS_NESTED_NAME'][$GUID]][]=$USERNAME; 
					      						if(!in_array($_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS_NESTED_NAME'][$GUID],$_SESSION['AUTH_LDAP_CLIENT__LDAP_USERS'][$USERNAME])) $_SESSION['AUTH_LDAP_CLIENT__LDAP_USERS'][$USERNAME][]=$_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS_NESTED_NAME'][$GUID];
					     					}
								}	
							}
					 }
					
					foreach($_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS'] as $GROUP_NUMBER_HYPEN_NAME=>$USERS_ARR ) {

							$GROUP=array();
							//foreach($GROUPS as $GROUP_NUMBER_HYPEN_NAME) {
								$GROUP_NUMBER_HYPEN_NAME2=str_replace('-', '_',$GROUP_NUMBER_HYPEN_NAME );
								list($ID_ZASOB,$REST)=explode('_', $GROUP_NUMBER_HYPEN_NAME2);
								if(isset($REST)&& preg_match("/[0-9]/", $ID_ZASOB)) {
									 $GROUP[]=$ID_ZASOB; //jezeli jest jakas grupa typu 1234_opis_costam - inne ignroujemy
								//	 echo " ze stringa:(".$GROUP_NUMBER_HYPEN_NAME.") *** dodalem ".$ID_ZASOB." ** ";
									$_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS_ID_NAME'][$ID_ZASOB]=$GROUP_NUMBER_HYPEN_NAME;
										$sql="insert ignore into LDAP_GROUPS (ID,NAME) values ('".$ID_ZASOB."','".$GROUP_NUMBER_HYPEN_NAME."') ";
//								echo "<br>sql:".$sql;
								DB::query($sql);
								}
							//}
					}
					foreach($_SESSION['AUTH_LDAP_CLIENT__LDAP_USERS'] as $USERNAME=>$GROUPS ) {
							$GROUP=array();
							foreach($GROUPS as $GROUP_NUMBER_HYPEN_NAME) {
								$GROUP_NUMBER_HYPEN_NAME2=str_replace('-', '_',$GROUP_NUMBER_HYPEN_NAME );
								list($ID_ZASOB,$REST)=explode('_', $GROUP_NUMBER_HYPEN_NAME2);
								if(!empty($REST)&& preg_match("/[0-9]/", $ID_ZASOB)) {
									 $GROUP[]=$ID_ZASOB; //jezeli jest jakas grupa typu 1234_opis_costam - inne ignroujemy
									// echo " ze stringa:(".$GROUP_NUMBER_HYPEN_NAME.") *** dodalem ".$ID_ZASOB." ** ";
							//		$_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS_ID_NAME'][$ID_ZASOB]=$GROUP_NUMBER_HYPEN_NAME;
								}
							}
						
			    			//echo "<br>Grupa to (".$REST.")"; print_r($GROUP);
			    			if(!empty($GROUP)) { //jezeli jest jakas grupa typu 1234_opis_costam - inne ignroujemy
			    		 					$sql="select CRM_AUTH_PROFILE.ID_ZASOB from CRM_AUTH_PROFILE 
			    		 					left join ADMIN_USERS on ( ADMIN_USERS.ID=CRM_AUTH_PROFILE.REMOTE_ID and CRM_AUTH_PROFILE.REMOTE_TABLE='ADMIN_USERS')
			    		 					where ADMIN_USERS.ADM_ACCOUNT='".$USERNAME."' and CRM_AUTH_PROFILE.ID_ZASOB not in ('".implode("','",$GROUP)."')   ";
			    		 		//echo "***".$sql."***";
			    		 		$res=DB::query($sql);
								if(DB::num_rows($res)>0) {
								$ERROR[]="ERROR UPRAWNIEN - uzytkownik ".$USERNAME." posiada wiecej uprawnien niz w serwerze LDAP! Oto nadmiarowe powiazania do zasobow:";
									 while($h=DB::fetch($res)) {
									 	$ERROR[]=$h->ID_ZASOB.",";
									 }
									// $ERROR[]="</font>";
								}
								$res=DB::query("select CRM_AUTH_PROFILE.ID_ZASOB from CRM_AUTH_PROFILE 
			    		 					left join ADMIN_USERS on ( ADMIN_USERS.ID=CRM_AUTH_PROFILE.REMOTE_ID and CRM_AUTH_PROFILE.REMOTE_TABLE='ADMIN_USERS')
			    		 					where ADMIN_USERS.ADM_ACCOUNT='".$USERNAME."' and CRM_AUTH_PROFILE.ID_ZASOB  in ('".implode("','",$GROUP)."')   ");
								if((DB::num_rows($res)<count($GROUP) ) &&!empty($USERNAME)) {
								
										//echo "<br><font color=red>ERROR UPRAWNIEN - uzytkownik ".$USERNAME." posiada mniej uprawnien (".count($GROUP).") niz w serwerze LDAP (".DB::num_rows($res).") !";
										foreach($GROUP as $IND=>$GR) {
											while($h=DB::fetch($res)) {
											 	if($GR==$h->ID_ZASOB) unset($GROUP[$IND]);
											 }
										}
										foreach($GROUP as $IND=>$GR) {
											//echo "<B> (nie robie tego z uwagi na SYNC) DODAJE UPRAWNIENIE DO ZASOBU ".$GR." </B>,";
											$sql="insert ignore into CRM_AUTH_PROFILE (ID_ZASOB,REMOTE_TABLE,REMOTE_ID,A_STATUS,A_RECORD_CREATE_DATE,A_RECORD_CREATE_AUTHOR) 
															select '".$GR."','ADMIN_USERS',ID,'WAITING',now(),'superedit-AUTH_LDAP_CLIENT.php' from ADMIN_USERS where ADM_ACCOUNT='".$USERNAME."' limit 1 ;
											 ";
										//	$res=DB::query($sql);

										}
										echo "</font>";
								}
			    		   }
			    	}
			    	if($_SESSION['ADM_ADMIN_LEVEL']=='0') DEBUG_S(-3,'ERROR UPRAWNIEN',array($ERROR),__FILE__,__FUNCTION__,__LINE__);
			    	
			    	$AUTH_LDAP_CLIENT__LDAP_GROUPS_ID_NAME=$_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS_ID_NAME'];
			    	$res=DB::query("select ID,`TYPE`,`DESC` from CRM_LISTA_ZASOBOW where A_STATUS!='DELETED' and  `TYPE` in ('STANOWISKO','DZIAL','PODMIOT') and PARENT_ID!='-1' ");
					while($h=DB::fetch($res)) {
						if(!isset($_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS_ID_NAME'][$h->ID])) { 
							echo "<font size=-3> Brak grupy [".$h->ID."] ".$h->TYPE." ".$h->DESC." , </font>";
							if(in_array($ADM_ACCOUNT,$_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS']['admin'])) {
							   $BAD_SIGNS = array(" ", "/", "\\", "!","(",")");
							   if($h->ID>1000) $PrimaryGroupID=$h->ID;
							    else $PrimaryGroupID="99".$h->ID;
							   $command1="dscl -u ".$ADM_ACCOUNT." -P ".$ADM_PASSWD." /LDAPv3/127.0.0.1 -create /Groups/".$h->ID."_".str_replace($_SESSION['CONFIG']['BAD_FILE_SIGNS_LETTERS'],$_SESSION['CONFIG']['OK_FILE_SIGNS_LETTERS'],str_replace($BAD_SIGNS,"_",substr($h->DESC,0,40)))." PrimaryGroupID ".$PrimaryGroupID."";
							   $command2="dscl -u ".$ADM_ACCOUNT." -P ".$ADM_PASSWD." /LDAPv3/127.0.0.1 -create /Groups/".$h->ID."_".str_replace($_SESSION['CONFIG']['BAD_FILE_SIGNS_LETTERS'],$_SESSION['CONFIG']['OK_FILE_SIGNS_LETTERS'],str_replace($BAD_SIGNS,"_",substr($h->DESC,0,40)))." RealName \"[".$h->ID."] ".$h->TYPE." ".substr($h->DESC,0,50)."\" ";
							   $return_dscl1=system($command1);
							   $return_dscl2=system($command2);

							   echo "\n<br><font size=-2>".$command1." return : ".$return_dscl1."</font>";
							   echo "\n<br><font size=-2>".$command2." return : ".$return_dscl2."</font>";
								flush();
							   $AKTUALIZOWALEM=true;
							}
							
							$BRAKI_W_LDAP=true;
						} else unset($AUTH_LDAP_CLIENT__LDAP_GROUPS_ID_NAME[$h->ID]);
					}
			    	
			    	foreach($AUTH_LDAP_CLIENT__LDAP_GROUPS_ID_NAME as $BRAK_W_SE) {
			    			echo "<br><font size=-3> Brak grupy w SE  ".$BRAK_W_SE."</font>";
			    	}
					
					if(isset($BRAKI_W_LDAP)&&(!isset($AKTUALIZOWALEM))) {
						//echo "<font color=red size=-2><br>Zaloguj sie na jedno z kont aby zsynchronizowac grupy LDAP : (".implode(',',$_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS']['admin']).")</font>";
						
					}




					if(in_array($ADM_ACCOUNT,$_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS']['admin'])) {

							//szukamy jakie zasoby sa do sharowania SHARED_IMAP_MAILBOX
							
							$sql="select cz.ID, cz.PARENT_ID from CRM_LISTA_ZASOBOW as cz where cz.`TYPE`='SHARED_IMAP_MAILBOX'
							 union select cz.ID, cz.PARENT_ID_ACCESS as PARENT_ID from CRM_LISTA_ZASOBOW as cz where cz.`TYPE`='SHARED_IMAP_MAILBOX' and cz.PARENT_ID_ACCESS like '%_'
							";
							$res=DB::query($sql);
							SEF('APPLE_IMAP_SHARED_FOLDER_CONTROL');
							while($h=DB::fetch($res)) {//dla kazdego znalezionego konta IMAP do sharowania
								if(strstr($h->PARENT_ID,',')) { 
									   $exploded=explode(',',$h->PARENT_ID);
									   foreach($exploded as $piece) {
									   		$share_arr[]=array($h->ID,$piece);
									   }
								} else $share_arr[]=array($h->ID,$h->PARENT_ID);
							}
							
							//print_r($share_arr);
							foreach($share_arr as $arr) {
								//echo "<br>Stanowisko do share to ".$arr[0]." to ".$arr[1];	
								//wykrywam nazwe uzytkownika source - moze byc kilku
								foreach($_SESSION['AUTH_LDAP_CLIENT__LDAP_USERS_NAMES'] as $username=>$user_arr) {
									 if($arr[0]==$user_arr['ID_ZASOB']) {
									 // echo "<br>Znalazlem src usera do udostepnienia:".$arr[0]." ".$username." jego UID to ".$user_arr['apple-generateduid'];
									  	//teraz szukam komu udostepnic - powinno byc parent ID - szukam grupy PARENT_ID
									  	//echo "<br>306(".$h->PARENT_ID."):".$_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS_ID_NAME'][$h->PARENT_ID]."AAA";
									  	$grupa_remote_to_share_to=$_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS_ID_NAME'][$arr[1]];
									//  	echo " Grupa to share to ".$grupa_remote_to_share_to;
									  	//array_search($_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS_ID_NAME'][$h->PARENT_ID],$_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS_NESTED_NAME']);
									 	foreach($_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS'][$grupa_remote_to_share_to] as $destuser) {
									 		 APPLE_IMAP_SHARED_FOLDER_CONTROL($user_arr['apple-generateduid'],$_SESSION['AUTH_LDAP_CLIENT__LDAP_USERS_NAMES'][$destuser]['apple-generateduid']);
									 	
									 	}
									 }
								}
								
							}
					}



			    	DEBUG_S(3,'LDAP Groups',array($_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS'],$_SESSION['AUTH_LDAP_CLIENT__LDAP_USERS'],$_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS_NESTED'],$_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS_NESTED_NAME'],$_SESSION['AUTH_LDAP_CLIENT__LDAP_GROUPS_ID_NAME']),__FILE__,__FUNCTION__,__LINE__);


			    	}
			    
			
			}





}


//die('dupa');



session_start();


//echo session_id();

//using ldap bind anonymously

// connect to ldap server
	//generate cn-name for LDAP_SERVER auth
	

?>
