<?
// включение плагина на /cab/setting/moduls/
// код для вывода
// $this->form_checkbox_left('<strong>signature</strong>','Плагин работы с экранной подписью по лицу','IS[plugins][signature]',$GLOBALS['_SETTING']['plugins']['signature'],'i_signature') ;

function SIGNATURE() {if (is_object($GLOBALS['signature_plugin'])) return($GLOBALS['signature_plugin']);$GLOBALS['signature_plugin']=new i_signature();return($GLOBALS['signature_plugin']);} ;

class i_signature
{

 function declare_menu($page)
 {
	$page->menu['/cab/setting/']['items']['/cab/esmo_setting/mo/']['items']['/cab/esmo_setting/sv/']='Экранная подпись' ;
 }

 function install()
 {  $descr_class[259]['name']='Экранная подпись' ;
	$descr_class[259]['parent']=0 ;
	$descr_class[259]['fields']['mo_id']=array('type'=>'int(11)','default'=>0) ; // ID MO
	$descr_class[259]['fields']['quiz_id']=array('type'=>'int(11)','default'=>0) ; // ID КЗ
	$descr_class[259]['fields']['DTW_res']=array('type'=>'int(11)','default'=>0) ; // результат проверки экранной подписи
    $descr_class[259]['fields']['DTW_sign_result']=array('type'=>'float(10,5)','default'=>0) ; // результат проверки экранной подписи
    $descr_class[259]['fields']['signature_DTW_mp_Cost']=array('type'=>'float(10,5)','default'=>0) ; // результат проверки экранной подписи
    $descr_class[259]['fields']['signature_DTW_mp_Sum']=array('type'=>'float(10,3)','default'=>0) ; // результат проверки экранной подписи
    $descr_class[259]['fields']['signature_DTW_mp_Transform']=array('type'=>'float(10,3)','default'=>0) ; // результат проверки экранной подписи
    $descr_class[259]['fields']['signature_DTW_mp_StepCount']=array('type'=>'int(11)','default'=>0) ; // результат проверки экранной подписи
	$descr_class[259]['fields']['point_count']=array('type'=>'int(11)','default'=>0);
	$descr_class[259]['fields']['time_sign']=array('type'=>'int(11)','default'=>0);
	$descr_class[259]['fields']['point_per_sec']=array('type'=>'int(11)','default'=>0);
	$descr_class[259]['table_code']='DTW' ;

    SETUP()->reg_class($descr_class) ;

	$pattern=array() ;
    $pattern['table_title']				= 	'Экранная подпись' ;
    $pattern['use_clss']				= 	'259' ;
    $pattern['table_name']				= 	'obj_site_mo_session_DTW' ;
    $pattern['table_clss']				= 	101 ;
    create_table_by_pattern($pattern) ;

	// добавить возможность регистрации во вложенных меню!!!
	//SETUP()->reg_menu_item('main','signature','/cab/signature/') ;
	// $page->menu['/cab/setting/']['items']['/cab/esmo_setting/mo/']['items']['/cab/esmo_setting/sv/']='Подписи' ;


	//SETUP()->reg_ext('signature','signature') ;

	SETUP()->reg_report('Персонал','aspmo_sv/report_log_signatures.php') ;

    $id_sect = SETUP_add_section_to_site_setting('Подписи');

    SETUP_add_rec_to_site_setting($id_sect,"DTW_percent", 80, 'LS_sv_DTW_percent');
    SETUP_add_rec_to_site_setting($id_sect,"DTW_result", 35, 'LS_sv_DTW_result');
    SETUP_add_rec_to_site_setting($id_sect,"TimePercentLower", 10, 'LS_sv_TimePercentLower');
    SETUP_add_rec_to_site_setting($id_sect,"TimePercentUpper", 20, 'LS_sv_TimePercentUpper');

	SETUP()->reg_event_lister('examination_result_data_read','SIGNATURE','on_event_examination_result_data_read') ;         //
 }


public function mo_session_save_DTW($sess_id,$data,$DTW_res=array(),$options=array())
    {
        $time_sign=0 ;
        $point_count=0 ;
        $point_per_sec=0 ;

        if (isset($data))
        {
            $time_sign = $this->get_signature_time($data, true);
            $point_count = count($data);
            $point_per_sec =  ($time_sign > 0) ? floor(1000 * $point_count / $time_sign) : 0;
        }

	    $rec=array('clss'=>259,
	                'parent'=>$sess_id,
	                'mo_id'=>($options['mo_id'])? $options['mo_id']:0,
	                'quiz_id'=>($options['quiz_id'])? $options['quiz_id']:0,
	                'time_sign'=>$time_sign,
	                'point_count'=>$point_count,
	                'point_per_sec'=>$point_per_sec,
	    		    'DTW_sign_result' => (isset($DTW_res) && isset($DTW_res['cost'])) ? $DTW_res['cost'] : 100,
	    	        'DTW_res' => (isset($DTW_res) && $DTW_res['valid']) ? "1" : "0",
	    	        'signature_DTW_mp_Cost' => (isset($DTW_res['signature_DTW_mp_Cost'])) ? $DTW_res['signature_DTW_mp_Cost'] : "0",
	    	        'signature_DTW_mp_Sum' => (isset($DTW_res['signature_DTW_mp_Sum'])) ? $DTW_res['signature_DTW_mp_Sum'] : "0",
	    	        'signature_DTW_mp_Transform' => (isset($DTW_res['signature_DTW_mp_Transform'])) ? $DTW_res['signature_DTW_mp_Transform'] : "0",
	    	        'signature_DTW_mp_StepCount' => (isset($DTW_res['signature_DTW_mp_StepCount'])) ? $DTW_res['signature_DTW_mp_StepCount'] :  "0",
	    	        ) ;


        $id=adding_rec_to_table('obj_site_mo_session_DTW',$rec,array('debug'=>0)) ;

        return($id) ;
    }

