<?php
include_once(_DIR_TO_ENGINE."/admin/c_site.php") ;
include_once(_DIR_TO_ENGINE."/admin/i_clss_func.php") ;
include_once(_DIR_TO_ENGINE.'/admin/c_menu_tabs.php') ;
include_once(_DIR_TO_ENGINE.'/c_db_mssql.php') ;

//-----------------------------------------------------------------------------------------------------------------------------
// главное окно
//-----------------------------------------------------------------------------------------------------------------------------

class c_aspmo_setup extends c_editor_obj
{
  function body($options=array()) { $this->body_frame_2x(array('fra_tree'=>_PATH_TO_ADMIN.'/aspmo_setup_tree.php')) ; }
}

class c_aspmo_setup_tree extends c_fra_tree
{
    function body($options=array())
     {?><body id=tree_objects>
         <ul class="tree_root" on_click_script="aspmo_setup_viewer.php">
            <li clss=1>Служебные операции</li>
            <ul>
                <li clss=1>Установка</li>
                         <ul>
                             <li cmd=create_based_tables>Создать базовые таблицы</li>
                             <li cmd=install_modules script="ext/setup">Инсталлировать модули</li>
                             <li cmd=install_modules script="ext/setup">Чистка таблиц</li>
                         </ul>
                         <li clss=1>Обновление</li>
                         <ul>
                             <li cmd=aspmo_setup/update_from_zip>Обновить из архива</li>
                             <li cmd=update_log_reqest>Обновить лог запросов</li>
                             <li cmd=create_pass_hash>Создать хеш паролей аккаунтов</li>
                         </ul>
                         <li clss=1>Чистка</li>
                         <ul>
                             <li cmd=clear_log_events>Очистка журнала событий</li>
                             <li cmd=delete_temp_mo>Удалить неоконченные МО</li>
                             <li cmd=delete_personal>Удалить персонал</li>
                             <li cmd=delete_org>Удалить компании и подразделения</li>
                             <li cmd=delete_bill>Очистить биллинг</li>
                             <li cmd=delete_MO_lost_personal>Удалить МО несуществующих сотрудников</li>
                             <li cmd=delete_MO_org>Удалить МО организации</li>
                             <li cmd=delete_person>Удалить персону</li>
                             <li cmd=delete_message>Удалить сообщения</li>
                             <li cmd=delete_events>Удалить мероприятия</li>
                             <li cmd=rand_persons>Перетасовать личные данные персонала</li>
                             <li cmd=rand_org>Перетасовать названия орзанизаций</li>
                             <li cmd=clear_names>Обезличить персонал и организации</li>
                             <li cmd=split_obj_name>Разделить obj_name</li>
                         </ul>
                         <li clss=1>MSSQL</li>
                         <ul>
                             <li cmd=mssql_save_row_count>Сохранить размеры таблиц</li>
                             <li cmd=mssql_pass_info>Информация по пропуску</li>
                             <li cmd=mssql_personal_info>Информация по сотруднику</li>
                             <li cmd=mssql_check_create_member>Тест добавления сотрудника в базу</li>
                             <li cmd=mssql_member_operation>Тест операций с сотрудником</li>
                             <li cmd=mssql_card_delete>Удалить пропуск</li>
                             <li cmd=mssql_view_group_of_section>Показать группы раздела</li>
                         </ul>
                         <li clss=1>Отладка Медицина</li>
                         <ul>
                             <li cmd=get_terminal_by_id>get_terminal_by_id</li>
                             <li cmd=get_personal_by_propusk>get_personal_by_propusk</li>
                             <li cmd=get_personal_by_id>get_personal_by_id</li>
                             <li cmd=get_org_by_id>get_org_by_id</li>
                             <li cmd=get_member_by_id>get_member_by_id</li>
                             <li cmd=get_mo_by_id>get_mo_by_id</li>
                             <li cmd=check_doctor>check_doctor</li>
                             <li cmd=check_personal_access>check_personal_access</li>
                             <li cmd=check_update_mo_type>check_update_mo_type</li>
                             <li cmd=update_mo_type>update_mo_type</li>
                             <li cmd=update_model>update_model</li>
                             <li cmd=get_presense>get_presense</li>
                             <li cmd=update_PP>update PP</li>
                             <li cmd=update_sign_image>update_sign_image</li>
                             <li cmd=update_bill>update bill</li>
                             <li cmd=create_podpis>create podpis</li>
                             <li cmd=set_ball_pressure>Обновить баллы по давлению</li>
                             <li cmd=get_MO_stats>Статистика по МО</li>
                             <li cmd=update_flag_res>Обновить флаги результатов МО</li>
                             <li cmd=update_group_in_mo>Обновить группу в МО в соответствии с терминалом</li>
                             <li cmd=update_pp_cnt>Обновить кол-во измерений ПП для сотрудников</li>
                         </ul>
                         <li clss=1>Отладка СКД</li>
                         <ul>
                             <li cmd=skd_check_import_HR>skd_check_import_HR</li>
                             <li cmd=skd_exec_import_HR>skd_exec_import_HR</li>
                             <li cmd=skd_get_access_by_skippass>get_access_by_skippass</li>
                             <li cmd=skd_update_time_out>update time_out</li>
                             <li cmd=skd_get_log_info_to_pass_one>get_log_info_to_pass_one</li>
                             <li cmd=skd_delete_DEMO_persons>Удалить DEMO аккаунты</li>
                             <li cmd=skd_merge_diplicate_persons>Объеденить дубликаты персон</li>
                             <li cmd=skd_delete_free_pass_log>Удалить потерянные записи из журнала проходов</li>
                             <li cmd=skd_delete_log_events>Удалить записи журнала событий</li>
                         </ul>
                      </ul>
            </ul>
         </body>
     <?
   }


}

class c_aspmo_setup_viewer extends c_fra_based
{  public $no_inner_form=1 ;
   function body($options=array()) {$this->body_frame($options) ; }

   function get_terminal_by_id()
   {    echo '<h1>Проверка get_terminal_by_id</h1>' ;
        ?><div id="get_terminal_by_id">
            <form method="POST"><input name="terminal_id" value="" type="text"><input cmd=get_terminal_by_id_apply type="submit" value="send"></form>
        </div><?
   }

    function get_terminal_by_id_apply()
       {
          echo '<h1>Проверка get_terminal_by_id</h1>' ;
          $rec=ESMO()->get_terminal_by_id($_POST['terminal_id'],array('debug'=>2)) ;
          ?><h1>Информация по терминалу</h1><?
          damp_array($rec,1,-1);
       }

   function get_personal_by_propusk()
   {    echo '<h1>Проверка get_personal_by_propusk</h1>' ;
        ?><div id="get_personal_by_propusk">
          <form method="POST"><input name="propusk_id" value="" type="text"><input cmd=get_personal_by_propusk_apply type="submit" value="send"></form>
        </div><?
   }

   function get_personal_by_propusk_apply()
   {  global $debug_db ; $debug_db=2 ;
      echo '<h1>Проверка get_personal_by_propusk</h1>' ;
      //damp_array($_POST,1,-1);
      $rec_member=PERSONAL()->get_personal_by_propusk($_POST['propusk_id'],array('debug'=>1)) ;
      damp_array($rec_member,1,-1);
      $rec_member=PERSONAL()->get_personal(array('propusk'=>$_POST['propusk_id'])) ;
      damp_array($rec_member,1,-1);
   }

   function get_member_by_id()
   {    echo '<h1>Проверка get_member_by_id</h1>' ;
        ?><div id="get_member_by_id">
          <form method="POST"><input name="id" value="" type="text"><input cmd=get_member_by_id_apply type="submit" value="send"></form>
        </div><?
   }

   function get_member_by_id_apply()
   {
      echo '<h1>Проверка get_member_by_id</h1>' ;
      //damp_array($_POST,1,-1);
      $rec_member=ACCOUNTS()->get_member_by_id($_POST['id'],array('debug'=>1)) ;
      damp_array($rec_member,1,-1);
   }

   function get_mo_by_id()
   {    echo '<h1>Проверка get_mo_by_id</h1>' ;
        ?><div id="get_mo_by_id">
          <form method="POST"><input name="id" value="<?echo $_POST['id']?>" type="text"><input cmd=get_mo_by_id_apply type="submit" value="send"></form>
        </div><?
   }

   function get_mo_by_id_apply()
   {  $this->get_mo_by_id() ;
      //damp_array($_POST,1,-1);
      $rec=ESMO()->get_mo_by_id($_POST['id'],array('debug'=>1)) ;
      damp_array($rec,1,-1);
   }
   function get_org_by_id()
   {    echo '<h1>Проверка get_org_by_id</h1>' ;
        ?><div id="get_org_by_id">
          <form method="POST"><input name="id" value="" type="text"><input cmd=get_org_by_id_apply type="submit" value="send"></form>
        </div><?
   }

   function get_org_by_id_apply()
   {
      echo '<h1>Проверка get_org_by_id</h1>' ;
      //damp_array($_POST,1,-1);
      $rec_member=PERSONAL()->get_org_by_id($_POST['id'],array('debug'=>1)) ;
      damp_array($rec_member,1,-1);
   }

   function get_personal_by_id()
   {    echo '<h1>Проверка get_personal_by_id</h1>' ;
        ?><div id="get_personal_by_id">
          <form method="POST"><input name="id" value="" type="text"><input cmd=get_personal_by_id_apply type="submit" value="send"></form>
        </div><?
   }

   function get_personal_by_id_apply()
   {
      echo '<h1>Проверка get_personal_by_id</h1>' ;
      //damp_array($_POST,1,-1);
      $rec_member=PERSONAL()->get_personal_by_id($_POST['id'],array('debug'=>1)) ;
      damp_array($rec_member,1,-1);
   }

   function check_doctor()
   { echo '<h1>Проверка check_doctor</h1>' ;
       ?><div id="check_doctor">
         <form method="POST">Терминал ID <input name="terminal_id" value="<?echo $_POST['terminal_id']?>" type="text"><input cmd=check_doctor type="submit" value="send"></form>
       </div><?
     if ($_POST['terminal_id'])
     {
          $rec_terminal=ESMO()->get_terminal_by_id($_POST['terminal_id']) ;
          $doctor_id=ESMO()->check_doctor($rec_terminal['parent'],array('debug'=>2)) ;
          echo '$doctor_id='.$doctor_id.'<br>' ;
          $rec_member=ACCOUNTS()->get_member_by_id($doctor_id) ;
          damp_array($rec_member,1,-1) ;

     }
   }

   function check_personal_access()
   { echo '<h1>Проверка check_personal_access</h1>' ;
       ?><div id="check_personal_access">
         <form method="POST">Пропуск <input name="propusk_id" value="" type="text"><input cmd=check_personal_access_apply type="submit" value="send"></form>
       </div><?
   }

    function check_personal_access_apply()
       {  global $aspmo_system,$debug_db ; $debug_db=2 ;
          echo '<h1>Проверка check_personal_access</h1>' ;

          $rec_member=PERSONAL()->get_personal_by_propusk($_POST['propusk_id']) ;
          ESMO()->check_personal_access($rec_member,array('debug'=>2)) ;
          damp_array($rec_member,1,-1);
          $debug_db=0 ;
       }


