<?php

class Cmd_word
{
	/**
	 * インスタンスを取得する。
	 */
	static function getinstance()
	{
		return new Cmd_word;
	}
	
	
	function run()
	{
		$get = KinoWiki::getinstance()->getGET();
		if((!isset($get['page']) || $get['page'] == '') || (!isset($get['word']) || $get['word'] == '')){
			throw new CmdException('パラメータが足りません。', 'word');
		}
		$page = Page::getinstance($get['page']);
		
		$_word = trim($get['word']);
		$word = mb_split('[\s　]+', $_word);
		
		$header[] = '<p>';
		$header[] = '次の単語がハイライトされています：' . join(' ', $word);
		$header[] = '</p>';
		$header[] = '<hr />';
		
		$type = isset($get['type']) ? $get['type'] : 'normal';
		$ret['title'] = $this->markword(htmlspecialchars($page->getpagename()), $word, $type);
		$ret['body'] = $this->markword(join("\n", $header) . convert_block($page->getsource(), $page->getpagename()), $word, $type);
		$ret['pagename'] = $page->getpagename();
		$ret['lastmodified'] = $page->gettimestamp();
		$ret['lastmodified_old'] = getold($page->gettimestamp());
		$ret['footnote'] = $this->markword(Footnote::getinstance()->getnote(), $word, $type);
		return $ret;
	}
	
	
	/**
	 * 検索語にタグをつける。
	 * 
	 * @param	string	$text	タグをつける対象
	 * @param	array(string)	$word	検索語
	 * @param	string	$type	検索の種類
	 */
	protected function markword($text, $word, $type)
	{
		switch($type){
			case 'fuzzy':
				$call = '_markword_fuzzy';
				break;
			case 'ereg':
				$call = '_markword_ereg';
				break;
			default:
				$call = '_markword_normal';
				break;
		}
		
		$count = 1;
		foreach($word as $w){
			if($w == ''){
				continue;
			}
			$s = $this->$call($w);
			$pattern = "((?:\G|>)[^<]*?)($s)";
			$replace = "\\1<span class=\"search word$count\">\\2</span>";
			$text = mb_ereg_replace($pattern, $replace, $text, 'm');
			$count++;
		}
		return $text;
	}
	
	
	protected function _markword_normal($w)
	{
		return mb_ereg_quote($w);
	}
	
	
	protected function _markword_fuzzy($w)
	{
		require_once(SYSTEM_DIR . 'kanatable.inc.php');
		
		$s = '';
		$len = mb_strlen($w);
		for($i = 0; $i < $len; $i++){
			$c = mb_strtolower(mb_convert_kana(mb_substr($w, $i, 1), 'KVCas'));
			$c = htmlspecialchars(isset($kanatable[$c]) ? $kanatable[$c] : $c);
			$s .= '[' . mb_ereg_quote($c) . '][ッー・゛゜、。]?';
		}
		return $s;
	}
	
	
	protected function _markword_ereg($w)
	{
		return $w;
	}
	
}

?>