    function check_sign($user_id, $data)
    {
        $result = array();
        $result['cost'] = 100; //maxcost
        $result['valid'] = 0;

        include_once(_DIR_EXT.'/aspmo_signature/class.DTW.php') ;

        $standart_sign_data = PERSONAL()->get_personal_sign_by_personal_id($user_id);

        if (!isset($standart_sign_data) || !$standart_sign_data) {
            return $result;
        }

        $standart_sign = unserialize($standart_sign_data);

        $obj_DTW = new DTW();
        $obj_DTW->setReference($standart_sign);
        $obj_DTW->setCheck($data);

        $result['cost'] = $obj_DTW->getMinCost();
        //$result['valid'] = ((100 - $GLOBALS['LS_sv_DTW_percent']) > $result['cost']) ? 1 : 0;
        $result['signature_DTW_mp_Cost'] = $obj_DTW->getMinPath();
        $result['signature_DTW_mp_Sum'] = $obj_DTW->getDTWResult();
        $result['signature_DTW_mp_Transform'] = $obj_DTW->getTransformResult();
        $result['signature_DTW_mp_StepCount'] = $obj_DTW->getStep();

        $s_time_st = $this->get_signature_time($standart_sign);
        $s_time = $this->get_signature_time($data);

        $diff_time_percent = false;

        if ($s_time_st > 0) {
            $diff_time_percent = (1 - $s_time / $s_time_st) * 100;
        }

        if ($result['signature_DTW_mp_Cost'] <= $GLOBALS['LS_sv_DTW_result'] &&
            //(100 - $GLOBALS['LS_sv_DTW_percent']) > $result['cost'] &&
            $s_time_st > 0 &&
            $diff_time_percent <= $GLOBALS['LS_sv_TimePercentUpper'] &&
            $diff_time_percent >= -$GLOBALS['LS_sv_TimePercentLower']) {

            $result['valid'] = 1;
        } else {
            $result['valid'] = 0;
        }

        return $result;
    }

    function get_signature_time($signature, $in_millisecond = false) {
        $last_point = array_pop($signature);
        $first_point = array_shift($signature);

        if ($in_millisecond) {
            return $last_point['t'] - $first_point['t'];
        }

        return number_format(($last_point['t'] - $first_point['t']) / 1000, 3) ;
    }

    function get_signature_time_by_str_sign($signature, $in_millisecond = false) {
        if (!$signature) {
            return false;
        }

        return $this->get_signature_time(unserialize($signature), $in_millisecond);
    }