    function update_PP()
    {  execSQL_update('delete from obj_site_narko_data where id_mo=0 or id_mo is null') ;
       execSQL_update('update obj_site_narko_data set result=""') ;
       $ids=execSQL('select pkey,id_mo from obj_site_narko_data') ;
       if (_sizeof($ids)) foreach($ids as $rec)
       { $rec_mo=ESMO()->get_mo_by_id($rec['id_mo']) ;
         $result='';
         if (($rec_mo['status']==2 or $rec_mo['status']==3) and !$rec_mo['reason']=='cancelTimeout') list($result,$code)=PP()->check_narko($rec['pkey'],array()) ;
         echo $rec['pkey'].': '.$result.'<br>' ;
       }
       execSQL('select pkey,id_mo,result from obj_site_narko_data',2) ;
    }

    function update_pp_cnt(){
        $recs=execSQL('select SQL_NO_CACHE personal_id,count(pkey) as cnt from obj_site_narko_data group by personal_id',1);
        foreach ($recs as $key=>$value){
          if ($key==0) continue;
          update_rec_in_table('obj_site_personals',array('cnt_pp'=>$value['cnt']),'pkey='.$key,array('debug'=>1)) ;
        }
    }

   //----------------------------------------------------------------------------------------------------------------------------------------------------------
   //
   // УДАЛЯЕМ ЗАПИСИ ПО НЕОКОНЧЕННЫМ МО
   //
   //----------------------------------------------------------------------------------------------------------------------------------------------------------


    function delete_temp_mo()
    {   $temp_MO_cnt=execSQL_value('select count(pkey) as cnt from obj_site_mo_session where e_data=0') ;
        ?>Из таблицы МО будут удалены все записи по неоконченным на текущий момент МО. В таблице МО сейчас <strong><?echo $temp_MO_cnt?></strong> таких записи.<br><br><?
        if ($temp_MO_cnt){?><form method="POST"><input cmd=delete_temp_mo_apply type="submit" value="Удалить"></form><?}
    }

    function delete_temp_mo_apply()
    {
        $res=execSQL_update('delete from obj_site_mo_session where e_data=0 ') ;
        ?>Из таблицы МО удалены все записи по неоконченным на текущий момент МО.<?
    }


   //----------------------------------------------------------------------------------------------------------------------------------------------------------
   //
   // УДАЛЯЕМ ПЕРСОНАЛ
   //
   //----------------------------------------------------------------------------------------------------------------------------------------------------------

    function delete_personal()
    {   $cnt=execSQL_value('select count(pkey) as cnt from obj_site_personals where clss=211 ') ;
        ?>Из таблицы персонала будут удалены все записи по персоналу -  <strong><?echo $cnt?></strong><br><br><?
        if ($cnt){?><form method="POST"><input cmd=delete_personal_apply type="submit" value="Удалить"></form><?}
    }

    function delete_personal_apply()
     {   $cnt1=execSQL_value('select count(pkey) as cnt from obj_site_personals where clss=211 ') ;
         $cnt2=execSQL_value('select count(pkey) as cnt from obj_site_personals_image where clss=3 ') ;
         $res=execSQL_update('delete from obj_site_personals where clss=211') ;
         $res=execSQL_update('delete from obj_site_personals_image where clss=3') ;
         ?>Из таблицы персонала удалены все записи по персоналу<br><?
         ?>Из таблицы фото персонала удалены все записи по фото персонала<?
         _event_reg('Очистка системы','Удалены все записи по персоналу - '.$cnt1.', все записи по фото персонала  - '.$cnt2) ;
     }

     function delete_message()
     {
         execSQL_update('delete from obj_site_personal_mess',2) ;
     }

     function delete_events()
     {
         execSQL_update('delete from obj_site_events_schedule',2) ;
         execSQL_update('delete from obj_site_events_pass',2) ;
         execSQL_update('delete from obj_site_events_pass_status',2) ;
         execSQL_update('delete from obj_site_events_themes',2) ;
         execSQL_update('delete from obj_site_events_themes_files',2) ;
         execSQL_update('delete from obj_site_lession',2) ;
         execSQL_update('delete from obj_site_lession_persons',2) ;
         execSQL_update('delete from obj_site_lession_themes',2) ;
     }



   //----------------------------------------------------------------------------------------------------------------------------------------------------------
   //
   // УДАЛЯЕМ БИЛЛИНГ
   //
   //----------------------------------------------------------------------------------------------------------------------------------------------------------

    function delete_bill()
    {   $cnt=execSQL_value('select count(pkey) as cnt from obj_site_bill where clss=400 ') ;
        ?>Из таблицы биллинга будут удалены все записи по операциям  -  <strong><?echo $cnt?></strong><br><br><?
        if ($cnt){?><form method="POST"><input cmd=delete_bill_apply type="submit" value="Удалить"></form><?}
    }

    function delete_bill_apply()
     {   $cnt1=execSQL_value('select count(pkey) as cnt from obj_site_bill where clss=400 and pkey>1 ') ;
         $res=execSQL_update('delete from obj_site_bill where clss=400 and pkey>1') ;
         $res=execSQL_update('update obj_site_rs set value=0') ;
         ?>Из таблицы биллинга удалены все записи<br><?
         _event_reg('Очистка системы','Удалены все записи по биллингу - '.$cnt1) ;
     }

   //----------------------------------------------------------------------------------------------------------------------------------------------------------
   //
   // УДАЛЯЕМ ОРГАНИЗАЦИИ И ОТДЕЛЫ
   //
   //----------------------------------------------------------------------------------------------------------------------------------------------------------

    function delete_org()
    {   $cnt=execSQL_value('select count(pkey) as cnt from obj_site_personals where clss=1 ') ;
        ?>Из таблицы персонала будут удалены все записи по организациям и отделам  -  <strong><?echo $cnt?></strong><br><br><?
        if ($cnt){?><form method="POST"><input cmd=delete_org_apply type="submit" value="Удалить"></form><?}
    }

    function delete_org_apply()
     {   $cnt1=execSQL_value('select count(pkey) as cnt from obj_site_personals where clss=1 and pkey>1 ') ;
         $res=execSQL_update('delete from obj_site_personals where clss=1 and pkey>1') ;
         ?>Из таблицы персонала удалены все записи по персоналу<br><?
         _event_reg('Очистка системы','Удалены все записи по организациям и отделам - '.$cnt1) ;
     }

   //----------------------------------------------------------------------------------------------------------------------------------------------------------
   //
   // УДАЛЯЕМ МО несуществующих сотрудников - они нарушают работу статистики
   //
   //----------------------------------------------------------------------------------------------------------------------------------------------------------

    function delete_MO_lost_personal()
    {  // $cnt=execSQL_line('select pkey from obj_site_personals where clss=211',2) ;
        $cnt=execSQL_line('select pkey from obj_site_mo_session where member_id not in (select pkey from obj_site_personals where clss=211) and dopusk in (1,2)',2) ;
        ?>Из таблицы персонала будут удалены все записи по организациям и отделам  -  <strong><?echo $cnt?></strong><br><br><?
        if ($cnt){?><form method="POST"><input cmd=delete_MO_lost_personal_apply type="submit" value="Удалить"></form><?}
    }

    function delete_MO_lost_personal_apply()
     {   //$cnt1=execSQL_value('select count(pkey) as cnt from obj_site_personals where clss=1 and pkey>1 ') ;
         //$res=execSQL_update('delete from obj_site_personals where clss=1 and pkey>1') ;
         ?>Из таблицы персонала удалены все записи по персоналу<br><?
         //_event_reg('Очистка системы','Удалены все записи по организациям и отделам - '.$cnt1) ;
     }

   //----------------------------------------------------------------------------------------------------------------------------------------------------------
   //
   // УДАЛЯЕМ МО тестовых организаций - они нарушают работу статистики
   //
   //----------------------------------------------------------------------------------------------------------------------------------------------------------

    function delete_MO_org()
    {  // $cnt=execSQL_line('select pkey from obj_site_personals where clss=211',2) ;
       $list_org=execSQL_row('select pkey,obj_name from obj_site_personals where clss=207 and demo=1') ;
       if (_sizeof($list_org))foreach($list_org as $org_id=>$org_name)
       {  $ids=PERSONAL()->tree[$org_id]->get_list_child() ;
          ?><h2><?echo $org_name?></h2><?
          $mo_cnt=execSQL_value('select count(pkey) from obj_site_mo_session where member_id in (select pkey from obj_site_personals where clss=211 and parent in ('.$ids.'))') ;
          echo 'Найдено МО:'.$mo_cnt ;
       }

       // return ;
       //$ids=ESMO()->
        //$cnt=execSQL_line('select pkey from obj_site_mo_session where member_id not in (select pkey from obj_site_personals where clss=211) and dopusk in (1,2)',2) ;
        //?>Из таблицы МО будут удалены все записи по данным  организациям<br><br><?
        ?><form method="POST"><input cmd=delete_MO_org_apply type="submit" value="Удалить"></form><?
    }

    function delete_MO_org_apply()
     {  $list_org=execSQL_row('select pkey,obj_name from obj_site_personals where clss=207 and demo=1') ;
        if (_sizeof($list_org))foreach($list_org as $org_id=>$org_name)
            {  $ids=PERSONAL()->tree[$org_id]->get_list_child() ;
               ?><h2><?echo $org_name?></h2><?
               $mo_cnt=execSQL_value('select count(pkey) from obj_site_mo_session where member_id in (select pkey from obj_site_personals where clss=211 and parent in ('.$ids.'))') ;
               execSQL_update('delete from obj_site_mo_session where member_id in (select pkey from obj_site_personals where clss=211 and parent in ('.$ids.'))') ;
               echo 'Удалено МО:'.$mo_cnt ;
            }

     //$cnt1=execSQL_value('select count(pkey) as cnt from obj_site_personals where clss=1 and pkey>1 ') ;
         //$res=execSQL_update('delete from obj_site_personals where clss=1 and pkey>1') ;
         ?>Из таблицы МО удалены все записи по тестовым оргианизациям<br><?
         //_event_reg('Очистка системы','Удалены все записи по организациям и отделам - '.$cnt1) ;
     }

   //----------------------------------------------------------------------------------------------------------------------------------------------------------
   //
   // ОЧИЩАЕМ ЖУРНАЛЫ
   //
   //----------------------------------------------------------------------------------------------------------------------------------------------------------


    function clear_log_events()
    {   $cnt=execSQL_value('select count(pkey) as cnt from obj_site_mo_log ') ;
        ?>Будет очищена таблица журнала событий. В журнале событий сейчас <strong><?echo $cnt?></strong> записей<br><br><?
        if ($cnt){?><form method="POST"><input cmd=clear_log_events_apply type="submit" value="Очистить"></form><?}
    }

    function clear_log_events_apply()
    {
        $res=execSQL_update('delete from obj_site_mo_log') ;
        ?>Журнал событий очищен<?
    }

