<?php
mb_internal_encoding("UTF-8");
//mb_language( 'Japanese' );

$get_mb_encoding_translation =  ini_get('mbstring.encoding_translation');
$get_mb_internal_encoding =   ini_get('mbstring.internal_encoding');

ini_set('memory_limit', '128M');
ini_set("mbstring.internal_encoding","UTF-8");
ini_set("mbstring.http_input","UTF-8");
ini_set("mbstring.http_output","UTF-8");

/* /////////////////////////////////////////////////////////////////////////////////////////////////
  KONICA MINOLTA User's Guide
  Operation Key Search Rresults PHP
  Modified : 2018-02-10
  ///////////////////////////////////////////////////////////////////////////////////////////////// */

// インデックスファイル
	define('INDEX_FILE', 'search_opkey.js');
// 1ページあたりの結果数
	define('maxItem', 50);
// ヒットキーワードの前何文字表示
	define('snippetStart', 30);
// 説明の表示文字数
	define('snippetLength', 80);
// 検索タイプ
	define('searchType', 'and');//(and|or)
// 検索結果説明の接頭末尾語
	define('trimMark', '<span class="conm">&#8230;</span>');
// ユーザーフォントパターン
	define('UF_Pattern', '@@@((\d@)+)@@');

// sharedフォルダ
	define('SHARED_DIR', 'shared/js/');

// JS __load.jsファイル
	define('JS__load', '__load.js');
// JS ini.jsファイル
	define('JSini', 'ini.js');
// JS textData_**.jsファイルの接頭
	define('JStextData', 'textData');

////////////////////////////////////////////////////////////////////


	$sCountHTML = "";
	$searchCt_HTML = '';
	$resultsHtml = "";
	$naviHTML = "";
	$data = "";
	$keyword_data = "";
	$searchTime = "";
	$Error = array();
	$itemOne = "false";
	$searchTiChk = array("","");
	$andSearch = searchType==='and';
	$TimeStart = microtime(true);
	$_isJSini = false;
	$splitStrBase = '㌀ ㍇ ㍬ ㍭ ㍮ ㍯ ㍰';


//GETデータ
foreach($_GET as $k => $v){
	//$_GET[$k] = @mb_convert_encoding($_GET[$k], "SJIS", "auto");
	//$_GET[$k] = mb_convert_encoding($_GET[$k], "UTF-8", "SJIS");
	if($get_mb_encoding_translation == 1 && $get_mb_internal_encoding){
		$_GET[$k] = mb_convert_encoding($_GET[$k], "UTF-8", $get_mb_internal_encoding);
	}
	$_GET[$k] = mb_convert_encoding($_GET[$k], "UTF-8", "auto");
	//$_GET[$k] = htmlspecialchars($_GET[$k], ENT_COMPAT, "UTF-8");
}
//POSTデータ
//foreach($_POST as $k => $v){
//	$_POST[$k] = mb_convert_encoding($_POST[$k], "SJIS", "auto");
//	$_POST[$k] = mb_convert_encoding($_POST[$k], "UTF-8", "SJIS");
//	$_POST[$k] = htmlspecialchars($_POST[$k], ENT_COMPAT, "UTF-8");
//}




//インデックスファイル読み込み
if($data = @file_get_contents( SHARED_DIR . INDEX_FILE )){
	$pattern = array('/^[^\[]+\[/u', '/;\s*?$/u');
	$replace = array('[', '');
	$data = json_decode(preg_replace($pattern, $replace, $data), true);
}else{
	$Error[] = "Index file Load Error.";
}




//lang読み込み
if($_isJSini = file_exists(SHARED_DIR . JSini)){
	if($jsini = @file_get_contents(SHARED_DIR . JSini)){
		$jsini = json_decode(preg_replace('/(^\s*?var\s+?settings\s*?=\s*?|;\s*?$)/u', '', $jsini), true);
		$langType = $jsini = $jsini['lang'];
	}
}else{
	if($jsini = @file_get_contents( SHARED_DIR . JS__load)){
		preg_match("/var lang\s*=\s*(?:\'|\")(.*?)(?:\'|\")\s*;/", $jsini, $matches);
		$langType = $matches[1];
	}
}




if( $langType=='zh-tw' ){
	$srCountType = 1;
}else if( !$_isJSini && $langType=='zh' ){
	$srCountType = 1;
	$langType="zh-tw";
}else if( !$_isJSini && $langType=='th' ){
	$srCountType = 0;
	$langType="zh-CN";
}else{
	$srCountType = 0;
}




//ページカウント取得
$page = (@$_GET['p'])? ($_GET['p']) : 1 ;




