<?php // $Id: extwiki.inc.php 80 2010-12-10 02:05:47Z mashiki $
// PukiWiki - Yet another WikiWikiWeb clone.
//
// ExtWiki plugin: support ExtWiki mode by mashiki

// Configページの名前 
define('PLUGIN_EXTWIKI_CONFIG', ':ExtConfig');

// pukiwiki自体のJavascriptを有効にするか
// trueだとjavascript付きのプラグインが動く可能性があるが、
// extwiki自体が動かなくなる危険あり。非推奨
define('PLUGIN_EXTWIKI_ENABLE_SCRIPT', false);

// Configページの名前 
define('PLUGIN_EXTWIKI_INTERNAL_ENCODING', strToUpper(mb_internal_encoding()));

if (!function_exists('json_encode')) {
	include_once 'json_encode.php' ;    // for php 4.x
}

function plugin_extwiki_action() {
	global $vars, $defaultpage;

	$page = isset($vars['page']) ? $vars['page'] : '';
	$mode = isset($vars['mode']) ? $vars['mode'] : '';
	$mode = $mode=='' ? 'cmd':$vars['mode'];
	$cmd  = isset($vars['x_cmd']) ? $vars['x_cmd'] : 'read';

	switch ($mode) {
	case 'extwiki':
		extwiki_getBaseHtml($page);
	case 'getConfig':
		extwiki_getConfig();
	case 'getDiff':
		extwiki_getDiff($page);
	case 'getImage':
		extwiki_getImage();
	case 'getPage':
		extwiki_getPage($cmd);
	case 'getPageInfo':
		extwiki_getPageInfo($page);
	case 'getPreview':
		extwiki_getPreview($page);
	case 'getTreeList':
		extwiki_getTreeList($page);
	case 'postForm':
		extwiki_postForm($cmd);
	default:
		extwiki_ajax_res(false, "想定外のモード($mode)が指定されました", 'UnexpectedMode');
	}
}