    function update_model()
    {
        $recs=execSQL_line('select pkey from  obj_site_mo_session where status in (2,3) and (temp is null or temp=0)  order by pkey limit 10000 ') ;
        //damp_array($recs) ;
        if ($recs) foreach($recs as $id)
        {   $model=ESMO()->set_model_to_session_mo($id) ;
            echo 'id='.$id.' => '.$model.'<br>' ;
        }

    }

    function update_mo_type()
    {
        $recs=execSQL('select pkey,member_id,c_data from  obj_site_mo_session where (mo_type=0 or mo_type is null) and reason!="noAutorize" order by pkey') ;
        if ($recs) foreach($recs as $rec)
        {  $time_mo=getdate($rec['c_data']) ;
           $time_from=mktime($time_mo['hours']-2,$time_mo['minutes']-$GLOBALS['LS_setting_auto_mo_interval'],$time_mo['seconds'],$time_mo['mon'],$time_mo['mday'],$time_mo['year']);
           $rec_prev_mo=execSQL_van('select pkey,mo_type from obj_site_mo_session where member_id="'.$rec['member_id'].'" and pkey<'.$rec['pkey'].' and c_data>='.$time_from.' and status=3 and terminal_id>0 and (dopusk=0 or dopusk is null) order by pkey desc limit 1') ;
           if (!$rec_prev_mo['pkey'])      { $data['mo_type']=1 ;  $data['mo1_id']=0 ; } // первичный МО
           else                            { $data['mo_type']=2 ; $data['mo1_id']=$rec_prev_mo['pkey'] ; } // вторичный МО
           update_rec_in_table('obj_site_mo_session',$data,'pkey='.$rec['pkey']) ;


        }
        echo 'Проверено '._sizeof($recs).' записей<br>' ;
        //echo 'Обновлено '.$cnt.' записей<br>' ;
    }

    function check_update_mo_type()
    {   $cnt=0 ;

        $recs=execSQL('select pkey,member_id,c_data,mo_type,mo1_id from  obj_site_mo_session where reason!="noAutorize" order by pkey') ;
        if ($recs) foreach($recs as $rec)
        {  if ($rec['mo_type']==1)  $rec['mo1_id']=0 ;
           $time_mo=getdate($rec['c_data']) ;
           $time_from=mktime($time_mo['hours']-2,$time_mo['minutes']-$GLOBALS['LS_setting_auto_mo_interval'],$time_mo['seconds'],$time_mo['mon'],$time_mo['mday'],$time_mo['year']);
           $rec_prev_mo=execSQL_van('select pkey,mo_type from obj_site_mo_session where member_id="'.$rec['member_id'].'" and pkey<'.$rec['pkey'].' and c_data>='.$time_from.' and status=3 and terminal_id>0 and (dopusk=0 or dopusk is null) order by pkey desc limit 1') ;
           if (!$rec_prev_mo['pkey'])      { $data['mo_type']=1 ; $data['mo1_id']=0 ; } // первичный МО
           else                            { $data['mo_type']=2 ; $data['mo1_id']=$rec_prev_mo['pkey'] ; } // вторичный МО
           //update_rec_in_table('obj_site_mo_session',$data,'pkey='.$rec['pkey']) ;
           if ($rec['mo_type']!=$data['mo_type'] or $rec['mo1_id']!=$data['mo1_id'])
           { echo $rec['pkey'].': '.$rec['mo_type'].' => '.$data['mo_type'].' , '.$rec['mo1_id'].' => '.$data['mo1_id'].'<br>' ;
             $cnt++ ;
           }
        }
        echo 'Проверено '._sizeof($recs).' записей<br>' ;
        echo 'Ошибка в '.$cnt.' записей<br>' ;
    }


    function get_presense()
    {
        $conn = new XMPPHP_XMPP(ESMO()->XMPP_server_host,ESMO()->XMPP_client_to_server_port,'aspmo_server'.ESMO()->XMPP_login_domain,'12345','cur_connect');
        try
        {   $conn->connect();
            $conn->processUntil('session_start');
            $conn->presence();     // away,
            $conn->disconnect();
        }
        catch(XMPPHP_Exception $e) { error_log($e->getMessage());}
        $arr=$conn->roster->getRoster()  ; //print_r($arr,1,-1) ; ;
        damp_array($arr,1,-1) ;
    }

    function update_log_reqest()
    {  $recs=execSQL('select * from '.ENGINE()->table_mo_req.' where personal_id is null or mo_id is null and cmd!="" order by c_data desc') ;
       if (_sizeof($recs)) foreach($recs as $rec)
       { $mess1=json_decode($rec['mess1'],true) ;
         $mess2=json_decode($rec['mess2'],true) ;
         $data=array() ;
         if ($mess1['args']['id']['medexam']) $data['mo_id']=$mess1['args']['id']['medexam'] ;
         if ($mess2['args']['id']['medexam']) $data['mo_id']=$mess2['args']['id']['medexam'] ;
         $propusk=$mess1['args']['id']['user'] ;
         if (!$propusk) $propusk=$mess2['args']['id']['user'] ;
         if ($propusk)
         { $rec_personal=PERSONAL()->get_personal_by_propusk($propusk) ;
           $data['personal_id']=$rec_personal['pkey'] ;
         }
         if (_sizeof($data)) update_rec_in_table(ENGINE()->table_mo_req,$data,'pkey='.$rec['pkey']) ;
         echo $rec['pkey'].':cmd='.$rec['cmd'].',  mo_id='.$data['mo_id'].', personal_id='.$data['personal_id'].'<br>' ;
       }
       //damp_array($recs) ;

    }

 function update_sign_image()
    {
        $recs=execSQL('select pkey,c_data from obj_site_mo_session where status in (2,3) order by pkey desc limit 1200') ;
        if (_sizeof($recs)) foreach($recs as $rec)
        {   $img_name='sign_'.$rec['pkey'].'.gif' ;
            if (!file_exists(_DIR_TO_ROOT.'/public/mo_sign/'.$img_name))
            {
                $img_cont=file_get_contents(_MAIN_PROTOCOL._MAIN_DOMAIN.'/services/esmo_signature/graf_signature/?mo_id='.$rec['pkey']) ;
                $cnt=file_put_contents(_DIR_TO_ROOT.'/public/mo_sign/'.$img_name,$img_cont) ;
                echo 'Сохранен файл '.$img_name.' для МО '.$rec['pkey'].' ['.date('d.m.Y H:i',$rec['c_data']).'] - '.$cnt.' байт<br>' ;
            }

        }
    }



    function delete_person()
    {   ?>Будет удалена персона и вся информация, связанная с данной персоной<br><br><?
        ?><form method="POST">Номер пропуска: <input type="text" name="propusk"><input cmd=delete_person_apply type="submit" value="Найти персону"></form><?
    }

    function delete_person_apply()
    {
        $rec_personal=PERSONAL()->get_personal(array('propusk'=>$_POST['propusk'])) ;
        //damp_array($rec_personal) ;
        if ($rec_personal['pkey'])
        { $mo_ids=execSQL_line('select pkey from obj_site_mo_session where member_id='.$rec_personal['pkey']) ;
          $cnt2=execSQL_value('select count(pkey) from obj_site_mo_log where personal_id='.$rec_personal['pkey']) ;
          $cnt3=execSQL_value('select count(pkey) from obj_site_req_log where personal_id='.$rec_personal['pkey']) ;
          if (_sizeof($mo_ids)) $cnt_sign=execSQL_value('select count(pkey) from obj_site_mo_session_DTW where parent in ('.implode(',',$mo_ids).')') ; else $cnt_sign=0 ;
          ?><table class="left">
            <tr><td>Таблица сотрудников:</td><td><?echo $rec_personal['obj_name']?></td></tr>
            <tr><td>Таблица МО:</td><td><?echo _sizeof($mo_ids).' записей'?></td></tr>
            <tr><td>Таблица SIGN:</td><td><?echo $cnt_sign.' записей'?></td></tr>
            <tr><td>Журнал событий:</td><td><?echo $cnt2.' записей'?></td></tr>
            <tr><td>Журнал обмена:</td><td><?echo $cnt3.' записей'?></td></tr>
           </table><?
        }
        ?><form method="POST"><input cmd=delete_person_apply2 personal_id=<?echo $rec_personal['pkey']?> type="submit" value="Удалить записи"></form><?
    }

    function delete_person_apply2()
    {
      //damp_array($_POST) ;
      $rec_personal=PERSONAL()->get_personal(array('pkey'=>$_POST['personal_id'])) ;
      if ($rec_personal['pkey'])
        { execSQL_update('delete from obj_site_personals where pkey='.$rec_personal['pkey'],array('debug'=>2)) ;
          execSQL_update('delete from obj_site_personals_image where parent='.$rec_personal['pkey'],array('debug'=>2)) ;
          execSQL_update('delete from obj_site_mo_session where member_id='.$rec_personal['pkey'],array('debug'=>2)) ;
          execSQL_update('delete from obj_site_mo_log where personal_id='.$rec_personal['pkey'],array('debug'=>2)) ;
          execSQL_update('delete from obj_site_req_log where personal_id='.$rec_personal['pkey'],array('debug'=>2)) ;
        }

    }

    function update_bill()
    {  $recs_mo=execSQL_line('select pkey from obj_site_mo_session where member_id!=0 and dopusk in (1,2) order by c_data',1) ;
       if (_sizeof($recs_mo)) foreach($recs_mo as $mo_id)
       {
          $rec_mo=ESMO()->get_mo_by_id($mo_id) ;
          if ($rec_mo['pkey'] and $rec_mo['member_id']) ESMO_BILLING()->apply_mo_bill($rec_mo) ;
       }
       _event_reg('БИЛЛИНГ','Создание записей по биллингу (для '._sizeof($recs_mo).' МО)') ;

    }

    function create_podpis()
    {  //update_rec_in_table('obj_site_mo_session_DTW',array('temp'=>0),'pkey>0') ;
       $recs_podpis=execSQL('select * from obj_site_mo_session_DTW where temp is null order by pkey desc limit 100',1) ;
       if (_sizeof($recs_podpis)) foreach($recs_podpis as $rec)
       {  $cnt=file_put_contents(_DIR_TO_ROOT.'/public/mo_photo/'.$rec['parent'].'_DTW_600.png',file_get_contents(_PATH_TO_SITE.'/services/esmo_signature/graf_signature/?mo_id='.$rec['parent'])) ;
          $cnt=file_put_contents(_DIR_TO_ROOT.'/public/mo_photo/'.$rec['parent'].'_DTW_150.png',file_get_contents(_PATH_TO_SITE.'/services/esmo_signature/graf_signature/?mo_id='.$rec['parent'].'&width=150')) ;
          if ($cnt) update_rec_in_table('obj_site_mo_session_DTW',array('temp'=>1),'pkey='.$rec['pkey']) ;
          echo 'Сохранение подписи для МО '.$rec['parent'].': ' ;
          echo ($cnt)? '<span class="green">OK</span>':'<span class="red">ERROR</span>' ;
          echo '<br>' ;
       }
       $recs_podpis=execSQL('select temp,count(pkey) from obj_site_mo_session_DTW group by temp order by temp',2) ;

    }

