<?
function IO(){ if (!is_object($GLOBALS['IO'])) $GLOBALS['IO']=new c_io();return($GLOBALS['IO']);}

class c_io
{
    // ОТПРАВЛЯЕМ ЗАПРОС на адрес IP
    //function doPut($IP,$path,$cmd,$fields,$options=array())
    function doPut($protokol,$IP,$req='',$get_data='',$post_data='',$options=array())
    { $__times['start']=get_formatted_microtime() ;
      $server_url=$protokol.$IP.$req ;
      if ($get_data) $server_url.='?'.$get_data ;
      $post_data = (is_array($post_data)) ? http_build_query($post_data) : $post_data;
      parse_str($get_data,$get_params) ;
      $text_json_in=$post_data ;
      if ($options['show_url']) echo  $server_url.'<br>' ; 
        $GLOBALS['doPUT_url']=$server_url ;
      if($ch = curl_init($server_url))
      {   if ($GLOBALS['LS_debug_mode'])
          { $log_fname=_TEMP_DIR.'curl_'.date('d_m_Y_H_i_s').'.txt' ;
            $this->log_fname=$log_fname ;
            $f = fopen($log_fname, 'ab');
            curl_setopt($ch, CURLOPT_VERBOSE, true);
            curl_setopt($ch, CURLOPT_STDERR,$f );
          }
          
          
         //curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
         curl_setopt($ch, CURLOPT_REFERER, $_SERVER['HTTP_HOST']);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Length: ' . strlen($post_data),
                                                    'Content-Type: application/json'
                                                    )
                    );
         if ($post_data) curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
          $connect_timeout=($options['connect_timeout'])? $options['connect_timeout']:$GLOBALS['LS_curl_connect_timeout'] ;
          $timeout=($options['timeout'])? $options['timeout']:$GLOBALS['LS_curl_timeout'] ;
          curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,$connect_timeout);
          curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); //timeout in seconds

        if ($options['use_sertifikat'])
        {
          curl_setopt($ch, CURLOPT_CAINFO, _CA_CERT);
          curl_setopt($ch, CURLOPT_SSLCERT, _SERVER_CERT);
          curl_setopt($ch, CURLOPT_SSLKEY, _SERVER_KEY);

          if ($GLOBALS['LS_debug_mode'])
	    
	    {
		    echo 'CURLOPT_CAINFO='._CA_CERT.'<br>' ;
		    echo 'CURLOPT_SSLCERT='._SERVER_CERT.'<br>' ;
		    echo 'CURLOPT_SSLKEY='._SERVER_KEY.'<br>' ;
	    }
	}

        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,0);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);
          //print_r($options) ;
        if ($options['basic_login'] and $options['basic_pass'])
        { curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
          curl_setopt($ch,CURLOPT_USERPWD,$options['basic_login'].":".$options['basic_pass']);

        }
        $t=fixed_time() ;
         $res=curl_exec($ch);

         if ($GLOBALS['LS_debug_mode'])
         { fclose($f);
         $cont_debug=file_get_contents($log_fname);
         }
          
         $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); //echo '$status='.$status.'<br>' ;
         $error_text='' ;
          $t2=fixed_time($t) ;
         if ($status!=200 or $options['debug'])
         { ob_start() ;
           if ($status!=200) echo '<div class=alert>Ошибка ответа сервера: '.$status.'<br>'.$server_url.'<br></div>' ;
           else             echo '<div class=green>Ответ сервера: '.$status.'<br>'.$server_url.'<br></div>' ;
           $error=curl_error($ch);
           $error_text=' ['.$error.']' ;
           echo 'Ошибка curl: '.nl2br($error).'<br>'.nl2br($cont_debug) ;
           ?><h3>POST DATA</h3><?
           print_r($post_data) ;
           ?><h3>OPTIONS</h3><?
           damp_array($options,1,-1) ;
           $text=ob_get_clean() ;
           $url=LOGS()->reg_file_log('doPut',$text) ;
           echo $text ;
           LOGS()->reg_log('doPut','<span class=red>ERROR STATUS</span>: '.$status.'<br><a href="'.$url.'">Отчет</a>',array('time_exec'=>$t2)) ;

           // сохраняем в записи по терминалу информацию по ошибке и переводим термнал в статус "нет связи"
           //if ($options['terminal_id']) ESMO()->terminal_save($options['terminal_id'],array('status'=>8,'ext_info'=>array('curl_error'=>$error))) ;

           //if ($options['terminal_id'])
           //{   $term_rec=ESMO()->get_terminal_by_id($options['terminal_id']) ;
           //    if ($GLOBALS['LS_term_logging_full'])  ESMO()->terminal_save($term_rec['pkey'],array('status'=>8,'ext_info'=>array('curl_error'=>$error.' ['.$cont_debug.']'))) ;
           //}
         }
         else
         {

         }
        $size=curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
        //echo 'CURLINFO_CONTENT_LENGTH_DOWNLOAD: '.$size.'<br>' ;

         // если не отправляем команду на себя - регистрируем запрос
         parse_str($get_data,$get_params) ;
         $__times['end']=get_formatted_microtime() ;
         $time_int=$__times['end']-$__times['start'] ;
         if (!$options['no_log_request'])
         { $text_json_out=$res ;
           $options['size1']=strlen($text_json_in) ;
           $options['size2']=strlen($text_json_out) ;
           //$options['req_id']=$req_id ;
           //if ($GLOBALS['LS_debug_mode']) LOGS()->log_request($_SERVER['REMOTE_ADDR'],IP,$options['cmd'],'',$text_json_out,$options) ;
           //if ($GLOBALS['LS_debug_mode']) LOGS()->reg_log('doPut','url: '.$server_url.'<br>status: '.$status.$error_text,array('terminal_id'=>$options['terminal_id'],'personal_id'=>$options['personal_id'],'mo_id'=>$options['mo_id'],'time_exec'=>$time_int,'reffers'=>$options['reffers'])) ;
         }

         curl_close($ch);

         return $res;
      }
      else return false;
    }

 // ОТПРАВЛЯЕМ ЗАПРОС на адрес IP
    function doPut_v3($server_url,$send=array(),$options=array())
    { $url_log='' ;$get_data=''; $post_data='' ; $post_files=[];

      if (isset($send['get'])) $get_data = (is_array($send['get'])) ? http_build_query($send['get']) : $send['get'];
      if (isset($send['post'])) $post_data = (is_array($send['post'])) ? http_build_query($send['post']) : $send['post'];
         //if (isset($send['post'])) $post_data = (is_array($send['post'])) ? $send['post'] : $send['post'];
      if (isset($send['files'])) foreach($send['files'] as $varname=>$fname)
      {    $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $mime =  finfo_file($finfo, $fname);
            $curlFile = (function_exists('curl_file_create')? curl_file_create($fname, $mime, basename($fname)):'@'.realpath($fname));
            $post_files[$varname]=$curlFile ;


      }

      //для отправки каких-либо значений вместе с файлом как multipart/form-data
      if (isset($send['post_with_files']) and is_array($send['post_with_files']))
      {
            $post_files = array_merge($post_files,$send['post_with_files']);
      }

      //damp_array($post_files,1,-1) ;

      if ($get_data) $server_url.='?'.$get_data ;

      // на случай, если надо сначало залогировать, а потом отправлять запрос
      //$req_id=LOGS()->log_request(IP,$IP,$options['cmd'],$text_json_in,'',$options) ;
      if ($options['show_url']) echo  $server_url.'<br>' ;
      $result['server_url']=$server_url ;
      if ($get_data)  $result['GET']=$get_data ;
         if ($post_data) $result['POST']=htmlspecialchars($post_data) ;
         //if ($options) $result['options']=$options ;
      if($ch = curl_init($server_url))
      {
             $log_fname=_TEMP_DIR.'curl_'.ENGINE()->generate_UID().'.txt' ;
          $this->log_fname=$log_fname ;
          $f = fopen($log_fname, 'ab');
          curl_setopt($ch, CURLOPT_VERBOSE, true);
          curl_setopt($ch, CURLOPT_STDERR,$f );

         //curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
         curl_setopt($ch, CURLOPT_REFERER, $_SERVER['HTTP_HOST']);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

          if ($post_data) $options['headers'][]='Content-Length: '.strlen($post_data) ;
         if ($options['content_type']) switch($options['content_type'])
         { case 'json':  $options['headers'][]='Content-Type: application/json' ; break ;
           case 'xml':  $options['headers'][]='Content-Type: application/xml' ; break ;
           case 'file':  $options['headers'][]='Content-Type: multipart/form-data' ; break ;
           default:  $options['headers'][]='Content-Type: '.$options['content_type'] ;
         }  
         if ($options['headers'])  curl_setopt($ch, CURLOPT_HTTPHEADER, $options['headers']) ;
         
         if ($post_data or $post_files) curl_setopt($ch, CURLOPT_POST,1);
         if ($post_data) curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
         if ($post_files) curl_setopt($ch, CURLOPT_POSTFIELDS, $post_files);
         $connect_timeout=($options['connect_timeout'])? $options['connect_timeout']:$GLOBALS['LS_curl_connect_timeout'] ;
         $timeout=($options['timeout'])? $options['timeout']:$GLOBALS['LS_curl_timeout'] ;
         curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,$connect_timeout);
         curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); //timeout in seconds

        if ($options['use_sertifikat'])
        {
          curl_setopt($ch, CURLOPT_CAINFO, _CA_CERT);
          curl_setopt($ch, CURLOPT_SSLCERT, _SERVER_CERT);
          curl_setopt($ch, CURLOPT_SSLKEY, _SERVER_KEY);


          if ($GLOBALS['LS_debug_mode'])
	    
	    {
		    echo 'CURLOPT_CAINFO='._CA_CERT.'<br>' ;
		    echo 'CURLOPT_SSLCERT='._SERVER_CERT.'<br>' ;
		    echo 'CURLOPT_SSLKEY='._SERVER_KEY.'<br>' ;
	    }



        }

        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,0);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);

        if (isset($options['CURLOPT_NOPROGRESS'])) curl_setopt($ch,CURLOPT_NOPROGRESS,$options['CURLOPT_NOPROGRESS']);
        if (isset($options['CURLOPT_PROGRESSFUNCTION'])) curl_setopt($ch,CURLOPT_PROGRESSFUNCTION,$options['CURLOPT_PROGRESSFUNCTION']);

        if ($options['basic_login'] and $options['basic_pass'])
        { curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
          curl_setopt($ch,CURLOPT_USERPWD,$options['basic_login'].":".$options['basic_pass']);

        }

        if ($options['COOKIEJAR']) {
            curl_setopt($ch, CURLOPT_COOKIEJAR, $options['COOKIEJAR']);
        }

        if ($options['COOKIEFILE']) {
            curl_setopt($ch, CURLOPT_COOKIEFILE, $options['COOKIEFILE']);
        }
        $t=fixed_time() ;
          $content=curl_exec($ch);

         fclose($f);
         $cont_debug=file_get_contents($log_fname);

         $error=0 ;
         $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); //echo '$status='.$status.'<br>' ;
         if ($status!=200) $error=curl_error($ch);

         $size=curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
         curl_close($ch);
          $t2=fixed_time($t) ;

         $result['status']=$status ;
         $result['time_exec']=$t2 ;
         if (!$options['save_content_to_file']) $result['content']=$content ;
         $result['length']=$size ;

         // сохранение трассировки запроса в файл, имя файла в $result['log_url']
            if (!$status or $status>=300 or $options['debug'] or $options['log_request'])
         { ob_start() ;
           ?><h3>POST DATA</h3><?
              print_r(htmlspecialchars($post_data)) ;
           ?><h3>OPTIONS</h3><?
           damp_array($options,1,-1) ;
		    echo 'CURLOPT_CAINFO='._CA_CERT.'<br>' ;
		    echo 'CURLOPT_SSLCERT='._SERVER_CERT.'<br>' ;
		    echo 'CURLOPT_SSLKEY='._SERVER_KEY.'<br>' ;


         $c_info=curl_getinfo($ch,CURLINFO_SSL_VERIFYRESULT);
damp_array($c_info,1,-1) ;


           echo '<h3>RESPONSE HEADERS</h3>============================================<br>'.nl2br($cont_debug).'<br>============================================<br>' ;
           ?><h3>RESULT</h3><?
           damp_array($result,1,-1) ;
           $text=ob_get_clean() ;
           $url_log=LOGS()->reg_file_log('doPut',$text) ;
           $result['log_url']=_PATH_TO_SITE.$url_log ;
         }

            if ($status>=300)
         {  $result['send_error']=$error ;
            $result['send_response']='<div class=alert>Ошибка ответа сервера: '.$status.'</div>'.$server_url.'<br>Ошибка curl: '.$error.'<br><a href="'.$url_log.'">Отчет</a>' ;
               if (!$options['no_log_error']) LOGS()->reg_log('doPut','<span class=red>ERROR STATUS</span>: '.$status.'<br><a href="'.$url_log.'">Отчет</a>',array('time_exec'=>$t2)) ;
         }

         if ($options['save_content_to_file'])
             { file_put_contents($options['save_content_to_file'],$content) ;
               $result['content_save_fname']=$options['save_content_to_file'] ;
               $result['content_save_fsize']=filesize($options['save_content_to_file']) ;
             }

         // если не отправляем команду на себя - регистрируем запрос
         parse_str($get_data,$get_params) ;

         // если стоит опция - регистрации запроса - сохраняем запрос/ответ в отдельную таблицу
         if ($options['log_request'])
            {
              $text_json_in=$post_data ;
              $text_json_out=$content ;
           $options['status']=$status;
           $options['time_exec']=$t2;
           $options['req_url']=$result['server_url'];
           $options['req_type']=1;  // исходящий запрос
              $options['size1']=strlen($text_json_in) ;
              $options['size2']=strlen($text_json_out) ;
           $options['debug_text']='<a target=_blank href="'.$url_log.'">Отчет</a>' ;
           $options['content_type1']=$options['content_type'] ;
           $arr=parse_url($server_url) ;
              LOGS()->log_request($_SERVER['SERVER_ADDR'],$arr['host'],$options['cmd'],$text_json_in,$text_json_out,$options) ;
         }
      }
      else $result['status']=0 ;

      return $result;
    }

    // ОТПРАВЛЯЕМ ЗАПРОС на адрес IP
    function doPut_v2($protokol,$IP='',$req='',$get_data='',$post_data='',$options=array())
    { $server_url=$protokol.$IP.$req ;
      $data=array() ;
      if ($get_data) $data['get']=$get_data ;
      if ($post_data) $data['post']=$post_data ;
      $result=$this->doPut_v3($server_url,$data,$options) ;
      return($result) ;
    }

    function send_async_cmd($cmd,$options=array())
    { $__times['start']=get_formatted_microtime() ;
      $params=array('cmd'=>$cmd) ;
      if (is_array($options)) $params=array_merge($params,$options) ;
      $comm=_MAIN_PROTOCOL._MAIN_DOMAIN.'/async.php?'.http_build_query($params) ;
      //exec('bash -c "/usr/bin/wget  \"'.$comm.'\" > /dev/null 2>&1 &"',$output); // тоже работает но не async
      exec('bash -c "/usr/bin/wget -O /dev/null --no-check-certificate \"'.$comm.'\q" > /dev/null 2>&1 &"',$output); // тоже работает но не async
      $__times['end']=get_formatted_microtime() ;
      $time_int=$__times['end']-$__times['start'] ;
      $text=$cmd ;
      //$text.='<br>'.$comm ;
      //$text=http_build_query($params) ;
      LOGS()->reg_log('ASYNC CMD SET',$text,array('time_exec'=>$time_int)) ;
    }
}

?>