    function recalculate_signatures($personal_id, $sign_id)
    {
        $res=execSQL("select mos.pkey, mosDTW.obj_name from obj_site_mo_session as mos "
             . "left join obj_site_mo_session_DTW as mosDTW on mosDTW.parent = mos.pkey "
             . "where mos.member_id=".$personal_id." order by mos.pkey");

        foreach($res as $rec) {
            if (isset($rec['obj_name'])) {
                $DTW_res = $this->check_sign($personal_id, unserialize($rec['obj_name'])) ;
            } else {
                $DTW_res['cost'] = 100;
                $DTW_res['valid'] = 0;
            }
            ESMO()->update_mo_session($rec['pkey'], array('DTW_sign_result' => (isset($DTW_res) && isset($DTW_res['cost'])) ? $DTW_res['cost'] : 100,
                                                                'DTW_res' => (isset($DTW_res) && $DTW_res['valid']) ? "1" : "0",
                                                                'signature_DTW_mp_Cost' => $DTW_res['signature_DTW_mp_Cost'],
                                                                'signature_DTW_mp_Sum' => $DTW_res['signature_DTW_mp_Sum'],
                                                                'signature_DTW_mp_Transform' => $DTW_res['signature_DTW_mp_Transform'],
                                                                'signature_DTW_mp_StepCount' => $DTW_res['signature_DTW_mp_StepCount']));
        }

        return $res;
    }
    /*
    function get_result_sign_verification($rec)
    {
        $rec['DTW_sign_result'] = floor(100 - $rec['DTW_sign_result']);

        //$member = execSQL_van('select sign_id from obj_site_personals where pkey='.$rec['member_id']);

        //$rec['st_sign_id'] = $member['sign_id'];

        return $rec;
    }
    */
    function save_DTW_data_to_js($str_data, $key, $variable_name = 'sample1') {
        if ($str_data) {
            $data=unserialize($str_data) ;  //damp_array($data) ;
            $out=new stdClass() ;
            $cur_level=&$out ;
            $all_points=_sizeof($data)-1 ; // echo  $all_points ;
            $t1=$data[0]['t'] ;  $t_abs=0 ;

            foreach($data as $i=>$value)
            {
            $t2=$data[$i+1]['t'] ;
            $int=($t2-$t1) ;
            $obj=new stdClass() ;
            $obj->type=$value['type'] ;
            $obj->x=$value['x'] ;
            $obj->y=$value['y'] ;
            $obj->isMovable=false ;
            $obj->index=0 ;
            $obj->actionType=1 ;
            $cur_level->actions[]=$obj ;

            if ($int>0)
            {
                $t_abs=$t_abs+$int ;
                $cur_level->interval=$t_abs ;
            }

            if ($i!=$all_points)
            {
                $cur_level->next=new stdClass()  ;
                $cur_level=&$cur_level->next ;
            }
                $t1=$value['t'] ;
            }
        }

        $script_name='sign_'.$key.'.js' ;
        file_put_contents(_TEMP_DIR.$script_name,'var ' . $variable_name . ' = '.json_encode($out).';');

        return $script_name;
    }

    function save_DTW_data_to_js_by_id($DTW_id, $variable_name = 'sample1')
    {   $rec_DTW=execSQL_van("select * from obj_site_mo_session_DTW where pkey=".$DTW_id);
        $content='' ;
        $file_dir=ESMO()->get_mo_DTW_data_dir_by_id($rec_DTW['pkey'],'dir') ; // старая схема
	    if ($file_dir) $content=file_get_contents($file_dir) ;
        if (strlen($content)) $result=$this->save_DTW_data_to_js($content, $rec_DTW['pkey'], $variable_name) ;
        else $result='no_DWT_data' ;
        return $result;
    }

    // вспомогательная функция для пересчета точек, вермени и соотношения точек/времени подписи
    // надо удалить после переноса c_server версии 2.14.1.edison
    function recalculate_number_of_points()
    {
        $res=execSQL("SELECT `pkey`, `obj_name`  FROM `obj_site_mo_session_DTW` WHERE `time_sign` = 0 ORDER BY `pkey` DESC");

        foreach($res as $rec) {
            $data = unserialize($rec['obj_name']);

            $time_sign = $this->get_signature_time($data, true);
            $point_count = count($data);
            $point_per_sec = ($time_sign > 0) ? floor(1000 * $point_count / $time_sign ) : 0;

            $fields = array('time_sign' => $time_sign, 'point_count' => $point_count, 'point_per_sec' => $point_per_sec);

            update_rec_in_table('obj_site_mo_session_DTW', $fields, 'pkey=' . $rec['pkey']) ;

        }
    }


