<?php
include_once("c_AD_setting.php");
class c_page_cab_AD_setting_check extends c_page_cab_AD_setting
{
  public $h1='Проверка коннекта к ActiveDirectory' ;

  var $arr_cmd=array('get_AD_member_info'=>'get_AD_member_info',
                     'check_rol'=>'check_rol',

          ) ;

 function block_main()
	 { $this->page_title() ;
	   //damp_array($_POST,1,-1) ;
	   ?> <form action="/cab/AD/setting/check/">
	      <select name="check_cmd"><option></option><?if (_sizeof($this->arr_cmd)) foreach($this->arr_cmd as $cmd=>$title){?><option value="<?echo $cmd?>" <?if ($_POST['check_cmd']==$cmd) echo 'selected'?>><?echo $title?></option><?}?></select>
	      <button class="v1" cmd="exec_check">Выполнить</button>
	      <br><br></form>
	    <?
	     $cmd=$_POST['check_cmd'] ;
	     $action=$_POST['action'] ;
	     if ($cmd and method_exists($this,$cmd)) $this->$cmd() ;
	     elseif ($action and method_exists($this,$action)) $this->$action() ;
	     elseif ($this->filter['action'] and method_exists($this,$this->filter['action'])) $this->{$this->filter['action']}() ;
	     if ($this->filter['action2'] and method_exists($this,$this->filter['action2'])) $this->{$this->filter['action2']}() ;
	 }

function check_rol()
{    $data=AD()->get_AD_member_info('yakimov_sn') ;
    $recs_group=execSQL('select * from obj_site_account where clss in (1,206) and enabled=1 and parent>0',2) ;
    $arr_rol=array() ; $main_rol=0 ;$arr_group=array() ; $main_group=$GLOBALS['LS_AD_default_group'] ; $arr_AD_result=array() ;
     if (_sizeof($data['groups']))  foreach($data['groups'] as $guid=>$group_name)
       {   echo 'check group '.$group_name.' ['.$guid.']<br>' ;
           $id_grp=_IL('IL_ad_groups')->get_id_of_value($group_name) ;
           echo   '$id_grp='.$id_grp.'<br>' ;
         if ($id_grp)
         {   // id роли храниться в поле personal_id
             $rec_AD=_IL('IL_ad_groups')->recs[$id_grp] ; print_r($rec_AD) ; echo '<br>' ;
             if ($rec_AD['personal_id'] and $rec_AD['enabled'])
             { $arr_rol[]=$rec_AD['personal_id'] ;
               $arr_AD_result[$rec_AD['obj_name']]['Роль']=$_SESSION['ARR_roll'][$rec_AD['personal_id']]['obj_name'].' [id='.$rec_AD['personal_id'].']' ;
             }
             if ($rec_AD['group_id'] and $rec_AD['enabled']) { $arr_group[]=$rec_AD['group_id'] ; $arr_AD_result[$rec_AD['obj_name']]['Группа']=$recs_group[$rec_AD['group_id']]['obj_name'].' [id='.$rec_AD['group_id'].']' ;   }
         }
       }
      damp_array($arr_rol,1,-1) ;
}


 function get_AD_member_info()
 {
     AD()->AD_connect() ;
           $result=array() ;
           $login = explode('@',MEMBER()->login, 2)[0];
     //damp_array(MEMBER(),1,-1);
       //    $login ='yakimov_sn' ;
           if ($login)
           {   try
               { $user = AD()->manager->buildLdapQuery()->select(['name', 'lastName', 'firstName', 'dn', 'guid', 'username', 'memberOf', 'displayName'])->fromUsers()->where(['samaccountname' => $login])->getLdapQuery()->getSingleResult();
                 $result['name']=$user->has('lastName') ? $user->get('lastName') : '';
                 $result['lastName']=$user->has('lastName') ? $user->get('lastName') : '';
                 $result['firstName']=$user->has('firstName') ? $user->get('firstName') : '';
                 $result['displayName']=$user->has('displayName') ? $user->get('displayName') : '';
                 $result['dn']=$user->get('dn') ;
                 $result['guid']=$user->get('guid') ;
                 $result['username']=$user->get('username') ;
                 $result['groups'] = [];

                 $groups = $user->has('memberOf') ? $user->get('memberOf') : [];
                 if (!is_array($groups)) {
                     $groups = [$groups];
                 }

                 foreach ($groups as $dn) {
                    $group = AD()->manager->buildLdapQuery()->select(['guid', 'name'])->fromGroups()->where(['dn' => $dn])->getLdapQuery()->getSingleResult();
                    $guid = $group->get('guid');
                    $name = $group->get('name');
                    $result['groups'][$guid] = $name;
                 }
               }
               catch (Exception $e)
               {  switch($e->getMessage())
                  { //case 'LDAP returned no results': $result= []; break ;
                    //default: LOGS()->reg_log('AD_error','get_AD_member_info("'.$REMOTE_USER.'"): '.$e->getMessage()) ;

                  }
                  $result= [];
               }
           } else  $result= [];
           damp_array($result,1,-1) ;
 }

 function _block_main()
 { if (!function_exists('AD')) {echo 'Необходимо включить модуль AD' ; return ;}

   $this->page_title() ;

   //AD()->AD_connect() ;
   try
   {
   $user_dns = AD()->get_group_members2('esmo');
   print_2x_arr($user_dns) ;

 }
   catch (Exception $e)
   {
	     echo '<br>Возникла ошибка: <strong>'.$e->getMessage()."</strong>\n";
   }



 }




}
 /*
register_shutdown_function( "fatal_handler" );

function fatal_handler() {
    $errfile = "unknown file";
    $errstr  = "shutdown";
    $errno   = E_CORE_ERROR;
    $errline = 0;

    $error = error_get_last();

    if( $error !== NULL) {
        $errno   = $error["type"];
        $errfile = $error["file"];
        $errline = $error["line"];
        $errstr  = $error["message"];

        echo '===='.format_error( $errno, $errstr, $errfile, $errline).'=====';
    }
}

function format_error( $errno, $errstr, $errfile, $errline ) {
    $trace = print_r( debug_backtrace( false ), true );

    $content = "
    <table>
        <thead><th>Item</th><th>Description</th></thead>
        <tbody>
            <tr>
                <th>Error</th>
                <td><pre>$errstr</pre></td>
            </tr>
            <tr>
                <th>Errno</th>
                <td><pre>$errno</pre></td>
            </tr>
            <tr>
                <th>File</th>
                <td>$errfile</td>
            </tr>
            <tr>
                <th>Line</th>
                <td>$errline</td>
            </tr>
            <tr>
                <th>Trace</th>
                <td><pre>$trace</pre></td>
            </tr>
        </tbody>
    </table>";
    return $content;
}  */



?>