//検索データ作成
$datalist = array();
$datalistTit = array();
for($i=0,$len=count($data); $i<$len; $i++){
	$datalist[] = ufrm($data[$i]['Body'] . " " . $data[$i]['Title']);
	$datalistTit[] = ufrm($data[$i]['Title']);
}




//ユーザーフォント削除
	function ufrm($d){
		return mb_ereg_replace(UF_Pattern, '', $d);
	}




//タイトル文字読み込み
	function titleReq(){//**************************************
		global $langType;
		
		$_lang = ($langType) ? '_'.$langType.'.js' : '.js';
		if($load = @file_get_contents( SHARED_DIR . JStextData . $_lang)){
			preg_match("/(?:\'|\")opkeySearchTitle(?:\'|\")\s*:\s*(?:\'|\")(.*?)(?:\'|\")/", $load, $matches);
			$r = $matches[1];
		}else{
			$r = '';
		}
		
		return $r;
	}




//検索処理
	function find($q){//**************************************
		global $datalist, $datalistTit, $andSearch;
		
		$result = array();
		
		if($andSearch){
		//AND検索
			$querys = $q;
			foreach($querys as &$value){
				$value = '/'.preg_quote($value,'/').'/iu';
			}
			unset($value);
			
			foreach($datalist as $i => $val){
				$res = false;
				$tHit = false;
				$res = 0;
				foreach($querys as $query){
					$tHit = ($tHit) ? $tHit : preg_match($query, $datalistTit[$i]);
					if(preg_match($query, $val)){
						$res++;
					}else{
						break;
					}
				}
				if(count($querys) == $res){
					$result[] = array($tHit, $i);
				}
			}
			
		}else{
		//OR検索
			$querys = $q;
			foreach($querys as &$value){
				$value = preg_quote($value,'/');
			}
			$query = '/'.implode('|',$querys).'/iu';
			
			foreach($datalist as $i => $val){
				$res = false;
				$tHit = false;
				$tHit = ($tHit) ? $tHit : preg_match($query, $datalistTit[$i]);
				if(preg_match($query, $val)){
					$result[] = array($tHit, $i);
				}
			}
			
		}
		
		
		
		usort($result, "cmp");
		foreach($result as &$val){
			$val = $val[1];
		}
		unset($val);
		
		return $result;
	}




//ソート関数
	function cmp($a, $b){
		if($a[0] == $b[0]){
			return ($a[1] < $b[1])? -1 : 1 ;
		}
		if($a[0] < $b[0]){
			return 1;
		}
		return -1;
	}




//ページナビ作成
	function pagenavi($result){//**************************************
		global $naviHTML, $page;
		$len = count($result);
		$ct = ceil($len/maxItem);
		$page = min($ct, $page);
		$naviHTML = "";
		for($i=1; $i<=$ct; $i++){
			$pageClass = ($i == $page*1)? ' class="selected"' : "" ;
			$naviHTML.='<span page="'.$i.'"'.$pageClass.'>'.$i.'</span>';
		}
	}




//説明トリミング
	function snippet($body, $querys){//**************************************
		global $splitStrBase;
		
		$userFont = array();
		$sniPoint = 0;
		$showStrLen = floor(snippetLength * 1.385);
		
		if(mb_ereg(UF_Pattern, $body)){
			if(mb_ereg('['. mb_ereg_replace(" ", "", $splitStrBase) .']', $body, $matches)){
				$splitStr = mb_ereg_replace("\s+", " ", mb_ereg_replace('['. implode("", $matches) .']', '', $splitStrBase));
				$splitStr = explode(' ', $splitStr);
			}else{
				$splitStr = explode(' ', $splitStrBase);
			}
			preg_match_all('/'.UF_Pattern.'/', $body, $match, PREG_PATTERN_ORDER);
			$body = mb_ereg_replace(UF_Pattern, $splitStr[0], $body);
			$userFont = $match[0];
		}
		
		foreach($querys as $query){
			if(($hitPoint = mb_stripos($body, $query)) != false){
				$sniPoint = max($sniPoint, $hitPoint);
				break;
			}
		}
		
		$trimPoint = array(
			max($sniPoint - snippetStart, 0),
			snippetStart + $showStrLen
		);
		$trimStrs = array(
			mb_substr($body, 0, $trimPoint[0]),
			mb_substr($body, $trimPoint[0], $trimPoint[1]),
			mb_substr($body, $trimPoint[1])
		);
		$rb = $trimStrs[1];
		if(count($userFont) > 0){
			$ufNum = array();
			foreach($trimStrs as $trimStr){
				array_push($ufNum, preg_match_all('/'.$splitStr[0].'/', $trimStr, $m));
			}
			$centerUF = array_slice($userFont, $ufNum[0], ($ufNum[0] + $ufNum[1]));
			$splitStrArr = array();
			for($i = 0; $i < count($centerUF); $i++){
				array_push($splitStrArr, "/".$splitStr[0]."/");
			}
			$rb = preg_replace($splitStrArr, $centerUF, $trimStrs[1], 1);
		}
		
		if($trimPoint[0] > 0){
			$rb = trimMark . $rb;
		}
		if(mb_strlen($body) > $trimPoint[1]){
			$rb = $rb . trimMark;
		}
		return $rb;
	}




