<?
class i_server
{ public $terminal_id ;
  public $personal_id ;
  public $mo_id ;
  public $mo_reffer ;
  public $rec_terminal ;
  public $is_log_request=1 ;
  public $JSON_source='' ;
  public $result_stream='output' ;
  public $data_in=array() ;
  public $data_out=array() ;
  public $operation=array() ;

  // прием команды от терминала
  function __construct($options=array())
  { set_time_point('start SERVER') ;  //return ;
  	if (!$options['data_in'])
  	{ $this->JSON_source = file_get_contents("php://input");
	  set_time_point('get INPUT') ;
	  $this->data_in=$this->load_json_utf8($this->JSON_source) ;
	  set_time_point('load_json_utf8') ;
    }
    else $this->data_in=$options['data_in'] ;
  	$this->operation=($options['operation'])? $options['operation']:$_GET['operation'] ;
  }

  function show(&$options=array()) { $this->body($options) ;}

	function body(&$options=array())
	  {
	    $GLOBALS['stack_sql_stats']=1 ;
	    $time_rec=time() ;
	    $size2=0 ;
	    ob_start() ;  //global $debug_db ; $debug_db=2 ;
	    $size1=strlen($this->JSON_source) ;
	    if (is_array($this->data_in) and _sizeof($this->data_in)) $this->data_out=$this->exec_operation($this->operation,$this->data_in) ;
	    else $this->data_out['error']='not_valid_JSON_scructure' ;

	    $this->data_out['LS_trace_SQL']=$GLOBALS['LS_trace_SQL'] ;
	    if ($this->mo_id) LOGS()->reg_file_log($this->operation.'_'.$this->mo_id.'.html',$this->JSON_source,array('no_append_time'=>1)) ;
	    else              LOGS()->reg_file_log($this->operation,$this->JSON_source) ;

	      $debug_db=0 ;
	    //show_time_line(2) ; ;
	    $debug=ob_get_clean() ;
	    //LOGS()->reg_log('WHOIS log',$debug) ;
	    if (is_array($this->data_out))
	    { //if ($debug) $this->data_out['args']['data']['reason'].=$debug ;
	      $text_json_out=json_encode($this->data_out) ;
	      $size2=strlen($text_json_out) ;
	      // возвращает ответ устройству
	      if ($this->result_stream=='output') echo $text_json_out ;
	      ob_end_flush() ; // отправляем все данные обратно
	    }

		  $this->data_in['_script_name']=$_SERVER['REQUEST_URI'] ;
	    // регистрируем запрос
	    $text_json_in=(is_array($this->data_in) and _sizeof($this->data_in))? json_encode($this->data_in,JSON_UNESCAPED_UNICODE):'' ;
	    $text_json_out=(is_array($this->data_out) and _sizeof($this->data_out))? json_encode($this->data_out,JSON_UNESCAPED_UNICODE):'' ;
	    if ($this->is_log_request)
	    LOGS()->log_request($_SERVER['REMOTE_ADDR'],IP,$this->operation,$text_json_in,$text_json_out,array('terminal_id'=>$this->terminal_id,
	                                                                                                         'personal_id'=>$this->personal_id,
	                                                                                                         'mo_id'=>$this->mo_id,
	                                                                                                         'size1'=>$size1,
	                                                                                                         'size2'=>$size2,
	                                                                                                         'time_rec'=>$time_rec)) ;

	    //if ($GLOBALS['LS_trace_SQL'])
	    { $GLOBALS['stack_sql_stats']=0 ;
	      ob_start() ;
	      damp_array($GLOBALS['sql_stats'],1,-1) ;
	      $text=ob_get_clean() ;
	      LOGS()->reg_file_log($this->operation.'_'.$this->mo_id.'_db.html',$text) ;
	    }
	  }

  function load_json_utf8($content_str)
    {  $bom = chr(0xEF).chr(0xBB).chr(0xBF);
        if(substr_compare($bom, $content_str, 0, strlen($bom)) == 0) $content_str = substr($content_str, strlen($bom));
        return json_decode($content_str,true);
    }