	function on_event_examination_result_data_read(&$data,$rec_personal,$rec_session)
	{   ob_start() ;
		$session_id=$rec_session['pkey'] ; $DTW_res=array() ; $options_save_DTW=array() ;
	    echo '<strong>SIGNATURE: on_event_examination_result_data_read</strong><br>' ;

        if ($data['args']['terminal_type']=='mt') $options_save_DTW['mo_id']=$session_id ;
        if ($data['args']['terminal_type']=='kz') $options_save_DTW['quiz_id']=$session_id ;

        $DTW_id=$this->mo_session_save_DTW($session_id,$data['args']['data']['signature']['data'],$DTW_res,$options_save_DTW);
       	echo 'Сохранена запись save_DTW: '.$DTW_id.'<br>' ;


		// распознование экранной подписи
		// более не генерим подпись на основании оцифровки
		// показываем подпись сотрудника из изходной картинки
		// на странице МО будет показана подпись другим способом
		if ($data['args']['data']['signature']['image'])
		{   echo 'Обнаружено signature image - сохраняем на диск<br>' ;
			$options=array('check_directory'=>1,'no_check_exist_file'=>1) ;
			if ($data['args']['terminal_type']=='mt') $options['base_dir']='/public/mo_sign_image/' ;
			if ($data['args']['terminal_type']=='kz') $options['base_dir']='/public/quiz_sign_image/' ;
			$img_dir=ENGINE()->get_dir_by_id($session_id,'relative','_DTW.png',$options) ;
			echo 'Изображение подписи сохранено в <strong>'.$img_dir.'</strong><br>' ;
		    if ($img_dir) $this->save_send_photo($data['args']['data']['signature']['image'],$img_dir) ;
		}

		if ($data['args']['data']['signature']['data'])
		{  echo 'Обнаружено signature data - делаем расчет и сохраняем на диск<br>' ;
		   $DTW_res = $this->check_sign($rec_personal['pkey'], $data['args']['data']['signature']['data']) ;
		   ?>DTW_res:<br><?
		   damp_array($DTW_res,1,-1);
		   $options=array('check_directory'=>1,'no_check_exist_file'=>1) ;
		   if ($data['args']['terminal_type']=='mt') $options['base_dir']='/public/mo_sign/' ;
		   if ($data['args']['terminal_type']=='kz') $options['base_dir']='/public/quiz_sign_data/' ;
		   $data_dir=ENGINE()->get_dir_by_id($DTW_id,'relative','.data',$options) ;
		   echo 'Сигнатура подписи сохранена в <strong>'.$data_dir.'</strong><br>' ;
		   if ($data_dir) file_put_contents(_DIR_TO_ROOT.$data_dir,serialize($data['args']['data']['signature']['data'])) ;
        }

        // сохраняем данные измерений в запись МО
       $rec=array(    // 'DTW_id' => $DTW_id,
                       'DTW_sign_result' => (isset($DTW_res) && isset($DTW_res['cost'])) ? $DTW_res['cost'] : 100,
                       'DTW_res' => (isset($DTW_res) && $DTW_res['valid']) ? "1" : "0",
                       'signature_DTW_mp_Cost' => (isset($DTW_res['signature_DTW_mp_Cost'])) ? $DTW_res['signature_DTW_mp_Cost'] : "0",
                       'signature_DTW_mp_Sum' => (isset($DTW_res['signature_DTW_mp_Sum'])) ? $DTW_res['signature_DTW_mp_Sum'] : "0",
                       'signature_DTW_mp_Transform' => (isset($DTW_res['signature_DTW_mp_Transform'])) ? $DTW_res['signature_DTW_mp_Transform'] : "0",
                       'signature_DTW_mp_StepCount' => (isset($DTW_res['signature_DTW_mp_StepCount'])) ? $DTW_res['signature_DTW_mp_StepCount'] :  "0",
                   ) ;

        if ($data['args']['terminal_type']=='mt') ESMO()->update_mo_session($session_id,$rec) ;
        if ($data['args']['terminal_type']=='kz') QUIZ()->update_quiz_session($session_id,array('DTW_id' => $DTW_id)) ;

		$text=ob_get_clean() ;
		LOG_JSON('mo_session')->reg('on_event_examination_result_data_read',$text);
	}

	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."'>" ; // ддя сохранения в журнале
	}


}

?>
