<?php

/**
 * Synchronizacja kont z bazy danych do servera LDAP
 * 
 * $rcmail_config['address_book_type'] = 'sql';
$rcmail_config['ldap_public'] = array();
$rcmail_config['ldap_public']['localhost'] = array(
  'name' => 'localhost',
  'hosts' => array('127.0.0.1'),
  'port' => 389,
  'base_dn'       => 'cn=users,dc=biall,dc=pl',
  'search_base_dn' => '',
  'required_fields' => array('cn', 'sn', 'mail'),
  'filter'        => '(&(!(uid=_*))(mail=*@*))',
  'search_dn_default' => '',
  'LDAP_Object_Classes' => array('top', 'inetOrgPerson'),
  'search_fields' => array('givenName', 'cn', 'sn', 'mail'), 
  'fieldmap' => array(
 // Roundcube  => LDAP
 'name'        => 'cn',
 'surname'     => 'sn',
 'firstname'   => 'givenName',
 'email'       => 'mail',
 'phone:work'  => 'telephoneNumber'
 ),
  'LDAP_rdn'      => 'mail',
  'ldap_version'  => 3,  
  'scope'         => 'sub',      
 'fuzzy_search'  => true
);
 * 
 */
function SYNC_LDAP_PERMS() {

	SE_Layout::menu();

	echo '<div class="container">';
	echo '<h1>' . "Synchronizacja uprawnień do bazy LDAP" . '</h1>';

	$DBG = ('1' == V::get('DBG_SLP', '', $_GET));

	if ('' !== ($userName = V::get('syncUsr', '', $_GET))) {// TEST
		Lib::loadClass('UserStorageFactory');
		$usrStorageDB = UserStorageFactory::getStorage('DB');
		$usrStorageLdap = UserStorageFactory::getStorage('MacOSX');

		if (!$usrStorageDB || !$usrStorageLdap) {
			echo '<p>Error storage not exists</p>';
		}
		else {

			echo '<h4>Synchronizacja użytkownika '.$userName.'</h4>';
			$usrFrom = $usrStorageDB->getUser($userName);
			if ($usrFrom) {
				Lib::loadClass('ProcesHelper');
				$zasobUprawnienia = ProcesHelper::getZasobTableID('CRM_AUTH_PROFILE');
				if ($zasobUprawnienia > 0) {
					echo '<p>' . "Ustal stanowisko: ";
					echo '<a href="index.php?MENU_INIT=USER_ADD_GROUP&usrLogin='.$usrFrom->login.'">ustal stanowisko</a>';
					echo '</p>';
				}
			}

			Lib::loadClass('SyncUsers');
			$synUsers = new SyncUsers($usrStorageDB, $usrStorageLdap);

			$syncTodoList = $synUsers->getSyncUserTodoList($userName, $syncGroups = true, $syncDisabled = true);
			?>
			<?php if (empty($syncTodoList)) : ?>
				<div class="alert alert-info">Brak zadań do wykonania - użytkownik zsynchronizowany</div>
			<?php else : ?>
				<div class="well">
					<p>Lista zadań do wykonania:</p>
					<ul>
						<?php foreach ($syncTodoList as $vTask) : ?>
							<li><?php echo $vTask; ?></li>
						<?php endforeach; ?>
					</ul>
				</div>
			<?php endif; ?>
			<?php

			if ('1' == V::get('_runSync', '', $_POST)) {
				$synced = $synUsers->syncUser($userName, $syncGroups = true, $syncDisabled = true);
				if (!$synced) {
					?>
					<div class="alert alert-error">
						Nie udało się zsynchronizować uprawnień użytkownika <?php echo $userName; ?>.
					</div>
					<?php
					echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;display:none;">errors: (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($synUsers->getErrorsMsgListWithDbg());echo'</pre>';
				}
				else {
					?>
					<div class="alert alert-success">
						Synchronizacja uprawnień użytkownika <?php echo $userName; ?> zakończona powodzeniem.
					</div>
					<?php
				}
			}
			else {
				?>
				<form action="" method="POST">
					<input type="hidden" name="_runSync" value="1">
					<input type="submit" value="Synchronizuj" class="btn btn-primary btn-big">
				</form>
				<?php
			}
		}

		return;
	}

	if ('' !== ($userName = V::get('syncUsrDisabled', '', $_GET))) {// TEST
		Lib::loadClass('UserStorageFactory');
		$usrStorageDB = UserStorageFactory::getStorage('DB');
		$usrStorageLdap = UserStorageFactory::getStorage('MacOSX');

		if (!$usrStorageDB || !$usrStorageLdap) {
			echo '<p>Error storage not exists</p>';
		}
		else {

			Lib::loadClass('SyncUsers');
			$synUsers = new SyncUsers($usrStorageDB, $usrStorageLdap);

			$synced = $synUsers->syncDisabled($userName);
			if (!$synced) {
				?>
				<div class="alert alert-error">
					Nie udało się zsynchronizować uprawnień użytkownika <?php echo $userName; ?>.
				</div>
				<?php
				echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;display:none;">errors: (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($synUsers->getErrorsMsgListWithDbg());echo'</pre>';
			}
			else {
				?>
				<div class="alert alert-success">
					Synchronizacja uprawnień użytkownika <?php echo $userName; ?> zakończona powodzeniem.
				</div>
				<?php
			}
		}
		return;
	}

	if ('checkGroups' == V::get('TEST', '', $_GET)) {
		$DBG = 1;
		$zasobyGroupsTreeRoot = UsersHelper::getGroupsTreeRoot();
		$zasobyGroups = UsersHelper::getGroupsTreeItems();
		if($DBG){
			if($DBG > 1){
				echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">zasobyGroups (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($zasobyGroups);echo'</pre>';
				echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">zasobyGroupsTreeRoot (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($zasobyGroupsTreeRoot);echo'</pre>';
			}
			// print tree stanowiska
			function tmpPrintTreeItem($vGroup) {
				if ('' !== ($userName = V::get('userName', '', $_GET))) {
					$userGroups = UsersHelper::getGroupByUserName($userName);
				}

				if (is_array($userGroups) && !empty($userGroups) && array_key_exists($vGroup->ID, $userGroups)) {
					echo '<span style="color:red">' . "[{$vGroup->ID}] {$vGroup->TYPE} {$vGroup->DESC}" . '</span>';
				} else if (in_array($vGroup->TYPE, array('DZIAL', 'PODMIOT'))) {
					echo '<span style="color:silver">' . "[{$vGroup->ID}] {$vGroup->TYPE} {$vGroup->DESC}" . '</span>';
				} else {
					echo "[{$vGroup->ID}] {$vGroup->TYPE} {$vGroup->DESC}";
				}
			}

			function tmpPrintTreeRec($treeIds, $items, $callback) {
				echo '<ul>';
				foreach ($treeIds as $vID) {
					$vGroup = $items[$vID];
					echo '<li>';
						$callback($vGroup);
						if (!empty($vGroup->sub)) {
							tmpPrintTreeRec($vGroup->sub, $items, $callback);
						}
					echo '</li>';
				}
				echo '</ul>';
			}
			tmpPrintTreeRec($zasobyGroupsTreeRoot, $zasobyGroups, tmpPrintTreeItem);
			// tree flat
		}

		$groupsLdapAll = UsersLdapHelper::getGroupsAll($allAttrs = false);
		if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">groupsLdapAll (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($groupsLdapAll);echo'</pre>';}
	}

	if (0 < ($syncGroupID = V::get('syncGroup', 0, $_GET, 'int'))) {
		Lib::loadClass('UserStorageFactory');
		$usrStorageDB = UserStorageFactory::getStorage('DB');
		$usrStorageLdap = UserStorageFactory::getStorage('MacOSX');

		if (!$usrStorageDB || !$usrStorageLdap) {
			echo '<div class="alert alert-error">' . "Error storage not exists" . '</div>';
		}
		else {

			$groupFrom = $usrStorageDB->getGroup($syncGroupID);
			if (!$groupFrom) {
				$db = DB::getDB();
				$zasob = $db->get_by_id('CRM_LISTA_ZASOBOW', $syncGroupID);
				if (!$zasob) {
					echo '<div class="alert alert-error">' . "Zasób {$syncGroupID} nie istnieje" . '</div>';
				} else {
					echo '<div class="alert alert-error">' . "Zasób {$syncGroupID} nie jest grupą tylko {$zasob->TYPE}" . '</div>';
				}
			}
			else {
				?>
				<h4>Synchronizacja grupy: <?php echo $syncGroupID; ?></h4>
				<p>Ustal powiązania między grupami uprawnień - <a href="index.php?MENU_INIT=GROUP_ADD_NESTEDGROUPS&groupID=<?php echo $syncGroupID; ?>">grupy uprawnień</a></p>
				<?php
				Lib::loadClass('SyncUsers');
				$synUsers = new SyncUsers($usrStorageDB, $usrStorageLdap);

				$syncTodoList = $synUsers->getSyncGroupTodoList($syncGroupID, $syncNestedGroups = true);
				?>
				<?php if (empty($syncTodoList)) : ?>
					<div class="alert alert-info">Brak zadań do wykonania - grupa zsynchronizowana</div>
				<?php else : ?>
					<div class="well">
						<p>Lista zadań do wykonania:</p>
						<ul>
							<?php foreach ($syncTodoList as $vTask) : ?>
								<li><?php echo $vTask; ?></li>
							<?php endforeach; ?>
						</ul>
					</div>
				<?php endif; ?>
				<?php

				if ('1' == V::get('_runSync', '', $_POST)) {
					$synced = $synUsers->syncGroup($syncGroupID, $syncNestedGroups = true);
					if (!$synced) {
						?>
						<div class="alert alert-error">
							Nie udało się zsynchronizować grupy [<?php echo $syncGroupID; ?>].
						</div>
						<?php
						echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;display:none;">errors: (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($synUsers->getErrorsMsgListWithDbg());echo'</pre>';
					}
					else {
						?>
						<div class="alert alert-success">
							Synchronizacja grupy [<?php echo $syncGroupID; ?>] zakończona powodzeniem.
						</div>
						<?php
					}
				}
				else {
					?>
					<form action="" method="POST">
						<input type="hidden" name="_runSync" value="1">
						<input type="submit" value="Synchronizuj" class="btn btn-primary btn-big">
					</form>
					<?php
				}
			}
		}

		return;
	}

	if ('123' !== V::get('TEST', '', $_GET)) {// below is a test
		?>
			<div class="alert alert-error">
				<p>Brak dostępu</p>
			</div>
		<?php
		return;
	}



	Lib::loadClass('UsersHelper');
	Lib::loadClass('UsersLdapHelper');
	Lib::loadClass('LDAP');
	$ldap = LDAP::getInstance();
	if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">ldap (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($ldap);echo'</pre>';}

	if ('createLdapUsr' == V::get('task', '', $_GET)) {
		if ('' !== ($userName = V::get('checkUser', '', $_GET))) {
			$usrLdap = UsersLdapHelper::getUser($userName, true);
			$usrDB = UsersHelper::getUserByName($userName);

			if ($usrDB && !$usrLdap) {
				?>
				<div style="border:1px solid green;">OK jest DB i brak LDAP
					<?php
					Lib::loadClass('MacOSX');
					$mac = MacOSX::getInstance();

					$created = $mac->createUser($usrDB->ADM_ACCOUNT, $usrDB->EMPLOYEE_TYPE, $usrDB->ADM_NAME, $usrDB->EMAIL, $usrDB->ADM_PASSWD);
					if ($created) {
						$db = DB::getDB();
						$sql = "update `ADMIN_USERS` set `A_SYNC_LDAP_DATE`=NOW() where `ID`='{$usrDB->ID}'; ";
						$db->query($sql);
					}
					?>
				</div>
				<?php
			} else {
				echo '<p>Error: TODO (L.' . __LINE__ . ') ???</p>';
			}

		}
	}

	if ('' !== ($userName = V::get('checkUser', '', $_GET))) {
		// checkUser
		$usrLdap = UsersLdapHelper::getUser($userName, true);

		$usrDB = UsersHelper::getUserByName($userName);

		?>
		<table style="width:100%">
			<tr>
				<td style="width:50%;vertical-align:top;">
					<?php echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">usrDB (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($usrDB);echo'</pre>'; ?>
				</td>
				<td style="width:50%;vertical-align:top;">
					<?php echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">usrLdap (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($usrLdap);echo'</pre>'; ?>
				</td>
			</tr>
		</table>
		<?php

			Lib::loadClass('MacOSX');
			$mac = MacOSX::getInstance();
			$sysGroups = $mac->getUserGroups($userName);
			echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sysGroups (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sysGroups);echo'</pre>';

			if ($usrDB && $usrLdap) {
				echo '<p>OK jest DB i LDAP</p>';
			} else if (!$usrDB) {
				echo '<p>Brak DB</p>';
			} else if (!$usrLdap) {
				?>
				<p>Brak LDAP
					<a href="index.php?MENU_INIT=SYNC_LDAP_PERMS&checkUser=<?php echo $userName; ?>&task=createLdapUsr">utwórz usera ldap na podstawie danych w bazie</a>
				</p>
				<?php
			}

		if (V::get('syncUser', '', $_GET) > 0) {
			$errorMsg = '';
			if (!$ldap->bindDiradmin($errorMsg)) {
				echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error: cant bind as diradmin (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($errorMsg);echo'</pre>';
			} else {
				$attr = array();
				$attr['telephoneNumber'] = $usrDB->ADM_PHONE;
				$ldap->mod_replace($userName, $attr);

				//$attr = array();
				//$attr['homePhone'] = $usrDB->ADM_PHONE;
				//$ret = $ldap->mod_del($userName, $attr);
			}
		}
	}

	if ('' !== ($userName = V::get('userName', '', $_GET))) {
		$ldapUser = array();
		$filter = (false !== strpos($userName, '@'))? "(mail={$userName})" : "(uid={$userName})";
		//$filter = "cn=*";// show all ldap accounts
		$justthese = array();//array("uid", "givenName", "mail", "*");
		$res = $ldap->search($filter, 'cn=users', $justthese);
		if ($ldap->count_entries($res) > 0) {
			$entry = $ldap->first_entry($res);
			if ($entry) {
				$ldapUser['user_dn'] = $ldap->get_dn($entry);

				$val = $ldap->get_values($entry, 'uid');
				$ldapUser['uid'] = $val[0];
				$val = $ldap->get_values($entry, 'mail');
				$ldapUser['mail'] = $val[0];
				$val = $ldap->get_values($entry, 'cn');
				$ldapUser['cn'] = $val[0];
			} else {
				echo 'Login nie istnieje';
				return false;
			}
		}
if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">ldapUser (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($ldapUser);echo'</pre>';}

		$userLdapGroups = UsersLdapHelper::getUserGroups($userName);
		$userGroups = UsersHelper::getGroupByUserName($userName);

		$gidNumbers = array();
		if (!empty($userLdapGroups)) {
			foreach ($userLdapGroups as $vLdapGroup) {
				$gidNumbers[] = $vLdapGroup->gidNumber;
			}
		}
		$groupsAll = UsersHelper::getGroupsByLdapGids($gidNumbers);
if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">groupsAll (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($groupsAll);echo'</pre>';}

		$zasobyGroupsTreeRoot = UsersHelper::getGroupsTreeRoot();
		$zasobyGroups = UsersHelper::getGroupsTreeItems();
if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">treeZasoby (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($treeZasoby);echo'</pre>';}
if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">zasobyGroups (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($zasobyGroups);echo'</pre>';}
if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">zasobyGroupsTreeRoot (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($zasobyGroupsTreeRoot);echo'</pre>';}
		// print tree stanowiska
		function tmpPrintTreeItem($vGroup) {
			if ('' !== ($userName = V::get('userName', '', $_GET))) {
				$userGroups = UsersHelper::getGroupByUserName($userName);
			}

			if (array_key_exists($vGroup->ID, $userGroups)) {
				echo '<span style="color:red">' . "[{$vGroup->ID}] {$vGroup->TYPE} {$vGroup->DESC}" . '</span>';
			} else if (in_array($vGroup->TYPE, array('DZIAL', 'PODMIOT'))) {
				echo '<span style="color:silver">' . "[{$vGroup->ID}] {$vGroup->TYPE} {$vGroup->DESC}" . '</span>';
			} else {
				echo "[{$vGroup->ID}] {$vGroup->TYPE} {$vGroup->DESC}";
			}
		}

		function tmpPrintTreeRec($treeIds, $items, $callback) {
			echo '<ul>';
			foreach ($treeIds as $vID) {
				$vGroup = $items[$vID];
				echo '<li>';
					$callback($vGroup);
					if (!empty($vGroup->sub)) {
						tmpPrintTreeRec($vGroup->sub, $items, $callback);
					}
				echo '</li>';
			}
			echo '</ul>';
		}
		tmpPrintTreeRec($zasobyGroupsTreeRoot, $zasobyGroups, tmpPrintTreeItem);
		// tree flat

		?>
		<table>
			<tr><th>LDAP Groups (<?php echo $userName; ?>)</th><th>Zasoby Groups (<?php echo $userName; ?>)</th></tr>
			<tr>
				<td style="width:50%">
					<select size="5" class="span5">
					<?php $total = 0; foreach ($userLdapGroups as $vLDAPGroup) : ?>
						<?php if (true) : $total += 1; ?>
							<option value="<?php echo $vLDAPGroup->gidNumber; ?>"><?php echo "[{$vLDAPGroup->gidNumber}] {$vLDAPGroup->cn}"; ?></option>
						<?php endif; ?>
					<?php endforeach; ?>
					</select>
					<?php echo $total; ?>
				</td>
				<td>
					<select size="5" class="span5">
					<?php $total = 0; foreach ($userGroups as $vGroup) : ?>
						<?php if (true) : $total += 1; ?>
							<option value="<?php echo $vGroup->ID; ?>"><?php echo "[{$vGroup->ID}/{$vGroup->A_LDAP_GID}] {$vGroup->TYPE} {$vGroup->DESC}"; ?></option>
						<?php endif; ?>
					<?php endforeach; ?>
					</select>
					<?php echo $total; ?>
				</td>
			</tr>
		</table>
		<?php
	}

	if (1) {
		if (V::get('groups_connect', '', $_POST)) {
			$ldap_gid = V::get('ldap_gid', 0, $_POST);
			$zasob_id = V::get('zasob_id', 0, $_POST);
			if ($ldap_gid > 0 && $zasob_id > 0) {
				$sqlObj = new stdClass();
				$sqlObj->ID = $zasob_id;
				$sqlObj->A_LDAP_GID = $ldap_gid;
				$db = DB::getDB();
				$ret = $db->UPDATE_OBJ('CRM_LISTA_ZASOBOW', $sqlObj);

				if ($ret > 0) {
					echo '<div class="alert alert-success">';
						echo "Rekord zapisany pomyślnie";
					echo '</div>';
				} else if ($ret == 0) {
					echo '<div class="alert alert-info">';
						echo "Nie wprowadzono żadnych zmian";
					echo '</div>';
				} else {
					echo '<div class="alert alert-error">';
						echo "Database Error";
					echo '</div>';
					echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">db errors: (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($db->get_errors());echo'</pre>';
				}
			}
		}
		if (V::get('group_add', '', $_POST)) {
			$zasob_id = V::get('zasob_id', 0, $_POST);
			if ($zasob_id > 0) {
				$db = DB::getDB();
				$zasob = $db->get_by_id('CRM_LISTA_ZASOBOW', $zasob_id);
				if ($zasob) {
					if (in_array($zasob->TYPE, array('STANOWISKO', 'DZIAL', 'PODMIOT'))) {
						$ldap_gid = 0;
						// TODO: search for free GID
						$allLdapGroups = UsersLdapHelper::getGroupsAll();
						$ldapGids = array();
						foreach ($allLdapGroups as $vLdapGroup) {
							$ldapGids[] = $vLdapGroup->gidNumber;
						}
						$allGroups = UsersHelper::getGroupsAll();
						$dbGids = array_keys($allGroups);
						if ($zasob->ID > 1050 && !in_array($zasob->ID, $ldapGids)) {
							$ldap_gid = $zasob->ID;
						} else {
							for ($i = 10000 + $zasob->ID; $i < 20000 + $zasob->ID; $i++) {
								if (!in_array($i, $ldapGids) && !in_array($i, $dbGids)) {
									$ldap_gid = $i;
									break;
								}
							}
						}

						if ($ldap_gid) {
							$ldapUser = User::getName();
							$ldapPass = V::get('pass', '', $_POST);

							$newGroup = new stdClass();
							$newGroup->nameShort = mb_substr($zasob->DESC, 0, 50, 'utf8');
							$newGroup->name = $zasob->ID  . '_' .  $newGroup->nameShort;
							$newGroup->name = str_replace(' ' , '_', $newGroup->name);
							$pl_letters = array('ą', 'ć', 'ę', 'ł', 'ń', 'ó', 'ś', 'ź', 'ż', 'Ą', 'Ć', 'Ę', 'Ł', 'Ń', 'Ó', 'Ś', 'Ź', 'Ż');
							$en_letters = array('a', 'c', 'e', 'l', 'n', 'o', 's', 'z', 'z', 'A', 'C', 'E', 'L', 'N', 'O', 'S', 'Z', 'Z');
							$newGroup->name = str_replace($pl_letters , $en_letters, $newGroup->name);
							$newGroup->name = preg_replace('/[^a-z0-9-_]/i' , '', $newGroup->name);
							$newGroup->realName = "[{$zasob->ID}] {$zasob->TYPE} {$newGroup->nameShort}";
							$newGroup->gidNumber = $ldap_gid;
							$command1="dscl -u {$ldapUser} -P {$ldapPass} /LDAPv3/127.0.0.1 -create /Groups/{$newGroup->name} PrimaryGroupID {$newGroup->gidNumber}";
							$command2="dscl -u {$ldapUser} -P {$ldapPass} /LDAPv3/127.0.0.1 -create /Groups/{$newGroup->name} RealName \"{$newGroup->realName}\" ";
							$return_dscl1 = system($command1, $retVal1);
							$return_dscl2 = system($command2, $retVal2);
echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($command1, $command2));echo'</pre>';

							if ($retVal1 === 0 && $retVal2 === 0) {
								echo '<div class="alert alert-success">';
									echo "Grupę utworzono pomyślnie";
								echo '</div>';
								$sqlObj = new stdClass();
								$sqlObj->ID = $zasob->ID;
								$sqlObj->A_LDAP_GID = $newGroup->gidNumber;
								$db = DB::getDB();
								$ret = $db->UPDATE_OBJ('CRM_LISTA_ZASOBOW', $sqlObj);

								if ($ret > 0) {
									echo '<div class="alert alert-success">';
										echo "Grupę LDAP ({$newGroup->gidNumber}) przypisano pomyślnie do zasobu {$zasob->ID}";
									echo '</div>';
								} else if ($ret < 0) {
									echo '<div class="alert alert-error">';
										echo "Database Error";
									echo '</div>';
									echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">db errors: (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($db->get_errors());echo'</pre>';
								}
							}
							else {
								echo '<div class="alert alert-error">';
									echo "Error Cant create LDAP Group";
								echo '</div>';
							}
						} else {
							echo '<div class="alert alert-error">';
								echo "Error Cant find free Ldap GID";
							echo '</div>';
						}

						$zasob->DESC;// TODO: clean from bad chars
					} else {
						echo '<div class="alert alert-error">';
							echo "Error TYPE {$zasob->TYPE}";
						echo '</div>';
					}
				}
			}
		}

		Lib::loadClass('UsersHelper');
		$allLdapGroups = UsersLdapHelper::getGroupsAll();
		$allGroups = UsersHelper::getGroupsAll();
		$groupsConnected = array();
		foreach ($allGroups as $vGroup) {
			if ($vGroup->A_LDAP_GID > 0) {
				$groupsConnected[] = $vGroup->A_LDAP_GID;
			}
		}

		?>
		<table style="border-bottom:2px solid #eee;">
			<tr><th>All LDAP Groups</th><th>All Zasoby Groups</th></tr>
			<tr>
				<td style="width:50%">
						<select class="span5">
						<?php $total = 0; foreach ($allLdapGroups as $vLDAPGroup) : ?>
							<?php if (true) : $total += 1; ?>
								<option value="<?php echo $vLDAPGroup->gidNumber; ?>"><?php echo "[{$vLDAPGroup->gidNumber}] {$vLDAPGroup->cn}"; ?></option>
							<?php endif; ?>
						<?php endforeach; ?>
						</select>
						(<?php echo $total; ?>)
				</td>
				<td>
						<select class="span5">
						<?php $total = 0; foreach ($allGroups as $vGroup) : ?>
							<?php if (true) : $total += 1; ?>
								<option value="<?php echo $vGroup->ID; ?>"><?php echo "[{$vGroup->ID}] {$vGroup->TYPE} {$vGroup->DESC}"; ?></option>
							<?php endif; ?>
						<?php endforeach; ?>
						</select>
						(<?php echo $total; ?>)
				</td>
			</tr>
			<tr style="display:none">
				<td style="width:50%">
					<?php
echo'<pre style="max-height:200px;overflow:auto;border:1px solid yellow;text-align:left;">allLdapGroups('.count($allLdapGroups).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($allLdapGroups);echo'</pre>';
					?>
				</td>
				<td>
					<?php
echo'<pre style="max-height:200px;overflow:auto;border:1px solid yellow;text-align:left;">allGroups('.count($allGroups).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($allGroups);echo'</pre>';
					?>
				</td>
			</tr>
			<tr>
				<th colspan="2" style="border-top:2px solid #eee;">
					Połącz Zasoby z Grupami na serwerze LDAP
				</th>
			</tr>
			<tr>
				<td colspan="2">
					<div class="span10 offset2">
					<form class="form form-horizontal" method="post">
						<label for="zasob_id">Zasób: </label>
						<select name="zasob_id" class="span5">
							<option value=""> [ wybierz ] </option>
						<?php $total = 0; foreach ($allGroups as $vGroup) : ?>
							<?php if ($vGroup->A_LDAP_GID == 0) : $total += 1; ?>
								<option value="<?php echo $vGroup->ID; ?>"><?php echo "[{$vGroup->ID}] {$vGroup->TYPE} {$vGroup->DESC}"; ?></option>
							<?php endif; ?>
						<?php endforeach; ?>
						</select>
						(<?php echo $total; ?>)

						<input type="password" name="pass" placeholder="hasło" class="span2">
						<input type="submit" class="btn btn-primary" name="group_add" value="Utwórz grupę w LDAP">

						<label for="ldap_gid">Grupa LDAP: </label>
						<select name="ldap_gid" class="span5">
							<option value=""> [ wybierz ] </option>
						<?php $total = 0; foreach ($allLdapGroups as $vLDAPGroup) : ?>
							<?php if (!in_array($vLDAPGroup->gidNumber, $groupsConnected)) : $total += 1; ?>
								<option value="<?php echo $vLDAPGroup->gidNumber; ?>"><?php echo "[{$vLDAPGroup->gidNumber}] {$vLDAPGroup->cn}"; ?></option>
							<?php endif; ?>
						<?php endforeach; ?>
						</select>
						(<?php echo $total; ?>)

						<input type="submit" class="btn btn-primary" name="groups_connect" value="Połącz">
					</form>
					</div>
				</td>
			</tr>
		</table>
		<?php
	}

	if (1) {
		$allLdapUsers = UsersLdapHelper::getUsersAll();
		$allUsers = UsersHelper::getUsersAll();

		//if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">allLdapUsers (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($allLdapUsers);echo'</pre>';}

		// ldap.uid == db.ADM_ACCOUNT
		$usersDB = array();
		$usersLDAP = array();
		$usersConnected = array();
		foreach ($allUsers as $vDBUser) {
			$usersDB[] = $vDBUser->ADM_ACCOUNT;
		}
		foreach ($allLdapUsers as $vLDAPUser) {
			$usersLDAP[] = $vLDAPUser->uid;
		}
		// array czesc wspolna
		foreach ($usersDB as $vLogin) {
			if (in_array($vLogin, $usersLDAP)) {
				$usersConnected[] = $vLogin;
			}
		}
		//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$usersConnected (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($usersConnected);echo'</pre>';
		?>
		<table>
			<tr><th>LDAP Users (ok)</th><th>DB Users (ok)</th></tr>
			<tr>
				<td style="width:50%">
					<select class="span5">
					<?php $total = 0; foreach ($allLdapUsers as $vLDAPUser) : ?>
						<?php if (in_array($vLDAPUser->uid, $usersConnected)) : $total += 1; ?>
							<option value="<?php echo $vLDAPUser->uid; ?>"><?php echo "[{$vLDAPUser->uidNumber}] {$vLDAPUser->uid}: {$vLDAPUser->cn}"; ?></option>
						<?php endif; ?>
					<?php endforeach; ?>
					</select>
					<?php echo $total; ?>
				</td>
				<td>
					<form method="get">
						<select class="span4">
						<?php $total = 0; foreach ($allUsers as $vDBUser) : ?>
							<?php if (in_array($vDBUser->ADM_ACCOUNT, $usersConnected)) : $total += 1; ?>
								<option value="<?php echo $vDBUser->ADM_ACCOUNT; ?>"><?php echo "[{$vDBUser->ID}] {$vDBUser->ADM_ACCOUNT}: {$vDBUser->ADM_NAME}"; ?></option>
							<?php endif; ?>
						<?php endforeach; ?>
						</select>
						<?php echo $total; ?>
					</form>
				</td>
			</tr>
			<tr><th>LDAP Users (todo)</th><th>DB Users (todo)</th></tr>
			<tr>
				<td style="width:50%">
					<select size="10" class="span5">
					<?php $total = 0; foreach ($allLdapUsers as $vLDAPUser) : ?>
						<?php if (!in_array($vLDAPUser->uid, $usersConnected)) : $total += 1; ?>
							<option value="<?php echo $vLDAPUser->uid; ?>"><?php echo "[{$vLDAPUser->uidNumber}] {$vLDAPUser->uid}: {$vLDAPUser->cn}"; ?></option>
						<?php endif; ?>
					<?php endforeach; ?>
					</select>
					<?php echo $total; ?>
				</td>
				<td>
					<select size="10" class="span5">
					<?php $total = 0; foreach ($allUsers as $vDBUser) : ?>
						<?php if (!in_array($vDBUser->ADM_ACCOUNT, $usersConnected) && $vDBUser->ADM_ADMIN_LEVEL < 6) : $total += 1; ?>
							<option value="<?php echo $vDBUser->ADM_ACCOUNT; ?>"><?php echo "[{$vDBUser->ID}] {$vDBUser->ADM_ACCOUNT}: {$vDBUser->ADM_NAME} ({$vDBUser->A_STATUS}:{$vDBUser->ADM_ADMIN_LEVEL})"; ?></option>
						<?php endif; ?>
					<?php endforeach; ?>
					</select>
					<?php echo $total; ?>
				</td>
			</tr>
			<tr><th></th><th>konta bez możliwości zalogwania się</th></tr>
			<tr>
				<td style="width:50%">
				</td>
				<td>
					<select size="10" class="span5">
					<?php $total = 0; foreach ($allUsers as $vDBUser) : ?>
						<?php if (!in_array($vDBUser->ADM_ACCOUNT, $usersConnected) && $vDBUser->ADM_ADMIN_LEVEL == 6) : $total += 1; ?>
							<option value="<?php echo $vDBUser->ADM_ACCOUNT; ?>"><?php echo "[{$vDBUser->ID}] {$vDBUser->ADM_ACCOUNT}: {$vDBUser->ADM_NAME} ({$vDBUser->A_STATUS}:{$vDBUser->ADM_ADMIN_LEVEL})"; ?></option>
						<?php endif; ?>
					<?php endforeach; ?>
					</select>
					<?php echo $total; ?>
				</td>
			</tr>
			<tr>
				<td style="width:50%">
					<?php
echo'<pre style="max-height:200px;overflow:auto;border:1px solid yellow;text-align:left;">allLdapUsers('.count($allLdapUsers).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($allLdapUsers);echo'</pre>';
					?>
				</td>
				<td>
					<?php
echo'<pre style="max-height:200px;overflow:auto;border:1px solid yellow;text-align:left;">allUsers('.count($allUsers).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($allUsers);echo'</pre>';
					?>
				</td>
			</tr>
		</table>
		<?php
	}


	if ('' !== ($addLdapGroup = V::get('addLdapGroup', '', $_GET))) {
		echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">addLdapGroup (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($addLdapGroup);echo'</pre>';

		$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]);
			}
		}
	}

	echo '</div>';// .container
}