function plugin_extwiki_convert($page='') {
	global $vars;

	$page = $page?$page:$vars['page'];
	$uri = get_script_uri();
	$pageurl = $uri.'?cmd=extwiki&mode=extwiki&page='
			.str_replace('%23', '#', rawurlencode($page));
	$conf = extwiki_getConfigArray();
	if (
	    $conf['AutoMode']['value']
	 && $_SERVER['REQUEST_METHOD']=='GET'
	 && (!isset($_SERVER['HTTP_REFERER']) // referer isn't set or from external
	 	||strpos($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'])===false)
	 && !preg_match('/[\?&](cmd|plugin)=/', $_SERVER['REQUEST_URI']) // isn't plugin
	 && !preg_match('/DoCoMo|SoftBank|vodafone|UP[.]Browser/i',
	     $_SERVER['HTTP_USER_AGENT']) // isn't mobile phone
	 && !preg_match('/Googlebot|msnbot|robots|crawler|Yahoo! Slurp|Baiduspider/i',
	     $_SERVER['HTTP_USER_AGENT']) // isn't robot or crawler
	) {
		header("Location: $pageurl");
		exit;
	}
	$title = " ExtWikiで「[[[page]]]」を表示";
	if (PLUGIN_EXTWIKI_INTERNAL_ENCODING!='UTF-8') {
		$title = mb_convert_encoding($title, PLUGIN_EXTWIKI_INTERNAL_ENCODING, 'UTF-8');
	}

	$title = str_replace('[[[page]]]', $page, $title);

	return "<a href='$pageurl' title='$title'>".
		"<img src='$uri?cmd=extwiki&mode=getImage' />$page</a>";
_;
}

// wikiドキュメント中のプラグイン指定の変換
function plugin_extwiki_inline($page='') {
	return plugin_extwiki_convert($page);
}

function extwiki_ajax_res($success, $result, $reason='') {
	ob_end_clean();
	header('Content-Type: application/x-javascript; charset=UTF-8');
	mb_internal_encoding('UTF-8');
	die(json_encode(array(
		'success'=>$success,
		($success?'data':'message')=>$result,
		'reason'=>$reason
	)));
}

function extwiki_convert_encoding($item) {
	if (PLUGIN_EXTWIKI_INTERNAL_ENCODING!='UTF-8') {
		$item['text'] = mb_convert_encoding($item['text'],'UTF-8');
		if (isset($item['tooltip'])) {
			$item['tooltip'] = mb_convert_encoding($item['tooltip'],'UTF-8');
		}
	}
	return $item;
}

function extwiki_getBaseHtml($page) {
	global $page_title, $vars, $notimeupdate;
	$conf = extwiki_getConfigArray();
	$extconf = array();
	foreach($conf as $key=>$item) {
		$extconf[$key] = $item['value'];
	}
	$extconf['FirstPage'] = rawurlencode($page?$page:$extconf['DefaultPage']);
	$extconf['NoTimeUpdate'] = $notimeupdate;
	$extconf['PukiwikiVer'] = S_VERSION;
	$conf_json = json_encode($extconf);
	// style組み立て
	$tagsStyle = '';
	$styles = preg_split('/[\t ,]+/', $extconf['CustomStyle']);
	foreach($styles as $style) {
		if ($style=='') continue;
		$tagsStyle .= "<link rel='stylesheet' type='text/css' href='{$extconf['UrlExtWiki']}/$style'/>";
	}
	$sDebug = (isSet($vars['debug'])&&$vars['debug'])?'-debug':'';

	ob_end_clean();
	header('Content-Type: text/html; charset=UTF-8');
	mb_internal_encoding('UTF-8');
	die(str_replace("\t", "", <<< _
		<html><head>
		  <title>{$page_title}</title>
			<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
			<link rel="stylesheet" type="text/css" href="{$extconf['UrlExtJS']}/resources/css/ext-all.css" />
			<link rel="stylesheet" type="text/css" href="skin/pukiwiki.css.php" media="all"/>
			<link rel="stylesheet" type="text/css" href="{$extconf['UrlExtWiki']}/extwiki.css"/>
			<link rel="stylesheet" type="text/css" href="{$extconf['UrlExtJS']}/resources/css/xtheme-{$extconf['Theme']}.css" id='theme'>
			$tagsStyle
			<script type="text/javascript" src="{$extconf['UrlExtJS']}/adapter/ext/ext-base{$sDebug}.js"></script>
			<script type="text/javascript" src="{$extconf['UrlExtJS']}/ext-all{$sDebug}.js"></script>
			<script type="text/javascript">
				var ExtWikiConf = {$conf_json};
			</script>
			<script type="text/javascript" src="{$extconf['UrlExtWiki']}/extwiki{$sDebug}.js"></script>
		</head><body>
			<div id="north">
				<table class="top_tbl"><tr>
					<td id="top_logo"></td>
					<td class="top_center"><span class=top_title id=top_title></span><br/>
						<a id=top_url href=''></a>
					</td>
					<td class="top_info">
						<table class=top_info_tbl>
							<tr><td class="top_info_tbl">update:&nbsp;</td><td id=top_update></td></tr>
							<tr><td class="top_info_tbl">total:&nbsp;</td> <td id=top_count></td></tr>
							<tr><td class="top_info_tbl">today:&nbsp;</td> <td id=top_today></td></tr>
							<tr><td class="top_info_tbl">yesterday:&nbsp;</td><td id=top_yesterday></td></tr>
						</table>
					</td>
				</tr></table>
			</div>
			<div id=hidden_div></div>
		</body></html>
_
	));
}

function extwiki_getConfig($page) {
	$ca= extwiki_getConfigArray();
	$ret = array();
	foreach($ca as $key=>$val) {
		if (isset($val['title'])) {
			$val['name'] = $key;
			$ret[] = $val;
		}
	}
	extwiki_ajax_res(true, $ret);
}

function extwiki_getConfigArray() {
	global $page_title, $defaultpage;
	$conf = array(
		'SightName'=>array(
			'value'=>$page_title,
			'type'=>'string',
			'reg'=>'.+',
			'customizable'=>false
		),
		'TabPosition'=>array(
			'value'=>'bottom',
			'type'=>'string',
			'reg'=>'bottom|top',
			'customizable'=>true
		),
		'MenuPosition'=>array(
			'value'=>'left',
			'type'=>'string',
			'reg'=>'left|right|top|bottom',
			'customizable'=>true
		),
		'Theme'=>array(
			'value'=>'blue',
			'type'=>'string',
			'reg'=>'blue|gray|access',
			'customizable'=>true
		),
		'MaxTabs'=>array(
			'value'=>16,
			'type'=>'int',
			'min'=>5,
			'max'=>64,
			'customizable'=>true
		),
		'Timeout'=>array(
			'value'=>60,
			'type'=>'int',
			'min'=>5,
			'max'=>180,
			'customizable'=>true
		),
		'AutoMode'=>array(
			'value'=>'false',
			'type'=>'bool',
			'customizable'=>false
		),
		'UrlExtWiki'=>array(
			'value'=>'extwiki',
			'type'=>'string',
			'reg'=>'[-_.:\/a-zA-Z0-9]+',
			'customizable'=>false
		),
		'UrlExtJS'=>array(
			'value'=>'extwiki/ext3',
			'type'=>'string',
			'reg'=>'[-_.:\/a-zA-Z0-9]+',
			'customizable'=>false
		),
		'CustomStyle'=>array(
			'value'=>'',
			'type'=>'string',
			'reg'=>'([-_a-zA-Z0-9]+[.]css[, ]*){1,9}',
			'customizable'=>false
		),
	);
	$page = PLUGIN_EXTWIKI_CONFIG;
	if (is_page($page) && check_readable($page, false, false)) {
		$fConv = (PLUGIN_EXTWIKI_INTERNAL_ENCODING!='UTF-8');
		// 本文取得
		$source = get_source($page, TRUE);
		foreach ($source as $line) {
			if (preg_match('/^\|([^|]+)\|([^|]*)\|([^|]*)\|([^|]*)\|([^|]*)\|/', $line, $mch)) {
				$key = trim($mch[1]);
				$val = trim($mch[2]);
				$title = trim($mch[4]);
				$comment = trim($mch[5]);
				if (isset($conf[$key])) {
					if ($conf[$key]['type']=='string' && preg_match("/^{$conf[$key]['reg']}$/", $val)) {
						$conf[$key]['value'] = $fConv?mb_convert_encoding($val,'UTF-8'):$val;
					} elseif ($conf[$key]['type']=='int' && $conf[$key]['min']<=$val && $val<=$conf[$key]['max']) {
						$conf[$key]['value'] = (int) $val;
					} elseif ($conf[$key]['type']=='bool' && preg_match('/^(0|1|true|false)$/i', $val)) {
						$conf[$key]['value'] = (bool) preg_match('/^(1|true)$/i',$val);
					} else {
						$conf[$key]['invalid'] = true;
					}
					$conf[$key]['title'] = ($fConv?mb_convert_encoding($title,'UTF-8'):$title);
					$conf[$key]['comment'] = ($fConv?mb_convert_encoding($comment,'UTF-8'):$comment);
				}
			}
		}
	}
	$conf['UrlWiki']['value'] = get_script_uri();
	$conf['DefaultPage']['value'] = $defaultpage;
	$conf['ConfigPage']['value'] = $page;
	return $conf;
}

function extwiki_getDiff($page) {
	global $vars;

	$msg = preg_replace('/^(?:#freeze(?!\w)\s*)+/im', '', $vars['msg']); // PLUGIN_EDIT_FREEZE_REGEX
	$original = preg_replace('/^(?:#freeze(?!\w)\s*)+/im', '', $vars['original']); // PLUGIN_EDIT_FREEZE_REGEX
	$body = diff_style_to_css(do_diff($original, $msg));
	$body = "<pre style='margin:0;padding:2'>$body</pre>";
	$title = 'diff: '. $page;
	// UTF-8 を強制する
	if (PLUGIN_EXTWIKI_INTERNAL_ENCODING!='UTF-8') {
		$body = mb_convert_encoding($body, 'UTF-8');
		$title = mb_convert_encoding($title, 'UTF-8');
	}
	// 結果送信 
	extwiki_ajax_res(true, array(
		'success'=>true,
		'page'=>rawurlencode($page),
		'title'=>$title,
		'body'=>$body,
	));
}

function extwiki_getImage() {
	header('Content-Type: image/png');
	ob_end_clean();
	die(base64_decode(
		'iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAMAAAC6V+0/AAAAAXNSR0IArs4c6QAAAFdQTF'.
		'RFAAAAADNmADOZ//8AM2ZmZplmM2aZzMwzZpnMzMzM//8zAGaZMwCZMzNmZpkzmZkzzMwA'.
		'ZpkAmcwzzMz/ZpmZMzOZmZmZmZkAzMyZzMxmM2YzAACZAABmLGN4bQAAAAF0Uk5TAEDm2G'.
		'YAAAABYktHRACIBR1IAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH2AcTFisVwTPW'.
		'wwAAAOBJREFUGNNVkeuWgyAMhEkmIQiItt377vs/5w4e254O+sOBJB9jSoeWkkVyWdJTi5'.
		'xa5Xb3iiFiN6Wrl3J6f7t31eZqPiCHu6hiu1yb4g1aP0VnY1GvzUw0wO3ZgwdXraaUo3av'.
		'NNclFZFZ7Y6OHPtkKIl8RmUTaZJ9mjlNDj7Hq3pgCc08B3yrYYTvKorMckPfMDqacaTMlc'.
		'pqVTHcgzwwtLhmsnvUHATfNsfsJKQXR/SAd0glv0F5o9vgdq3v/MIvq8cR1BcRnfOMkbj9'.
		'fJwxqTwC1fIMeb2H/JL9y+/4B/+iB1jYNf++AAAAAElFTkSuQmCC'
	));
}

function extwiki_getPage($cmd) {
	global $vars, $defaultpage, $attach_link, $notes, $hr, $note_hr, $foot_explain;
	exist_plugin('counter');

	if ($cmd=='newpage') {
		$cmd = 'read';
		$new = true;
	}
	if (!exist_plugin_action($cmd)) {
		extwiki_ajax_res(false, "プラグイン「{$cmd}」は使用できません", 'PluginNotFound');
	}
	$page = (isSet($vars['page'])&&$vars['page']!=='')
		?$vars['page']
		:(isset($vars['refer']) ? $vars['refer'] : '');

	$default = false;
	if ($cmd=='read') {
		if ($page=='') {
			$default = true;
			$page = $defaultpage;
		}
		$vars['page'] = $page;
	} elseif ($cmd=='rename') {
		if ($vars['page']!='' && $vars['refer']=='') {
			$vars['refer'] = $vars['page'];
		}
	}
	if (isset($vars['x_mode'])) {
		$vars['mode'] = $vars['x_mode'];
	}
	if ($page=='' || isset($new) || isSet($vars['write']) || $cmd=='rename' || $cmd=='template' || $cmd=='pcomment') {
		$counter = array('total'=>'-','today'=>'-','yesterday'=>'-','now'=>'-');
		$update  = '-';
	} elseif (!check_readable($page, false, false)) {
		extwiki_ajax_res(false, "ページ「{$page}」を読む権限がありません", 'PageNotAuthorized');
	} elseif (is_page($page) ) {
		// カウンタ取得
		$counter = plugin_counter_get_count($page);
		$update = get_date('Y/m/d H:i', get_filetime($page));
	} else {
		extwiki_ajax_res(false, "ページ「{$page}」が見つかりません", 'PageNotFound');
	}

	// プラグイン実行本文取得
	$pagedata = do_plugin_action($cmd);
	$body = $pagedata['body'];

	if ($cmd=='read' && $body=='') { // 無効なページ名のときは$bodyが入ってる
		$body = convert_html(get_source($page, TRUE));

		// 注釈の追加
		ksort($foot_explain, SORT_NUMERIC);
		$notes = ! empty($foot_explain) ? $note_hr . join("\n", $foot_explain) : '';
		if ($notes != '') {
			$body .= "<div id='note'>$notes</div>";
		}

		// 添付ファイルの追加
		$attaches = ($attach_link  && exist_plugin_action('attach')) ?
			attach_filelist() : '';
		if ($attaches != '') {
			$body .= "<div id='attach'>$hr$attaches</div>";
		}
		$title = $page;
		$msg = $pagedata['msg'];
	} else {  // プラグイン結果
		$title = isset($pagedata['msg'])?'>>'.str_replace('$1',$page,$pagedata['msg']):"($cmd)";
	}

	// UTF-8 を強制する
	if (PLUGIN_EXTWIKI_INTERNAL_ENCODING!='UTF-8') {
		$title = mb_convert_encoding($title,'UTF-8');
		$body = mb_convert_encoding($body, 'UTF-8');
	}

	// ENABLE_SCRIPTがtrueでなければJavascriptカット
	if (!PLUGIN_EXTWIKI_ENABLE_SCRIPT) {
		$body = preg_replace(
			'/(<[^>]*)( on[a-z]+=)([^>]*>)/ie',
			'preg_replace("/ on[a-z]+=/i"," XX=", "${0}")',
			$body
		);
	}

	// 結果準備 
	$res = array(
		'success'=>true,
		'page'=>rawurlencode($page),
		'title'=>$title,
		'update'=>$update, 
		'cntTotal'=>$counter['total'],
		'cntToday'=>$counter['today'],
		'cntYesterday'=>$counter['yesterday'],
		'writable'=>check_editable($page, false, false),
		'fDefault'=>$default,
		'body'=>$body,
	);
	extwiki_ajax_res(true, $res);
} //extwiki_getPage

function extwiki_getPageInfo($page) {
	global $vars;
	exist_plugin('counter');
	$fBody = isSet($vars['body'])?$vars['body']:false;
	$res = array();
	$body = $digest = '';
	
	if (!check_readable($page, false, false)) {
		extwiki_ajax_res(false, "ページ「{$page}」を読む権限がありません", 'PageNotAuthorized');
	} elseif (is_page($page) ) {
		// カウンタ取得
		$counter = plugin_counter_get_count($page);
		$res['cntTotal'] = $counter['total'];
		$res['cntToday'] = $counter['today'];
		$res['cntYesterday'] = $counter['yesterday'];
		$res['update']   = get_date('Y/m/d H:i', get_filetime($page));
		$res['writable'] = check_editable($page, false, false);
		$res['found'] = true;
		if ($fBody) {
			$body = get_source($page, TRUE, TRUE);
			$res['digest'] = md5($body);
		}
	} else {
		$res['found'] = false;
		if ($fBody) {
			require_once('extwiki.inc.ondemand.php');
			$body = extwiki_getTemplate($page);
			$res['digest'] = md5('');
		}
	}
	
	$title = $page;

	// UTF-8 を強制する
	if (PLUGIN_EXTWIKI_INTERNAL_ENCODING!='UTF-8') {
		$title = mb_convert_encoding($title,'UTF-8');
		$body = mb_convert_encoding($body, 'UTF-8');
	}

	$res['page'] = rawurlencode($page);
	$res['title']= $title;

	if ($fBody) {
		$res['body'] = $body;
	}
	// 結果送信 
	extwiki_ajax_res(true, $res);
} // getPageInfo

function extwiki_getPreview($page) {
	global $vars;

	$msg = preg_replace('/^(?:#freeze(?!\w)\s*)+/im', '', $vars['msg']); // PLUGIN_EDIT_FREEZE_REGEX
	$msg = make_str_rules($msg===''?'Nothing':$msg);
	$body = drop_submit(convert_html($msg));
	$title = 'preview: '. $page;
	// UTF-8 を強制する
	if (PLUGIN_EXTWIKI_INTERNAL_ENCODING!='UTF-8') {
		$body = mb_convert_encoding($body, 'UTF-8');
		$title = mb_convert_encoding($title, 'UTF-8');
	}
	// 結果送信 
	extwiki_ajax_res(true, array(
		'success'=>true,
		'page'=>rawurlencode($page),
		'title'=>$title,
		'body'=>$body,
	));
}

function extwiki_getRecent($nLine) {
	global $date_format, $show_passage;

	$fnRecent = CACHE_DIR . PKWK_MAXSHOW_CACHE;
	$lines = false;
	if (file_exists($fnRecent)) {
		$lines = file_head($fnRecent, $nLine);
	}
	if (!$lines) {
		return array(array(
			'text'=>'Can not get recent change',
			'params'=>array('acttype'=>'menu')
		));
	}

	$days = array();
	$prevDate = '';
	foreach ($lines as $line) {
		list($time, $page) = explode("\t", rtrim($line));

		$date = get_date($date_format, $time);
		if ($prevDate != $date) {
			// New day
			$prevDate = $date;
			$days[] = array(
				'text'=>$date,
				'params'=>array('acttype'=>'menu'),
				'menu'=>array('items'=>array())
			);
		}

		$days[count($days)-1]['menu']['items'][] = extwiki_convert_encoding(array(
			'text'=>$page,
			'params'=>array('acttype'=>'plugin','page'=>rawurlencode($page)),
			'tooltip'=>$show_passage?get_passage($time):''
		));
	}
	for ($i=0; $i<count($days); ++$i) {
		$days[$i]['tooltip'] = count($days[$i]['menu']['items']).'件';
		$days[$i] = extwiki_convert_encoding($days[$i]);
	}
	return $days;
}

function extwiki_getPageTree($page) {
	// 末尾の'/'を外す
	$page = preg_replace('#/$#', '', $page);

	if ($page=='') {
		// 空白はすべて
		$res = get_existpages();
	} else {
		// GREP実行
		$res = preg_grep('#^' .  preg_quote($page , '#') . '/#', get_existpages());
	}

	if (count($res)==0) {
		return array(array(
			'text'=>'Not found',
			'params'=>array('acttype'=>'menu')
		));
	}
	// 並べ替え
	natcasesort($res);
	
	$prev = $page;
	$pages = array();
	$items = & $pages;
	$branches = array(array('page'=>$prev, 'len'=>strlen($prev), 'items'=>& $items));
	$br = & $branches[0];
	$adj = $page==''?0:1;

	foreach ($res as $p) {
		// 前のページは新しい枝になるか
		if ($prev==$page) {
		} elseif (substr($p,0,strlen($prev)+1)==$prev.'/') {
			// 前のページを新しい枝にする
			$br['items'][count($br['items'])-1]['menu'] = array('items'=>array());
			$items = & $br['items'][count($br['items'])-1]['menu']['items'];
			$branches[] = array('page'=>$prev, 'len'=>strlen($prev), 'items'=> & $items);
			$br = & $branches[count($branches)-1];
		} else {
			//どの枝の配下か
			for ($br = & $branches[count($branches)-1];
				 substr($p,0,strlen($br['page']))!=$br['page'];
				 $br = & $branches[count($branches)-1]) {
				array_pop($branches);
			}
		}

		$text = substr($p, $br['len']+$adj);
		$br['items'][] = extwiki_convert_encoding(array(
			'text'=>$text,
			'params'=>array('acttype'=>'plugin','page'=>rawurlencode($p))
		));
		$prev = $p;
	}
	return $pages;
}

function extwiki_getTreeList($page) {
	global $InterWikiName;
	if (!is_page($page) || !check_readable($page, false, false)) {
		extwiki_ajax_res(false, "ページ「{$page}」が見つからないか、権限がありません", 'PageNotFound');
	} else {
		// 本文取得
		$source = get_source($page, TRUE);
		$result = array();
		$fHR =false;
		$fRight =false;
		foreach ($source as $line) {
			if ($line[0]!='-' && $line[0]!='*') continue;
			if (substr($line,0,4)=='----') {
				$fHR = true;
			} elseif (substr($line,0,2)=='->') {
				$fRight = true;
			} else {
				// レベルを求める
				$target = &$result;
				for ($level=0; $line[$level]=='-' && $level<4; ++$level) {
					if (isset($target[count($target)-1])) {
						if (!isset($target[count($target)-1]['menu'])) {
							$target[count($target)-1]['menu'] = array('items'=>array());
						}
						$target = &$target[count($target)-1]['menu']['items'];
					}
				}
				if ($fHR) {
					$target[] = '-';
					$fHR = false;
				}
				$line = rtrim($line);
				if ($line[0]=='*') {
					if ($fRight) {
						$target[] = '->';
						$fRight = false;
					}
					$line = preg_replace('/\s*\[[^\[\]]+\]$/', '', $line);
				}
				$item = array();
				$text = preg_replace('/^[-*\s]+/', '', $line);
				// 書込可/不可による制御取得
				if (preg_match('/^([?!])edit(.*)$/', $text, $wk)) {
					$item['ctledit'] = $wk[1]=='?'?'enable':'disable';
					$text = $wk[2];
				}
				// アイコン取得
				if (preg_match('/^\(([a-z0-9]+)\)(.*)$/', $text, $wk)) {
					$item['iconCls'] = $wk[1];
					$text = $wk[2];
				}
				// 説明取得
				if (preg_match('/(.+):([^]]+)$/', $text, $wk)) {
					$text = trim($wk[1]);
					$item['tooltip'] = trim($wk[2]);
				}
				if (!preg_match('/^\s*\[\[(.+)\]\]\s*$/', $text, $wk)) {
					$type = 'menu';
				} else {
					$params = array();
					if (preg_match('/([^>]+)(>?)>([^>]+)$/', ($text = trim($wk[1])), $wk)) {
						$text = trim($wk[1]);
						$action = trim($wk[3]);
						if ($wk[2]=='>') {
							$params['_external'] = true;
						}
					} else {
						$action = $text;
					}
					if (!preg_match('/^(&+)(.+)$/', $action, $wk)) {
						if (is_url($action, TRUE)) {
							$params['url'] = $action;
							$type = 'link';
						} elseif(preg_match("/^$InterWikiName$/", $action, $mch)) {
							$params['url'] = get_interwiki_url($mch[2], $mch[3]);
							$type = 'link';
						} else {
							$params['page'] = $action;
							$type = 'plugin';
						}
					} else {
						$type = (strlen($wk[1])>1)?'xjf':'plugin';
						if (preg_match('/(.+)\((.*)\)$/', ($action=trim($wk[2])), $wk)) {
							$action = $wk[1];
							//パラメータセット
							foreach (explode(',', $wk[2]) as $p) {
								if (preg_match('/^([^=]+)=(.+)$/', $p, $wk)) {
									$params[trim($wk[1])] = trim($wk[2]);
								} else {
									$params['page'] = trim($p);
								}
							}
						}
						// recent システムコマンドの特殊処理
						if ($type=='xjf' && $action=='recent') {
							$type = 'menu';
							$cnt = isSet($params['page']) && 0+$params['page']>0
								?0+$params['page']
								:10
							;
							$item['menu'] = array('items'=>extwiki_getRecent($cnt));
						} else if ($type=='xjf' && $action=='pagetree') {
							$type = 'menu';
							$item['menu'] = array('items'=>extwiki_getPageTree($params['page']));
						} else if ($type=='plugin') {
							$params['cmd'] = $action;
						} else {
							$params[$type] = $action;
						}
					}
					if (isSet($params['page'])) {
						if (preg_match('/^([^#]+)#([^#]+)/',$params['page'], $wk)) {
							$params['page'] = $wk[1];
							$params['_anchor'] = '#'.rawurlencode($wk[2]);
						}
						$params['page'] = rawurlencode($params['page']);
					}
					$item['params'] = $params;
				}
				// タイプと名前セット
				$item['params']['acttype'] = $type;
				$item['text'] = $text;

				$target[] =extwiki_convert_encoding($item);
			
			}
		}

		// 結果準備
		extwiki_ajax_res(true, $result);
	}
}

function extwiki_postForm($cmd) {
	extwiki_getPage($cmd);
}
?>