//キーワードの強調処理
	function boldkeyword($body, $querys){//**************************************
		$result = $body;
		$ststr="";
		$enstr="";
		$quoTrimMark = preg_quote(trimMark,'/');
		
		if(preg_match('/^'.$quoTrimMark.'/iu', $result)){
			$ststr = trimMark;
		}
		if(preg_match('/'.$quoTrimMark.'$/iu', $result)){
			$enstr = trimMark;
		}
		$result = mb_ereg_replace($quoTrimMark, '', $result);
		
		$inUF=false;
		if(mb_ereg(UF_Pattern, $result)){
			$inUF=true;
			$result = explode('@@@', $result);
		}else{
			$result = array( 0=> $result);
		}
		
		foreach($querys as &$v){
			$v = htmlspecialchars($v, ENT_QUOTES);
			$v = preg_quote($v, "/");
		}
		$strreg = "/(" . implode("|", $querys) . ")/iu";
		foreach($result as &$v){
			if(mb_ereg_match("/^(\d|\d(@\d)+)$/", $v) == false){
				$v = preg_replace($strreg, '<span class="hitkey">$1</span>', $v);
			}
		}
		$result = ($inUF) ? implode("@@@", $result) : $result[0] ;
		$result = $ststr . $result . $enstr;
		
		return $result;
	}




//検索結果を表示
	function view($result, $page, $querys){//**************************************
		global $data, $TimeStart, $resultsHtml, $srCountHTML, $itemOne, $srCountType, $searchTime;
		$offset = $page;
		$r = $result;
		$buf = '';
		$itemCount = 0;
		
		$maxPage = ceil(count($r) / maxItem);
		$offset = min($maxPage, $offset);
		
		$itemStart = max($offset-1, 0) * maxItem;
		$itemEnd = $itemStart + maxItem;
		$itemCount = $itemStart;
		$lastLen = count($r)-1;
		
		while($itemCount < $itemEnd){
			if($lastLen < $itemCount || !$r){break;}
			$num = $r[$itemCount];
			$da = $data[$num];
			
			if($da['Title']){
				$h3Text = $da['Title'];
				$h3Text = mb_ereg_replace(UF_Pattern, '#####<span class="kmsymbol"><img src="./img/userfonts/\1.png" alt="" /></span>#####', $h3Text);
				$h3Text = explode('#####', $h3Text);
				foreach($h3Text as &$val){
					if(@preg_match('/^<span class="kmsymbol"><img [^>]+?><\/span>$/iu', $val)){
						$val = preg_replace('/@/u', '', $val);
					}
				}
				$h3Text = implode('', $h3Text);
				unset($val);
			}else{
				$h3Text = '<span class="searchUnknoun">&nbsp;</span>';
			}
			$buf .= '<li><a href="'. $da['File'] .'">'. $h3Text .'</a></li>';
			$itemCount++;
		}
		
		$TimeEnd = microtime(true);
		$searchTime = round($TimeEnd - $TimeStart, 3);
		
		$cost = min($itemStart + 1, count($result));
		$coen = min($itemStart + maxItem, count($result));
		
		$srCountHTML = ''.count($r);
		if($srCountType==1){
			$srCountHTML = '<span id="searchCountTxt">&nbsp;</span><span id="counts">' . count($result) . '</span> <span id="searchCounts1">&nbsp;</span> [ '. $cost .'-'. $coen .' / '. count($result) . '<span id="searchCounts2">&nbsp;</span> ]  (' . $searchTime . ' <span id="searchCounts3">&nbsp;</span>)';
		}else{
			$srCountHTML = '<span id="counts">' . count($result) . '</span> <span id="searchCounts1">&nbsp;</span> [ '. $cost .'-'. $coen .' / '. count($result) . '<span id="searchCounts2">&nbsp;</span> ]  (' . $searchTime . ' <span id="searchCounts3">&nbsp;</span>)';
		}
		
		$resultsHtml = $buf;
		$itemOne = (count($result)==1)? 'true' : 'false';
		
	}