    function set_ball_pressure()
    {
        //$recs=execSQL('select model,count(pkey) from obj_site_mo_session group by model order by model',2) ;
        $recs=execSQL(//'select * from obj_site_mo_session'.
                      'select pkey,systolic,diastolic,model from obj_site_mo_session'.
                      ' where status in (2) and
                              systolic!=-1 and
                              diastolic!=-1 and
                              (hand_check_user_id=0 or hand_check_user_id is null)
                        order by pkey',1) ;


        //  критерии по S - _IL('IL_pressure_s')->recs
        //  критерии по D - _IL('IL_pressure_d')->recs
        ?><table class="debug basic fz_small"><tr><th>systolic</th><th>Диапазон</th><th>Баллы</th><th>diastolic</th><th>Диапазон</th><th>Баллы</th></tr><?
        if (_sizeof($recs)) foreach($recs as $rec)
        {   $ball_s=0 ; $ball_d=0 ;
            ?><tr><?
            foreach(_IL('IL_pressure_s')->recs as $krit)
            { if (($krit['v1'] and $krit['v2'] and $rec['systolic']>=$krit['v1'] and $rec['systolic']<=$krit['v2']) or
                  (!$krit['v1'] and $krit['v2'] and $rec['systolic']<=$krit['v2']) or
                  ($krit['v1'] and !$krit['v2'] and $rec['systolic']>=$krit['v1'])
                 )
              { $ball_s=$krit['ball'] ;
                ?><td><?echo $rec['systolic']?></td><td><?echo $krit['v1'].'...'.$krit['v2']?></td><td><? echo $krit['ball']?></td><?
              }

            }
            foreach(_IL('IL_pressure_d')->recs as $krit)
            { if (($krit['v1'] and $krit['v2'] and $rec['diastolic']>=$krit['v1'] and $rec['diastolic']<=$krit['v2']) or
                  (!$krit['v1'] and $krit['v2'] and $rec['diastolic']<=$krit['v2']) or
                  ($krit['v1'] and !$krit['v2'] and $rec['diastolic']>=$krit['v1'])
                 )
              { $ball_d=$krit['ball'] ;
                ?><td><?echo $rec['diastolic']?></td><td><?echo $krit['v1'].'...'.$krit['v2']?></td><td><? echo $krit['ball']?></td><?
              }
            }
            update_rec_in_table('obj_site_mo_session',array('ball_s'=>$ball_s,'ball_d'=>$ball_d),'pkey='.$rec['pkey']) ;
            ?></tr><?

        }
    }

    function get_MO_stats()
    {
       ?><h2>Статистика по числу МО</h2><?
       $recs=execSQL('select member_id,concat("<a target=_blank href=\'http://dev.kvzrm.ru/cab/personal/person/",member_id,"/graf/\'>http://dev.kvzrm.ru/cab/personal/person/",member_id,"/graf/</a>") as personal_page_url,count(pkey) as cnt from obj_site_mo_session group by member_id having cnt>10 order by cnt desc') ;
       print_2x_arr($recs) ;
    }



   //----------------------------------------------------------------------------------------------------------------------------------------------------------
   //
   // MSSQL
   //
   //----------------------------------------------------------------------------------------------------------------------------------------------------------
     //0000000AAAAAAAAA
     //45812984490


    function mssql_save_row_count()
    { $last_state=execSQL('select object_id,row_count,c_data from obj_site_mssql where row_count>0 order by c_data asc',array('no_indx'=>0,'debug'=>1)) ;
//      $arr_system_tables[]='DownloadPending' ;
      $arr_system_tables=array() ;
      $recs=DB_MSSQL()->execSQL('select ps.object_id,OBJECT_NAME(ps.object_id) as tname,ps.row_count from sys.dm_db_partition_stats ps',array('no_indx'=>1,'debug'=>1)) ;
      $time_snap=time() ; // у всех записей должено быть одинаковое время
      if (_sizeof($recs)) foreach($recs as $rec)
      {  $cnt_new=$rec['row_count'] ; if (!$cnt_new) $cnt_new=0 ;
         $cnt_old=$last_state[$rec['object_id']]['row_count'] ; if (!$cnt_old) $cnt_old=0 ;

         if ($cnt_new!=$cnt_old and array_search($rec['tname'],$arr_system_tables)===false)
         { adding_rec_to_table('obj_site_mssql',array('clss'=>800,'c_data'=>$time_snap,'obj_name'=>$rec['tname'],'object_id'=>$rec['object_id'],'row_count'=>$rec['row_count'])) ;
           echo  $rec['tname'].': '.$cnt_old.' => '.$cnt_new.'<br>' ;
         }
      }
      //print_2x_arr($recs) ;
      execSQL('select distinct(c_data) from obj_site_mssql',2) ;

    }


// добавление пользователя
//Cards: 34073 => 34074
//Individuals: 32573 => 32574
//IndivImages: 30153 => 30154

//TenantNdx=109
//IndivId=1

// добавление группы пользователю
// XRefIndivGroupDoor: 116236 => 116237

    function mssql_personal_info()
    { ?><h1>Информация по сотруднику</h1><?
      ?><form method="POST">
           TenantNdx: <input type="text" name="TenantNdx" value="<?echo $_POST['TenantNdx']?>">
           IndivId: <input type="text" name="IndivId" value="<?echo $_POST['IndivId']?>">
           LastName: <input type="text" name="LastName" value="<?echo $_POST['LastName']?>">
           <input cmd=mssql_personal_info type="submit" value="Искать"></form>
      <?
      if ($_POST['LastName'])
      { $recs=DB_MSSQL()->execSQL('select * from Individuals where LastName="'.$_POST['LastName'].'"',array('no_indx'=>1,'debug'=>1)) ;
        print_2x_arr($recs) ;
      }
      elseif ($_POST['TenantNdx'] and $_POST['IndivId'])
      {
        $recs=DB_MSSQL()->execSQL('select * from Individuals where TenantNdx="'.$_POST['TenantNdx'].'" and IndivId="'.$_POST['IndivId'].'"',array('no_indx'=>1,'debug'=>1)) ;
        print_2x_arr($recs) ;

        $recs=DB_MSSQL()->execSQL('select * from IndivCustomData where TenantNdx="'.$_POST['TenantNdx'].'" and IndivNdx="'.$_POST['IndivId'].'"',array('no_indx'=>1,'debug'=>1)) ;
        print_2x_arr($recs) ;

        $recs=DB_MSSQL()->execSQL('select * from Cards where TenantNdx="'.$_POST['TenantNdx'].'" and IndivNdx="'.$_POST['IndivId'].'"',array('no_indx'=>1,'debug'=>1)) ;
        print_2x_arr($recs) ;

        $recs=DB_MSSQL()->execSQL('select * from CardsView where TenantNdx="'.$_POST['TenantNdx'].'" and IndivNdx="'.$_POST['IndivId'].'"',array('no_indx'=>1,'debug'=>1)) ;
        print_2x_arr($recs) ;
        $recs=DB_MSSQL()->execSQL('select * from CardTextView where TenantNdx="'.$_POST['TenantNdx'].'" and IndivNdx="'.$_POST['IndivId'].'"',array('no_indx'=>1,'debug'=>1)) ;
        print_2x_arr($recs) ;
        $recs=DB_MSSQL()->execSQL('select * from RptIndividuals where TenantNdx="'.$_POST['TenantNdx'].'" and IndividualNdx="'.$_POST['IndivId'].'"',array('no_indx'=>1,'debug'=>1)) ;
        print_2x_arr($recs) ;
        //var_dump($recs) ;

        // Status - ДОСТУП: 0 - постоянный, 1 - временный, 2 - запрещенный
        // PINnum - код
        // IamGraced - Откл
        // TempStart - начало
        // TempStop - окончание
        ?><h1>Фото</h1><?

        $recs=DB_MSSQL()->execSQL('select * from IndivImages where TenantNdx="'.$_POST['TenantNdx'].'" and IndivNdx="'.$_POST['IndivId'].'"',array('no_indx'=>1,'debug'=>1)) ;
        //print_2x_arr($recs) ;
        $img_name='user_'.$_POST['TenantNdx'].'_'.$_POST['IndivId'].'.jpg' ;
        file_put_contents(_TEMP_DIR.$img_name,$recs[0]['UserImage']) ; // картинка 222x166, было 1024x768
        ?><img src="/tmp/<?echo $img_name?>"><?
        //var_dump($recs) ;

        ?><h1>Группы</h1><?
        $recs=DB_MSSQL()->execSQL('select * from XRefIndivGroupDoor where TenantNdx="'.$_POST['TenantNdx'].'" and IndivNdx="'.$_POST['IndivId'].'" order by PriorityOrder',array('no_indx'=>1,'debug'=>1)) ;
        print_2x_arr($recs) ;
        $grp_ids=array() ;
        if (_sizeof($recs)) foreach($recs as $rec) $grp_ids[]=$rec['DoorGroupNdx'] ;
        if (_sizeof($grp_ids)) $recs=DB_MSSQL()->execSQL('select * from DoorsGroups where DoorGroupId in ('.implode(',',$grp_ids).')',array('no_indx'=>1,'debug'=>2)) ;

        $recs=DB_MSSQL()->execSQL('select * from RptIndividualGroups where TenantNdx="'.$_POST['TenantNdx'].'" and IndividualNdx="'.$_POST['IndivId'].'"',array('no_indx'=>1,'debug'=>1)) ;
        print_2x_arr($recs) ;

        ?><h1>Двери</h1><?
        $recs=DB_MSSQL()->execSQL('select * from RptIndividualDoors where TenantNdx="'.$_POST['TenantNdx'].'" and IndividualNdx="'.$_POST['IndivId'].'"',array('no_indx'=>1,'debug'=>1)) ;
        print_2x_arr($recs) ;


        ?><h1>События</h1><?
        $recs=DB_MSSQL()->execSQL('select * from Events where TenantNdx="'.$_POST['TenantNdx'].'" and IndivNdx="'.$_POST['IndivId'].'" order by EventId desc',array('no_indx'=>1,'debug'=>1)) ;
        print_2x_arr($recs) ;

        ?><h1>IamUser</h1><?
        $recs=DB_MSSQL()->execSQL('select * from IamUser where TenantNdx="'.$_POST['TenantNdx'].'" and IndivNdx="'.$_POST['IndivId'].'"',array('no_indx'=>1,'debug'=>1)) ;
        print_2x_arr($recs) ;

        ?><h1>UserHistory</h1><?
        $recs=DB_MSSQL()->execSQL('select * from UserHistory where TenantNdx="'.$_POST['TenantNdx'].'" and IndivNdx="'.$_POST['IndivId'].'"',array('no_indx'=>1,'debug'=>1)) ;
        print_2x_arr($recs) ;
        $recs=DB_MSSQL()->execSQL('select * from RptIndividualHistory where TenantNdx="'.$_POST['TenantNdx'].'" and IndividualNdx="'.$_POST['IndivId'].'"',array('no_indx'=>1,'debug'=>1)) ;
        print_2x_arr($recs) ;


      }

    }

    function mssql_pass_info()
    { ?><h1>Информация по пропуску</h1><?
      ?><form method="POST">
           PassID: <input type="text" name="PassID" value="<?echo $_POST['PassID']?>">
           <input cmd=mssql_pass_info type="submit" value="Искать"></form>
      <?
      if ($_POST['PassID'])
      {
        $pass_id_hex=dechex($_POST['PassID'])  ;
        $rec=DB_MSSQL()->execSQL('select * from CardsView where CardNumber=dbo.HexToBinary("'.$pass_id_hex.'")',array('no_indx'=>1,'debug'=>0)) ;
        print_2x_arr($rec) ;
        $rec=DB_MSSQL()->execSQL('select * from RptCards where CardNumber=dbo.HexToBinary("'.$pass_id_hex.'")',array('no_indx'=>1,'debug'=>0)) ;
        print_2x_arr($rec) ;
        $rec=DB_MSSQL()->execSQL('select * from CardTextView where CardNumber=dbo.HexToBinary("'.$pass_id_hex.'")',array('no_indx'=>1,'debug'=>0)) ;
        print_2x_arr($rec) ;
        $result=$rec[0] ;
        if (_sizeof($rec[0]))
        {  $rec_person=DB_MSSQL()->execSQL('select * from RptIndividuals where IndividualNdx="'.$rec[0]['IndivNdx'].'"',array('no_indx'=>1,'debug'=>0)) ;
           $result['pkey']=$_POST['PassID'] ;
           $result['_person']=$rec_person[0] ;
           $result['_person']['pkey']=$result['_person']['IndividualNdx'] ;
           $result['_person']['obj_name']=$result['_person']['LastName'].' '.$result['_person']['FirstName'] ;
           $result['time_from']=strtotime($result['_person']['TempStart']) ;
           $result['time_to']=strtotime($result['_person']['TempStop']) ;
           $result['enabled']=($result['Disabled'])? 0:1 ;
           $result['r_data']=$result['time_from'] ;
        }

        return ;
        print_2x_arr($result) ;
        $recs=DB_MSSQL()->execSQL('select * from Individuals where TenantNdx="'.$_POST['TenantNdx'].'" and IndivId="'.$_POST['IndivId'].'"',array('no_indx'=>1,'debug'=>1)) ;
        print_2x_arr($recs) ;

        $recs=DB_MSSQL()->execSQL('select * from IndivCustomData where TenantNdx="'.$_POST['TenantNdx'].'" and IndivNdx="'.$_POST['IndivId'].'"',array('no_indx'=>1,'debug'=>1)) ;
        print_2x_arr($recs) ;

        $recs=DB_MSSQL()->execSQL('select * from Cards where TenantNdx="'.$_POST['TenantNdx'].'" and IndivNdx="'.$_POST['IndivId'].'"',array('no_indx'=>1,'debug'=>1)) ;
        print_2x_arr($recs) ;

        $recs=DB_MSSQL()->execSQL('select * from CardsView where TenantNdx="'.$_POST['TenantNdx'].'" and IndivNdx="'.$_POST['IndivId'].'"',array('no_indx'=>1,'debug'=>1)) ;
        print_2x_arr($recs) ;
        $recs=DB_MSSQL()->execSQL('select * from CardTextView where TenantNdx="'.$_POST['TenantNdx'].'" and IndivNdx="'.$_POST['IndivId'].'"',array('no_indx'=>1,'debug'=>1)) ;
        print_2x_arr($recs) ;
        $recs=DB_MSSQL()->execSQL('select * from RptIndividuals where TenantNdx="'.$_POST['TenantNdx'].'" and IndividualNdx="'.$_POST['IndivId'].'"',array('no_indx'=>1,'debug'=>1)) ;
        print_2x_arr($recs) ;
        //var_dump($recs) ;

        // Status - ДОСТУП: 0 - постоянный, 1 - временный, 2 - запрещенный
        // PINnum - код
        // IamGraced - Откл
        // TempStart - начало
        // TempStop - окончание
        ?><h1>Фото</h1><?

        $recs=DB_MSSQL()->execSQL('select * from IndivImages where TenantNdx="'.$_POST['TenantNdx'].'" and IndivNdx="'.$_POST['IndivId'].'"',array('no_indx'=>1,'debug'=>1)) ;
        //print_2x_arr($recs) ;
        $img_name='user_'.$_POST['TenantNdx'].'_'.$_POST['IndivId'].'.jpg' ;
        file_put_contents(_TEMP_DIR.$img_name,$recs[0]['UserImage']) ; // картинка 222x166, было 1024x768
        ?><img src="/tmp/<?echo $img_name?>"><?
        //var_dump($recs) ;

        ?><h1>Группы</h1><?
        $recs=DB_MSSQL()->execSQL('select * from XRefIndivGroupDoor where TenantNdx="'.$_POST['TenantNdx'].'" and IndivNdx="'.$_POST['IndivId'].'" order by PriorityOrder',array('no_indx'=>1,'debug'=>1)) ;
        print_2x_arr($recs) ;
        $grp_ids=array() ;
        if (_sizeof($recs)) foreach($recs as $rec) $grp_ids[]=$rec['DoorGroupNdx'] ;
        if (_sizeof($grp_ids)) $recs=DB_MSSQL()->execSQL('select * from DoorsGroups where DoorGroupId in ('.implode(',',$grp_ids).')',array('no_indx'=>1,'debug'=>2)) ;

        $recs=DB_MSSQL()->execSQL('select * from RptIndividualGroups where TenantNdx="'.$_POST['TenantNdx'].'" and IndividualNdx="'.$_POST['IndivId'].'"',array('no_indx'=>1,'debug'=>1)) ;
        print_2x_arr($recs) ;

        ?><h1>Двери</h1><?
        $recs=DB_MSSQL()->execSQL('select * from RptIndividualDoors where TenantNdx="'.$_POST['TenantNdx'].'" and IndividualNdx="'.$_POST['IndivId'].'"',array('no_indx'=>1,'debug'=>1)) ;
        print_2x_arr($recs) ;


        ?><h1>События</h1><?
        $recs=DB_MSSQL()->execSQL('select * from Events where TenantNdx="'.$_POST['TenantNdx'].'" and IndivNdx="'.$_POST['IndivId'].'" order by EventId desc',array('no_indx'=>1,'debug'=>1)) ;
        print_2x_arr($recs) ;

        ?><h1>IamUser</h1><?
        $recs=DB_MSSQL()->execSQL('select * from IamUser where TenantNdx="'.$_POST['TenantNdx'].'" and IndivNdx="'.$_POST['IndivId'].'"',array('no_indx'=>1,'debug'=>1)) ;
        print_2x_arr($recs) ;

        ?><h1>UserHistory</h1><?
        $recs=DB_MSSQL()->execSQL('select * from UserHistory where TenantNdx="'.$_POST['TenantNdx'].'" and IndivNdx="'.$_POST['IndivId'].'"',array('no_indx'=>1,'debug'=>1)) ;
        print_2x_arr($recs) ;
        $recs=DB_MSSQL()->execSQL('select * from RptIndividualHistory where TenantNdx="'.$_POST['TenantNdx'].'" and IndividualNdx="'.$_POST['IndivId'].'"',array('no_indx'=>1,'debug'=>1)) ;
        print_2x_arr($recs) ;


      }

    }


    function mssql_check_create_member()
    {
       ?><h1>Тест добавления сотрудника в базу</h1><?
             ?><form method="POST">
                  TenantNdx: <input type="text" name="TenantNdx" value="<?echo $_POST['TenantNdx']?>">
                  IndivId: <input type="text" name="IndivId" value="<?echo $_POST['IndivId']?>">
                  LastName: <input type="text" name="LastName" value="<?echo $_POST['LastName']?>">
                  FirstName: <input type="text" name="FirstName" value="<?echo $_POST['FirstName']?>">
                  PassId: <input type="text" name="PassId" value="<?echo $_POST['PassId']?>">
                  <input cmd=mssql_check_create_member type="submit" value="Добавить"></form>
             <?
             if ($_POST['TenantNdx'] and $_POST['IndivId'])// and $_POST['LastName'] and $_POST['FirstName'] and $_POST['PassId'])
             { $recs=DB_MSSQL()->execSQL('select * from Individuals where TenantNdx="'.$_POST['TenantNdx'].'" and IndivId="'.$_POST['IndivId'].'"',array('no_indx'=>1,'debug'=>1)) ;
               if (_sizeof($recs[0]))
               {
                 ?><div class="alert">Такой персонал уже существует</div><?
               }
               else
               { $sql="BEGIN TRANSACTION" ;
                 DB_MSSQL()->execSQL_update($sql) ;
                 DB_MSSQL()->adding_rec_to_table('Individuals',array('TenantNdx'=>    $_POST['TenantNdx'],
                                                       'IndivId'=>      $_POST['IndivId'],
                                                       'AccessVerNdx'=> 1,
                                                       'LastName'=>     $_POST['LastName'],
                                                       'FirstName'=>    $_POST['FirstName'],
                                                       'TempStart'=>    date('m.d.Y h:i:s'),
                                                       'TempStop'=>     date('m.d.Y h:i:s'),
                                                       'Status'=>       1,
                                                       'IssueLevel'=>   0,
                                                       'APBtype'=>      1,
                                                       'PINnum'=>       0,
                                                       'ImagePath'=>    0,
                                                       'IamGraced'=>    0,
                                                       'IamDisabled'=>  0
                                                )) ;

                /*
                DB_MSSQL()->adding_rec_to_table('Cards',array('TenantNdx'=>    $_POST['TenantNdx'],
                                                              'IndivNdx'=>      $_POST['IndivId'],
                                                              'Resident'=>     0,
                                                              'CardNumber'=>   $_POST['PassId']
                                                              )) ;

               */
                $sql="insert into Cards (TenantNdx,IndivNdx,Resident,CardNumber) values ('".$_POST['TenantNdx']."','".$_POST['IndivId']."','0',dbo.HexToBinary('".dechex($_POST['PassId'])."'))" ;
                DB_MSSQL()->execSQL_update($sql) ;

                $img_cont=file_get_contents(_DIR_TO_ROOT.'/user_test.jpg') ;
                $data = unpack("H*hex", $img_cont);
                $sql="insert into IndivImages (TenantNdx,IndivNdx,UserImage) values ('".$_POST['TenantNdx']."','".$_POST['IndivId']."',0x".$data['hex'].")" ;
                DB_MSSQL()->execSQL_update($sql) ;
                $sql="COMMIT WORK" ;
                DB_MSSQL()->execSQL_update($sql) ;

               }


               $recs=DB_MSSQL()->execSQL('select * from Individuals where TenantNdx="'.$_POST['TenantNdx'].'" and IndivId="'.$_POST['IndivId'].'"',array('no_indx'=>1,'debug'=>1)) ;
               print_2x_arr($recs) ;

               $recs=DB_MSSQL()->execSQL('select * from Cards where TenantNdx="'.$_POST['TenantNdx'].'" and IndivNdx="'.$_POST['IndivId'].'"',array('no_indx'=>1,'debug'=>1)) ;
               print_2x_arr($recs) ;

               $recs=DB_MSSQL()->execSQL('select * from IndivImages where TenantNdx="'.$_POST['TenantNdx'].'" and IndivNdx="'.$_POST['IndivId'].'"',array('no_indx'=>1,'debug'=>1)) ;
               $img_name='user_'.$_POST['TenantNdx'].'_'.$_POST['IndivId'].'.jpg' ;
               file_put_contents(_TEMP_DIR.$img_name,$recs[0]['UserImage']) ; // картинка 222x166, было 1024x768
               ?><img src="/tmp/<?echo $img_name?>"><?



                // добавление пользователя
                //Cards: 34073 => 34074
                //Individuals: 32573 => 32574
                //IndivImages: 30153 => 30154

             }
    }

    function mssql_card_delete()
    {?><h1>Удаление пропуска из базы</h1><?
     ?><form method="POST">
          PassId: <input type="text" name="PassId" value="<?echo $_POST['PassId']?>"><input cmd=mssql_card_delete type="submit" mode=find value="Найти">
          <? if ($_POST['PassId']) {?><input cmd=mssql_card_delete type="submit" mode=delete value="Удалить"><?}?>
     <?
     damp_array($_POST,1,-1) ;
     if ($_POST['PassId'])
     {  $pass_id_hex=dechex($_POST['PassId'])  ;
        $rec=DB_MSSQL()->execSQL('select * from CardTextView where CardNumber=dbo.HexToBinary("'.$pass_id_hex.'")',array('no_indx'=>1,'debug'=>0)) ;
        print_2x_arr($rec) ;
        if (_sizeof($rec[0]))
        {  $rec_person=DB_MSSQL()->execSQL('select * from RptIndividuals where TenantNdx="'.$rec[0]['TenantNdx'].'" and IndividualNdx="'.$rec[0]['IndivNdx'].'"',array('no_indx'=>1,'debug'=>0)) ;
           print_2x_arr($rec_person) ;
           ?><input type="hidden" name="TenantNdx" value="<?echo $rec[0]['TenantNdx']?>"><?
           ?><input type="hidden" name="IndivNdx" value="<?echo $rec[0]['IndivNdx']?>"><?
        }
     }
     if ($_POST['TenantNdx'] and $_POST['IndivNdx'] and $_POST['mode']=='delete')
     {  $sql='delete from Cards where TenantNdx="'.$_POST['TenantNdx'].'" and IndivNdx="'.$_POST['IndivNdx'].'" and CardNumber=dbo.HexToBinary("'.$pass_id_hex.'")' ; // ) values ('".$_POST['TenantNdx']."','".$_POST['IndivId']."','0',dbo.HexToBinary(".dechex($_POST['PassId'])."))" ;
        echo $sql.'<br>' ;
        DB_MSSQL()->execSQL_update($sql) ;
     }
     ?></form><?
    }


    function mssql_view_group_of_section()
    {
        ?><form method="POST">
                  TenantNdx: <input type="text" name="TenantNdx" value="<?echo $_POST['TenantNdx']?>"><input cmd=mssql_view_group_of_section type="submit" value="Показать группы">
          </form><?

        if ($_POST['TenantNdx'])
        {
          $recs=DB_MSSQL()->execSQL('select * from Groups where TenantNdx="'.$_POST['TenantNdx'].'"',array('no_indx'=>1,'debug'=>1)) ;
          print_2x_arr($recs) ;

          $recs=DB_MSSQL()->execSQL('select * from RptGroups where TenantNdx="'.$_POST['TenantNdx'].'"',array('no_indx'=>1,'debug'=>1)) ;
          print_2x_arr($recs) ;

        }

    }

    function mssql_member_operation()
    {  ?><h1>Операции с сотрудником</h1><?
          ?><form method="POST">
               TenantNdx: <input type="text" name="TenantNdx" value="<?echo $_POST['TenantNdx']?>">
               IndivId: <input type="text" name="IndivId" value="<?echo $_POST['IndivId']?>">
               <input cmd=mssql_member_operation type="submit" value="Искать"></form>


          <?
           $recs=array() ;
          if ($_POST['TenantNdx'] and $_POST['IndivId'])
          {
            $recs=DB_MSSQL()->execSQL('select * from Individuals where TenantNdx="'.$_POST['TenantNdx'].'" and IndivId="'.$_POST['IndivId'].'"',array('no_indx'=>1,'debug'=>1)) ;
            print_2x_arr($recs) ;
          }

          if (_sizeof($recs[0]))
          {?><form  method="POST">
               GroupID: <input type="text" name="GroupID" value="<?echo ($_POST['GroupID'])? $_POST['GroupID']:536871034?>">
               <input type="hidden" name="TenantNdx" value="<?echo $_POST['TenantNdx']?>">
               <input type="hidden" name="IndivId" value="<?echo $_POST['IndivId']?>">
               <input cmd=mssql_member_operation mode=AddGroup type="submit" value="Добавть группу">
            </form><?}

          if (_sizeof($recs[0]))
          {?><form  method="POST">
               <input type="hidden" name="TenantNdx" value="<?echo $_POST['TenantNdx']?>">
               <input type="hidden" name="IndivId" value="<?echo $_POST['IndivId']?>">
               <input cmd=mssql_member_operation mode=ChangePhoto type="submit" value="Изменить фото">
            </form><?}

          if ($_POST['TenantNdx'] and $_POST['IndivId'] and $_POST['GroupID'])
          {
                $sql="BEGIN TRANSACTION ; insert into XRefIndivGroupDoor (TenantNdx,IndivNdx,DoorGroupNdx,PriorityOrder,DoorSchedule) values ('".$_POST['TenantNdx']."','".$_POST['IndivId']."','".$_POST['GroupID']."',1,0); COMMIT  ; " ;
                echo $sql ;
                DB_MSSQL()->execSQL_update($sql) ;
          }

          if ($_POST['TenantNdx'] and $_POST['IndivId'] and $_POST['new_img'])
          {
                $img_cont=file_get_contents(_DIR_TO_ROOT.'/user_test.jpg') ;
                $data = unpack("H*hex", $img_cont);
                $sql="BEGIN TRANSACTION ; insert into IndivImages (TenantNdx,IndivNdx,UserImage) values ('".$_POST['TenantNdx']."','".$_POST['IndivId']."',0x".$data['hex'].") ; COMMIT  ; " ;
                DB_MSSQL()->execSQL_update($sql) ;
          }


    }

   //----------------------------------------------------------------------------------------------------------------------------------------------------------
   //
   // СКД
   //
   //----------------------------------------------------------------------------------------------------------------------------------------------------------


    function skd_check_import_HR()
    {
       include_once(_DIR_EXT.'/HR/i_HR.php') ;
       //HR()->xml_file_check('/home/satellite/folder/DPROD/skud_personal.xml') ;
       HR()->xml_file_import('/var/www/satellite/folder/skud_personal.xml',array('check_mode'=>1)) ;
    }

    function skd_exec_import_HR()
    {
       include_once(_DIR_EXT.'/HR/i_HR.php') ;
       //HR()->xml_file_check('/home/satellite/folder/DPROD/skud_personal.xml') ;
       HR()->xml_file_import('/var/www/satellite/folder/skud_personal.xml') ;
    }

   function skd_get_access_by_skippass()
    {$recs_turnket=execSQL('select * from obj_site_skd where clss=601 and device_ID>0 order by parent,pkey') ;
      //damp_array($_POST) ;
     ?><h1>Получение доступа по пропуску</h1><?
     ?><form method="POST">
          Пропуск: <input type="text" name="PassId" value="<?echo $_POST['PassId']?>">&nbsp;&nbsp;
          Турникет: <select name="turnID"><?foreach($recs_turnket as $rec_turn){?><option value="<?echo $rec_turn['device_ID']?>" <?if ($_POST['turnID']==$rec_turn['device_ID']) echo 'selected'?>><?echo SKD()->get_full_zone_path($rec_turn['parent']).' ['.$rec_turn['device_ID'].']'?></option><?}?></select>
          Направление: <select name="access_type"><option id="0" <?if (!$_POST['access_type']) echo 'selected'?>>Вход</option>
                                                  <option id="1" <?if ($_POST['access_type']==1) echo 'selected'?>>Выход</option>
                       </select>
          <br>
          <input cmd=skd_get_access_by_skippass type="submit" mode=find value="Проверить">

     <?
     if ($_POST['PassId'] and $_POST['turnID'])
     { $access_type=$_POST['access_type'] ;
       $rec_terminal=SKD()->get_device_by_id($_POST['turnID'],array('debug'=>1)) ;
       if ($rec_terminal['in_out_reverse'])
       {   if ($access_type) $access_type=0 ; else $access_type=1 ; }



       // получаем разрешение на доступ на основе id терминала, номера пропуска, направления прохода
       $access=SKD()->get_access_by_skippass($rec_terminal,$_POST['PassId'],$access_type,array('debug'=>2)) ;
       damp_array($access,1,-1) ;

       if ($access['pass_reffer'])
       { ?><h1>История событий по пропуску</h1><?
         ?><h1>Журнал обмена</h1><?
         $recs=execSQL('select * from obj_site_req_log where reffer1="'.$access['pass_reffer'].'" or reffer1="'.$access['pass_reffer'].'" or reffer2="'.$access['pass_reffer'].'" or reffer3="'.$access['pass_reffer'].'" or reffer4="'.$access['pass_reffer'].'" or reffer5="'.$access['pass_reffer'].'" order by pkey') ;
         print_2x_arr($recs) ;
         ?><h1>Журнал событий</h1><?
         $recs=execSQL('select * from obj_site_mo_log where reffer1="'.$access['pass_reffer'].'" or reffer1="'.$access['pass_reffer'].'" or reffer2="'.$access['pass_reffer'].'" or reffer3="'.$access['pass_reffer'].'" or reffer4="'.$access['pass_reffer'].'" or reffer5="'.$access['pass_reffer'].'" order by pkey') ;
         print_2x_arr($recs) ;
         ?><h1>Журнал проходов</h1><?
         $recs=execSQL('select * from obj_site_gate_events where pass_type="'.$access['pass_type_id'].'" and pass_id="'.$access['pass_id'].'"  order by pkey') ;
         print_2x_arr($recs) ;

       }
     }
     ?></form><?
    }

    function skd_update_time_out()
    {
      $recs=execSQL('select pkey,c_data,pass_type,pass_id,evt_out_id,evt_out_time from obj_site_gate_events where evt_type=2 and access_type=0 and (evt_out_id is null or evt_out_id=0)',1) ;
      //$recs=execSQL('select pkey,c_data,pass_type,pass_id,evt_out_id,evt_out_time from obj_site_gate_events where evt_type=2 and access_type=0',1) ;
      foreach($recs as $rec)
      { $rec_out=execSQL_van('select pkey,c_data,zone_id,device_id from obj_site_gate_events where pass_type='.$rec['pass_type'].' and pass_id='.$rec['pass_id'].' and evt_type in (2,3) and access_type in (1,2) and result=1 and pkey>'.$rec['pkey'].' order by pkey limit 1') ;
        update_rec_in_table('obj_site_gate_events',array('evt_out_id'=>$rec_out['pkey'],'evt_out_time'=>$rec_out['c_data'],'evt_out_zone'=>$rec_out['zone_id'],'evt_out_dev'=>$rec_out['device_id']),'pkey='.$rec['pkey']) ;

      }
      $recs=execSQL('select pkey,c_data,evt_out_id,zone_id,device_id from obj_site_gate_events where evt_type=2 and access_type=0 and result=1 and evt_out_id>0 order by c_data',1) ;
      foreach($recs as $rec_in)
      { update_rec_in_table('obj_site_gate_events',array('evt_out_id'=>$rec_in['pkey'],'evt_out_time'=>$rec_in['c_data'],'evt_out_zone'=>$rec_in['zone_id'],'evt_out_dev'=>$rec_in['device_id']),'pkey='.$rec_in['evt_out_id']) ;
      }

    }

    function get_log_info_to_pass_one()
    {

    }


   function skd_delete_DEMO_persons()
   {   ?><h1>DEMO персонал</h1><?
       if ($_POST['mode']=='delete')
       { ob_start() ;
         echo '<h2>Удаляем DEMO персоны</h2>' ;
         $recs=execSQL('select * from obj_site_persons where demo=1') ;
         foreach($recs as $rec_person)
           {  echo '<h3>'.$rec_person['obj_name'].'</h3>' ;
              // корректия таблицы разовых пропусков
              $count=execSQL_update('delete from obj_site_pass_van where personal_id='.$rec_person['pkey']) ;
              if ($count) echo 'delete '.$count.' записей из таблицы разовых пропусков [obj_site_pass_van]<br>' ;
              // корректия таблицы временных пропусков
              $count=execSQL_update('delete from obj_site_pass_time where personal_id='.$rec_person['pkey']) ;
              if ($count) echo 'delete '.$count.' записей из таблицы временных пропусков [obj_site_pass_time]<br>' ;
              // корректия таблицы зон доступа временных пропусков
              $count=execSQL_update('delete from obj_site_pdp where person_id='.$rec_person['pkey']) ;
              if ($count) echo 'delete '.$count.' записей из таблицы зон доступа временных пропусков [obj_site_pdp]<br>' ;
              // корректия фото посетителя
              $count=execSQL_update('delete from obj_site_personals_temporary_image where parent='.$rec_person['pkey']) ;
              if ($count) echo 'delete '.$count.' записей из таблицы фото посетителя [obj_site_personals_temporary_image]<br>' ;
              // корректия Журнал событий прохода
              $count=execSQL_update('delete from obj_site_gate_events where person_id='.$rec_person['pkey']) ;
              if ($count) echo 'delete '.$count.' записей из таблицы Журнал событий прохода [obj_site_gate_events]<br>' ;
              // корректия персон в заявках на разовые пропуска
              $count=execSQL_update('delete from obj_site_request_pass_persons where personal_id='.$rec_person['pkey']) ;
              if ($count) echo 'delete '.$count.' записей из таблицы персон в заявках на разовые пропуска [obj_site_request_pass_persons]<br>' ;
              // корректия журнала событий
              $count=execSQL_update('delete from obj_site_mo_log where member_id='.$rec_person['pkey']) ;
              $count+=execSQL_update('delete from obj_site_mo_log where reffer1="'.$rec_person['pkey'].'.283"') ;
              $count+=execSQL_update('delete from obj_site_mo_log where reffer2="'.$rec_person['pkey'].'.283"') ;
              $count+=execSQL_update('delete from obj_site_mo_log where reffer3="'.$rec_person['pkey'].'.283"') ;
              $count+=execSQL_update('delete from obj_site_mo_log where reffer4="'.$rec_person['pkey'].'.283"') ;
              $count+=execSQL_update('delete from obj_site_mo_log where reffer5="'.$rec_person['pkey'].'.283"') ;
              if ($count) echo 'delete '.$count.' записей из таблицы журнала событий [obj_site_mo_log]<br>' ;

              // корректия журнала обмена
              $count=execSQL_update('delete from obj_site_req_log where personal_id='.$rec_person['pkey']) ;
              $count+=execSQL_update('delete from obj_site_req_log where reffer1="'.$rec_person['pkey'].'.283"') ;
              $count+=execSQL_update('delete from obj_site_req_log where reffer2="'.$rec_person['pkey'].'.283"') ;
              $count+=execSQL_update('delete from obj_site_req_log where reffer3="'.$rec_person['pkey'].'.283"') ;
              $count+=execSQL_update('delete from obj_site_req_log where reffer4="'.$rec_person['pkey'].'.283"') ;
              $count+=execSQL_update('delete from obj_site_req_log where reffer5="'.$rec_person['pkey'].'.283"') ;
              if ($count) echo 'delete '.$count.' записей из таблицы журнала обмена [obj_site_req_log]<br>' ;

              // удаляем дубликат из базы
              $count=execSQL_update('delete from obj_site_persons where pkey="'.$rec_person['pkey'].'"') ;
              if ($count) echo 'delete '.$count.' записей из таблицы посетителей [obj_site_persons]<br>' ;


           }
         $text=ob_get_clean() ;
         echo $text ;
         _event_reg('Удаляем DEMO персоны',$text) ;

       }

       $recs=execSQL('select * from obj_site_persons where demo=1') ;
       if (_sizeof($recs))
       { print_2x_arr($recs) ;
         ?><form method="POST"><input cmd=skd_delete_DEMO_persons type="submit" mode=delete value="Удалить"></form><?
       }
       else echo '<div class=alert>DEMO персон не обнаружено</div>' ;

   }

   function skd_merge_diplicate_persons()
   {
       ?><h1>Объединение дубликатов персон</h1><?
       if ($_POST['mode']=='merge')
       { ob_start() ;
         echo '<h2>Объединяем дубликаты персон</h2>' ;
         $recs=execSQL('select concat(obj_name,"_",dr,"",doc_type,"_",doc_seria,"_",doc_number) as name,count(pkey) as cnt,obj_name,dr,doc_type,doc_seria,doc_number from obj_site_persons where clss=511 group by name having name!="" and cnt>1 order by cnt desc ',0,1) ;
         //print_2x_arr($recs) ;
         if (_sizeof($recs)) foreach($recs as $rec)
        {  ?><h2><?echo $rec['name']?></h2><?
            $cnt_pass_time=0 ; $cnt_pass_one=0 ;
           $recs_persons=execSQL('select * from obj_site_persons where obj_name="'.$rec['obj_name'].'" and dr="'.$rec['dr'].'" and doc_type="'.$rec['doc_type'].'" and doc_seria="'.$rec['doc_seria'].'" and doc_number="'.$rec['doc_number'].'" order by pkey',0,1) ;
           print_2x_arr($recs_persons) ;
           if (_sizeof($recs_persons)) $cnt_pass_one=execSQL_value('select count(pkey) from obj_site_pass_van where personal_id in ('.implode(',',array_keys($recs_persons)).')') ;
           if ($cnt_pass_one) echo 'Разовых пропусков:'.$cnt_pass_one.'<br>' ;
           if (_sizeof($recs_persons)) $cnt_pass_time=execSQL_value('select count(pkey) from obj_site_pass_time where personal_id in ('.implode(',',array_keys($recs_persons)).')') ;
           if ($cnt_pass_time) echo 'Временных пропусков:'.$cnt_pass_time.'<br>' ;
           if (_sizeof($recs_persons)!=$rec['cnt']){?><div class="alert">НЕ ВСЕ</div><?}
           foreach($recs_persons as $i=>$rec_person) if (!$i) $main_id=$rec_person['pkey']    ;
           else
           {  // корректия таблицы разовых пропусков
              $count=execSQL_update('update obj_site_pass_van set personal_id='.$main_id.' where personal_id='.$rec_person['pkey']) ;
              if ($count) echo 'merge '.$count.' записей из таблицы разовых пропусков [obj_site_pass_van]<br>' ;
              // корректия таблицы временных пропусков
              $count=execSQL_update('update obj_site_pass_time set personal_id='.$main_id.' where personal_id='.$rec_person['pkey']) ;
              if ($count) echo 'merge '.$count.' записей из таблицы временных пропусков [obj_site_pass_time]<br>' ;
              // корректия таблицы зон доступа временных пропусков
              $count=execSQL_update('update obj_site_pdp set person_id='.$main_id.' where person_id='.$rec_person['pkey']) ;
              if ($count) echo 'merge '.$count.' записей из таблицы зон доступа временных пропусков [obj_site_pdp]<br>' ;
              // корректия фото посетителя
              $count=execSQL_update('update obj_site_personals_temporary_image set parent='.$main_id.' where parent='.$rec_person['pkey']) ;
              if ($count) echo 'merge '.$count.' записей из таблицы фото посетителя [obj_site_personals_temporary_image]<br>' ;
              // корректия Журнал событий прохода
              $count=execSQL_update('update obj_site_gate_events set person_id='.$main_id.' where person_id='.$rec_person['pkey']) ;
              if ($count) echo 'merge '.$count.' записей из таблицы Журнал событий прохода [obj_site_gate_events]<br>' ;
              // корректия персон в заявках на разовые пропуска
              $count=execSQL_update('update obj_site_request_pass_persons set personal_id='.$main_id.' where personal_id='.$rec_person['pkey']) ;
              if ($count) echo 'merge '.$count.' записей из таблицы персон в заявках на разовые пропуска [obj_site_request_pass_persons]<br>' ;
              // корректия журнала событий
              $count=execSQL_update('update obj_site_mo_log set member_id='.$main_id.' where member_id='.$rec_person['pkey']) ;
              $count+=execSQL_update('update obj_site_mo_log set reffer1="'.$main_id.'.283" where reffer1="'.$rec_person['pkey'].'.283"') ;
              $count+=execSQL_update('update obj_site_mo_log set reffer2="'.$main_id.'.283" where reffer2="'.$rec_person['pkey'].'.283"') ;
              $count+=execSQL_update('update obj_site_mo_log set reffer3="'.$main_id.'.283" where reffer3="'.$rec_person['pkey'].'.283"') ;
              $count+=execSQL_update('update obj_site_mo_log set reffer4="'.$main_id.'.283" where reffer4="'.$rec_person['pkey'].'.283"') ;
              $count+=execSQL_update('update obj_site_mo_log set reffer5="'.$main_id.'.283" where reffer5="'.$rec_person['pkey'].'.283"') ;
              if ($count) echo 'merge '.$count.' записей из таблицы журнала событий [obj_site_mo_log]<br>' ;

              // корректия журнала обмена
              execSQL_update('update obj_site_req_log set personal_id='.$main_id.' where personal_id='.$rec_person['pkey']) ;
              execSQL_update('update obj_site_req_log set reffer1="'.$main_id.'.283" where reffer1="'.$rec_person['pkey'].'.283"') ;
              execSQL_update('update obj_site_req_log set reffer2="'.$main_id.'.283" where reffer2="'.$rec_person['pkey'].'.283"') ;
              execSQL_update('update obj_site_req_log set reffer3="'.$main_id.'.283" where reffer3="'.$rec_person['pkey'].'.283"') ;
              execSQL_update('update obj_site_req_log set reffer4="'.$main_id.'.283" where reffer4="'.$rec_person['pkey'].'.283"') ;
              execSQL_update('update obj_site_req_log set reffer5="'.$main_id.'.283" where reffer5="'.$rec_person['pkey'].'.283"') ;
              if ($count) echo 'merge '.$count.' записей из таблицы журнала обмена [obj_site_req_log]<br>' ;

              // удаляем дубликат из базы
              $count=execSQL_update('delete from obj_site_persons where pkey="'.$rec_person['pkey'].'"') ;
              if ($count) echo 'delete '.$count.' записей из таблицы посетителей [obj_site_persons]<br>' ;
           }
          // break ;
        }
         $text=ob_get_clean() ;
         echo $text ;
         _event_reg('Объединяем дубликаты персон',$text) ;
       }

       $recs=execSQL('select concat(obj_name,"_",dr,"",doc_type,"_",doc_seria,"_",doc_number) as name,count(pkey) as cnt,obj_name,dr,doc_type,doc_seria,doc_number from obj_site_persons where clss=511 group by name having name!=""  and cnt>1 order by cnt desc ',0,1) ;
       if (_sizeof($recs))
       { print_2x_arr($recs) ;
         ?><form method="POST"><input cmd=skd_merge_diplicate_persons type="submit" mode=merge value="Объеденить"></form><?
       }
       else echo '<div class=alert>Дубликатов персон не обнаружено</div>' ;


   }

   function skd_delete_free_pass_log()
   {
     ?><h1>Удаляем потерянные записи из журнала проходов</h1><?
     $recs=execSQL('select * from '.SKD()->view_gate_events.' where _person_fio is null',2) ;
   }


   function skd_delete_log_events()
   { if ($_POST['action'])
        { $recs=execSQL_update('delete from obj_site_mo_log where obj_name like "'.trim($_POST['action']).'"',2) ;
        }
     ?><h1>Удаляем избранные записи журнала событий</h1><?
     $recs=execSQL_row('select obj_name,count(pkey) as cnt from obj_site_mo_log GROUP by obj_name order by cnt desc') ;
     damp_array($recs,1,-1) ;
     ?><form method="POST">
          Операция: <input type="text" name="action" class=big value="<?echo $_POST['action']?>">&nbsp;&nbsp;
          <br>
          <br>
          <input cmd=skd_delete_log_events type="submit" value="Удалить">

     <?

     ?></form><?
   }

   function clear_names()
   { $cnt1=execSQL_value('select count(pkey) as name from view_personals where clss=211 ') ;
     $cnt2=execSQL_value('select count(pkey) as name from view_personals where clss in (207,208) ') ;
     ?><h2>Обезличивание личных данных персонала</h2>
       <p>Все фамилии сотрудников будут заменены на обезличенные данные, <?echo $cnt1?> позиций</p>
       <h2>Обезличивание названий организаций</h2>
       <p>Все названия организаций будут заменены на обезличенные данные, <?echo $cnt2?> позиций</p>
     <?

   }

   function rand_persons()
   {  ?><h1>Перетасовка личных данных персонала</h1><?
      ?><h2>Мужчины</h2><?
      $recs_m1=execSQL_line('select distinct(name1) as name from view_personals where clss=211 and pol!=1 and name1!="" order by name') ;
      ?>Фамилий - <strong><?echo _sizeof($recs_m1)?></strong><br><?
      $recs_m2=execSQL_line('select distinct(name2) as name from view_personals where clss=211 and pol!=1 and name2!=""  order by name') ;
      ?>Имен - <strong><?echo _sizeof($recs_m2)?></strong><br><?
      $recs_m3=execSQL_line('select distinct(name3) as name from view_personals where clss=211 and pol!=1 and name3!=""  order by name') ;
      ?>Отчеств - <strong><?echo _sizeof($recs_m3)?></strong><br><?
      ?><h2>Женщины</h2><?

      $recs_w1=execSQL_line('select distinct(name1) as name from view_personals where clss=211 and pol=1 and name1!="" order by name') ;
      ?>Фамилий - <strong><?echo _sizeof($recs_w1)?></strong><br><?
      $recs_w2=execSQL_line('select distinct(name2) as name from view_personals where clss=211 and pol=1 and name2!="" order by name') ;
      ?>Имен - <strong><?echo _sizeof($recs_w2)?></strong><br><?
      $recs_w3=execSQL_line('select distinct(name3) as name from view_personals where clss=211 and pol=1 and name3!="" order by name') ;
      ?>Отчеств - <strong><?echo _sizeof($recs_w3)?></strong><br><?
      ?><form method="POST"><input cmd=rand_persons type="submit" action="random" value="Перетасовать"></form><?

      if ($_POST['action']=='random')
      { $ids=execSQL_row('select pkey,obj_name from view_personals where clss=211 and pol!=1',1) ;
        if (_sizeof($ids)) foreach($ids as $id=>$old_name)
        { $name1=$recs_m1[rand(0,_sizeof($recs_m1)-1)] ;
          $name2=$recs_m2[rand(0,_sizeof($recs_m2)-1)] ;
          $name3=$recs_m3[rand(0,_sizeof($recs_m3)-1)] ;
          $obj_name=$name1.' '.$name2.' '.$name3 ;
          $data=array('obj_name'=>$obj_name,'name1'=>$name1,'name2'=>$name2,'name3'=>$name3) ;
          echo $old_name.' => '.$data['obj_name'].'<br>' ;
          update_rec_in_table('view_personals',$data,'pkey='.$id) ;
        }
        $ids=execSQL_row('select pkey,obj_name from view_personals where clss=211 and pol=1',1) ;
        if (_sizeof($ids)) foreach($ids as $id=>$old_name)
        { $name1=$recs_w1[rand(0,_sizeof($recs_w1)-1)] ;
          $name2=$recs_w2[rand(0,_sizeof($recs_w2)-1)] ;
          $name3=$recs_w3[rand(0,_sizeof($recs_w3)-1)] ;
          $obj_name=$name1.' '.$name2.' '.$name3 ;
          $data=array('obj_name'=>$obj_name,'name1'=>$name1,'name2'=>$name2,'name3'=>$name3) ;
          echo $old_name.' => '.$data['obj_name'].'<br>' ;
          update_rec_in_table('view_personals',$data,'pkey='.$id) ;
        }
      }

   }

   function rand_org()
   {  ?><h1>Перетасовка названий организаций</h1><?
      $recs_m1=execSQL_line('select distinct(obj_name) as name from view_personals where clss in (207,208) order by name',2) ;

      $recs_w1=execSQL_line('select distinct(name1) as name from view_personals where clss=211 and pol=1 and name1!="" order by name') ;
      ?>Фамилий - <strong><?echo _sizeof($recs_w1)?></strong><br><?
      $recs_w2=execSQL_line('select distinct(name2) as name from view_personals where clss=211 and pol=1 and name2!="" order by name') ;
      ?>Имен - <strong><?echo _sizeof($recs_w2)?></strong><br><?
      $recs_w3=execSQL_line('select distinct(name3) as name from view_personals where clss=211 and pol=1 and name3!="" order by name') ;
      ?>Отчеств - <strong><?echo _sizeof($recs_w3)?></strong><br><?
      ?><form method="POST"><input cmd=rand_persons type="submit" action="random" value="Перетасовать"></form><?

      if ($_POST['action']=='random')
      { $ids=execSQL_row('select pkey,obj_name from view_personals where clss=211 and pol!=1',1) ;
        if (_sizeof($ids)) foreach($ids as $id=>$old_name)
        { $name1=$recs_m1[rand(0,_sizeof($recs_m1)-1)] ;
          $name2=$recs_m2[rand(0,_sizeof($recs_m2)-1)] ;
          $name3=$recs_m3[rand(0,_sizeof($recs_m3)-1)] ;
          $obj_name=$name1.' '.$name2.' '.$name3 ;
          $data=array('obj_name'=>$obj_name,'name1'=>$name1,'name2'=>$name2,'name3'=>$name3) ;
          echo $old_name.' => '.$data['obj_name'].'<br>' ;
          update_rec_in_table('view_personals',$data,'pkey='.$id) ;
        }
        $ids=execSQL_row('select pkey,obj_name from view_personals where clss=211 and pol=1',1) ;
        if (_sizeof($ids)) foreach($ids as $id=>$old_name)
        { $name1=$recs_w1[rand(0,_sizeof($recs_w1)-1)] ;
          $name2=$recs_w2[rand(0,_sizeof($recs_w2)-1)] ;
          $name3=$recs_w3[rand(0,_sizeof($recs_w3)-1)] ;
          $obj_name=$name1.' '.$name2.' '.$name3 ;
          $data=array('obj_name'=>$obj_name,'name1'=>$name1,'name2'=>$name2,'name3'=>$name3) ;
          echo $old_name.' => '.$data['obj_name'].'<br>' ;
          update_rec_in_table('view_personals',$data,'pkey='.$id) ;
        }
      }

   }

   function split_obj_name()
   {  ?><h1>Разбиваем obj_name на name1, name2, name3</h1><?
      $recs=execSQL('select * from view_personals where clss=211 and (name1="" or name2="" or name3="" or name1 is null or name2  is null or name3  is null) order by pkey',1) ;
      ?><form method="POST"><input cmd=split_obj_name type="submit" action="split" value="Разнести obj_name по колонкам"></form><?
      if ($_POST['action']=='split')
      { if (_sizeof($recs)) foreach($recs as $rec)
        { $arr=explode(' ',trim($rec['obj_name'])) ;
          if (!$arr[1]) { $arr[1]=$arr[2] ; }
          if (!$arr[2]) { $arr[2]=$arr[3] ; }

          $data=array('name1'=>$arr[0],'name2'=>$arr[1],'name3'=>$arr[2]) ;
          if (!$data['name1'] or !$data['name2'] or !$data['name3']) echo '<div class=red>' ;
          print_r($data) ; echo '<br>' ;
          if (!$data['name1'] or !$data['name2'] or !$data['name3']) echo '</div>' ;
          if (!$data['name1'] or !$data['name2'] or !$data['name3']) echo print_r($arr,true).'<br>' ;

          update_rec_in_table('obj_site_personals',$data,'pkey='.$rec['pkey']) ;

        }

      }

   }

   function update_flag_res()
   {
      execSQL_update('update obj_site_mo_session set res_n=3 where narko like "%зрачки%" or narko like "%Зрачки%" or narko like "%реакция%"',2) ;
   }


   function update_group_in_mo()
   {
     $arr_term=execSQL_row('select id,parent from obj_site_account where clss=203 ') ;
     if (_sizeof($arr_term)) foreach($arr_term as $terminal_id=>$group_id)
      execSQL_update('update obj_site_mo_session set group_id='.$group_id.' where terminal_id='.$terminal_id,2) ;

   }


   function create_pass_hash()
   {  $recs=execSQL('select * from obj_site_account where password!=""') ;
      if (_sizeof($recs)) foreach($recs as $rec) if (strlen($rec['password'])!=64)
      { $rec['password']=$rec['login'] ;
        $str=hash('sha256',$rec['login'].$rec['password']) ;
        echo 'Создан хеш для логина '.$rec['obj_name'].'<br>' ;
        //update_rec_in_table('obj_site_account',array('pass_hash'=>$str,'password=""'),'pkey='.$rec['pkey']) ;
        update_rec_in_table('obj_site_account',array('password'=>$str),'pkey='.$rec['pkey']) ;
      } else echo $rec['login'].' - хеш уже создан<br>' ;

   }

}

?>