   function whois($data)
   {
     $number=$data['args']['id']['number'] ;
     $terminal_id=$data['args']['id']['terminal']  ; $this->terminal_id=$terminal_id ;

     //$rec_member=ESMO()->get_personal_by_driving_tab_number($number) ;     set_time_point('get_personal_by_driver') ;
     //include_once(_DIR_EXT.'/aspmo_client/i_client.php') ;
     //$client=new c_client() ;
     if ($data['args']['id']['debug_db']) $GLOBALS['debug_db']=$data['args']['id']['debug_db'] ;
     ob_start() ;
     //$rec_member=PERSONAL()->whois_personal($number,array('dop_usl'=>'enabled=1')) ;  $this->personal_id=$rec_member['pkey'] ;
	 $options_whois=array('only_enabled'=>1,'dop_usl'=>'enabled=1') ;
     if (strpos($number,'#')!==false) $rec_member=PERSONAL()->whois_personal($number,$options_whois) ; // QR код будет сгенерирован на основе ВУ и номера авто
     else                             $rec_member=PERSONAL()->get_personal(array('propusk'=>$number,'tab_number'=>$number),array('only_enabled'=>1,'set_rules'=>1,'set_QR_code'=>$GLOBALS['LS_person_field_to_qrcode'],'dop_usl'=>'enabled=1')) ;
     //$this->personal_id=$rec_member['pkey'] ;

     $result['date'] = date('Y-m-d H:i:s');
     $result['args']['terminal_type']='mt' ;
     $result['args']['id']['terminal']=$terminal_id ;
     // 09.10.2015 если по whois был передан номер авто и номер прав - отправляем в user их обратно
     // это позволит  при check_access сформировать QR код на основе номер авто и номер прав
     $result['args']['id']['user']=($rec_member['_rec_car']['pkey'])? $rec_member['_rec_car']['obj_name'].'#'.$rec_member['driving']:$rec_member['propusk'] ;
     $result['args']['message']=($rec_member['pkey'])? 'success':'failure' ;
     //$result['args']['data']['reason']=($rec_member['pkey'])? '':'Сотрудник не найден' ; ;
     $result['args']['data']['reason']=$rec_member['_reason'] ;

     $result['args']['data']['user_name']=$rec_member['obj_name'] ;
     $result['args']['data']['user_ID']=$rec_member['pkey'] ;
     $result['args']['data']['user_propusk']=$rec_member['propusk'] ;
     $result['args']['data']['user_tab_number']=$rec_member['tab_number'] ;
     $result['args']['data']['user_driving']=$rec_member['driving'] ;
     $result['args']['data']['user_UUID']=$rec_member['uid'] ;
     $img_cont=(file_exists($rec_member['_image_dir']))? base64_encode(file_get_contents($rec_member['_image_dir'])):'' ;
     $result['args']['data']['photo']=$img_cont ;        set_time_point('photo') ;
     if ($rec_member['_qrcode_source']) $result['args']['data']['photo']=$rec_member['_qrcode_source'] ;

     LOGS()->reg_log('WHOIS','"'.$number.'"  => '.$rec_member['obj_name'].' ['.$rec_member['propusk'].']',array('member_id'=>$rec_member['pkey'],'terminal_id'=>$terminal_id)) ;
     if ($data['args']['id']['debug_db']) $GLOBALS['debug_db']=0;
     $text_debug=ob_get_clean()  ;
     if ($data['args']['id']['debug_db']) $result['args']['data']['debug_db']=$text_debug ;
       set_time_point('reg_log') ;
     return($result) ;
   }

    function save_send_photo(&$data,$img_name,$options=array())
    { $arr=explode(';',$data) ; // ([0] => data:image/png [1] => base64,iVBOR......==)
      if (_sizeof($arr)==1) $img_string=base64_decode($data) ;  //echo $img_string ;
      else
      { $arr2=explode(',',$arr[1]) ; // ([0] => base64 [1] => iVBOR......==)
        $img_string=base64_decode($arr2[1]) ;
      }
      $img_dir=$img_name ;
      file_put_contents(_DIR_TO_ROOT.$img_dir,$img_string) ;

      // коррекция изображения с аклотестера
      if ($options['img_rotare']) ENGINE()->rotare_image(_DIR_TO_ROOT.$img_dir,_DIR_TO_ROOT.$img_dir,$options['img_rotare']) ;

      $data="<img width=150 zoom src='"._MAIN_PROTOCOL._MAIN_DOMAIN.$img_dir."'>" ; // ддя сохранения в журнале
    }

    function save_send_video(&$data,$video_name)
    { $img_string=base64_decode($data) ;  //echo $img_string ;
      $img_dir='/public/mo_video/'.$video_name ;
      file_put_contents(_DIR_TO_ROOT.$img_dir,$img_string) ;
      //$data="<img width=150 zoom src='"._MAIN_PROTOCOL._MAIN_DOMAIN.$img_dir."'>" ; // ддя сохранения в журнале
      $data=_MAIN_PROTOCOL._MAIN_DOMAIN.$img_dir."'" ; // ддя сохранения в журнале
    }

    function check_update($data)
    {
        $terminal_id=$data['args']['id']['terminal'] ; $this->terminal_id=$terminal_id ;
        $version=$data['args']['id']['version'] ;

        $arch = $data['args']['id']['arch'] ;
        switch ($arch) {
            case 'arm':
                $arch = '-arm';
                break;
            default:
                $arch = '';
        }

        $terminal=ESMO()->get_terminal_by_id($terminal_id,array('check_reboot'=>1)) ;
        if ($terminal['pkey'])
        { $group_setting=unserialize(execSQL_value('select settings from obj_site_account where pkey="'.$terminal['parent'].'"')) ;
          $timezone=($group_setting['timezone'])? $group_setting['timezone']:'Europe/Moscow' ;
          date_default_timezone_set($timezone) ;
        }
        $res = [];
        if ($terminal['pkey']) {
            if ($terminal['assigned_version'] && $version != $terminal['assigned_version']) {
                $res['version'] = $terminal['assigned_version'];
                $res['url'] = _PATH_TO_SITE.'/updates/esmo-'.$terminal['assigned_version'].$arch.'-installer';
            }
        }
        return $res;
    }

}
?>