//////////////////////////////
	$_GET['k'] = @trim(preg_replace("/[\s　]+/u", " ", rawurldecode($_GET['k'])));
	if(count($Error)){
		$searchKey = "";
		$querys =  "";
		$resultsHtml = implode("<br />\n",$Error);
	}else if($_GET['k']){
		$searchKey = ' value="'. htmlspecialchars($_GET['k'], ENT_COMPAT, "UTF-8") .'" class="keyIn"';
//		$searchKeyV = preg_replace('/"/u', '&quot;', $_GET['k']);
//		$searchKey = ' value="'. $searchKeyV .'" class="keyIn"';
		$querys = explode(' ',$_GET['k']);
		$re = find($querys);//検索処理
		pagenavi($re);
		view($re, $page, $querys);
	}else{
		$searchKey = "";
		$querys =  "";
		$resultsHtml = '<div id="ErrorNoneKeyword"></div>';
	}
///////////////////////////////





?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="<?php echo $langType; ?>">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title><?php echo titleReq(); ?></title>

<meta http-equiv="Content-Style-Type" content="text/css" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />

<link href="shared/css/__default.css" rel="stylesheet" type="text/css" media="screen,print" />
<link href="shared/css/__print.css" rel="stylesheet" type="text/css" media="print" />
<?php
//ini.js有無判定(有る場合は読み込み処理追加)
if($_isJSini){
	echo '<script src="shared/js/ini.js" type="text/javascript"></script>';
}
?>
<script src="shared/js/__load.js" type="text/javascript"></script>
<script src="shared/js/__default.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
	
	
	
	$('#ugtitle').text(textData.userGuide);
	$('#search label, #opkeySearch label').text(textData.SearchTxt);
	$('#searchSubmit, #op_searchSubmit').val(textData.SearchTxt);
	$('#crombsNavi span.frist a').text(textData.home);
	$('#crombsNavi span:last-child, h1').text(textData.opkeySearchTitle);
	$('#searchCounts1').text(textData.searchCounts1);
	$('#searchCounts2').text(textData.searchCounts2);
	$('#searchCounts3').text(textData.searchCounts3);
	$('#searchCountTxt').text(textData.searchCountTxt);
	
	
	
	/**/
	$('#navi span').live('click', function(){
		var val = $('#op_searchKey').val();
		if((val==textData.opSearchDefTxt)||val==""){
			return false;
		}
		var p = $(this).attr('page');
		window.location =  searchAction($('#opkeySearch form').attr('action')) +"?k="+encodeURIComponent(val)+'&p='+p;
	});
	
	if(<?php echo $itemOne ?>){
		var temp = $('#sCount').html().replace(/items/g, "item");
		$('#sCount').html(temp);
	}
	
});
</script>
</head>
<body class="c2style">
	
<div id="documentBody">
	
<div id="header">
<div id="title">
<div id="ugtitle"><!--userGuide--></div>
<img src="shared/img/model_name.gif" alt="" title=""/>
</div>

<hr class="separator"/>

<div id="search">
<form action="search_result.php">
<label for="searchKey"></label><input type="text" id="searchKey"/><input type="submit" id="searchSubmit" value=""/>
</form>
</div>

<hr class="separator"/>
<!-- /header --></div>

<div id="crombsNavi">
<span class="frist"><a href="../index.html"><!--home--></a></span>
<span><!--opkeySearchTitle--></span>
</div>

<div id="contents">

<div id="c2style">

<div id="leftNavi"></div>

<div id="container" class="container">

<div id='opkeySearch'>
<form action="opkey_search_result.php">
<label for="op_searchKey"><!--SearchTxt--></label><input type="text" id="op_searchKey"<?php echo $searchKey; ?>/><input type="submit" id="op_searchSubmit" value="<!--SearchTxt-->"/><span id="op_searchBtn"></span>
</form>
</div>

<div id="opkeySearchResults">
<h1><!--opkeySearchTitle--></h1>
<div id="sCount"><?php echo $srCountHTML ?></div>
<div id="results"><?php echo $resultsHtml ?></div>
<div id="navi"><?php echo $naviHTML ?></div>
</div>

</div><!-- /container -->

</div><!-- /c2style -->
<hr class="separator"/>
</div><!-- /contents -->

<div id="footer">&nbsp;</div>
<div id='navigation'></div>

</div><!-- /documentBody -->

</body>
</html>
