<?php

// union_table.inc.php, 0.4 2006/12/08	taru        plugin

function plugin_union_table_convert()
{
	global $script, $vars;

	static $number = array();
	if (! isset($number[$page])) $number[$page] = 1;
	$count = $number[$page]++;

	$opt = array(
		'page_link' => '',
		'sort' => 0,
	);

	//$opt['xxx']
	$args = func_get_args();

	foreach ($args as $opt_key) {
		list($key, $val) = explode('=', $opt_key);
		$opt[$key] = htmlspecialchars($val);
	}
	$opt['count'] = $count;

	$page = isset($opt['page']) ? $opt['page'] : $vars['page'] . '/';
	$opt['page'] = $opt['refer'] = $page;

	$table_source = sort_table($page,$opt);

	make_page(& $table_source,null,$opt);

	return $table_source;
}	
function plugin_union_table_action()
{
	global $vars, $post, $script;
	$vars['count'] = 1;

	$page = $vars['refer'];

	if ( isset( $vars['set_filter_form'] ) ) {
		foreach ( $vars as $key => $data ) {
			if ( preg_match('/^text_([a-z]+)_([0-9]+)/', $key,$match_key) ) {
				if (! isset( $vars["filter_{$match_key[2]}"] ) || $vars["filter_{$match_key[2]}"] == '' )
					$vars["filter_{$match_key[2]}"] = $data;
			}
		}
	}

	$table_source = sort_table($page,$vars);

	$page = preg_replace("/\/$/", "", $page);

	make_page(& $table_source, $page, $vars);

	$title = $page;

	return array('msg'=>$title, 'body'=>$table_source);

}
function make_page($table_source, $page, $opt)
{
	$count = 0;$cells_count = 0;
	foreach ( $table_source as $key => $cells ){
		if ( $count === 0 ) $cells_count = count($cells) - 1;
		for ( $i = 0; $i < $cells_count; $i++ ) {
			if ( preg_match('|^\[\[(.+)\]\]|',$cells[$i],$match_cell) && $i < 2 ){
				$select_data[$i][] = preg_match('|(.+)(?=>)|',$match_cell[1],$m_cell) ? $m_cell[1] : $match_cell[1];
			} else {
				$select_data[$i][] = ($cells[$cells_count] == 'h') ? '' : $cells[$i];
			}
		}
		$table_source[$key] = '|' . join('|', $cells);
		$count++;
	}
	$count--;
	array_push($table_source, "&br;\n","|~count|$count|\n");

	$table_source = convert_html($table_source);

	if ( isset($opt['set_filter_form'])) {
		$form = "";
		for ( $i = 0; $i < $cells_count; $i++ ) {
			$select_data[$i] = array_unique($select_data[$i]);
			natcasesort($select_data[$i]);
			$select_list = "";
			foreach($select_data[$i] as $s_data) {
				if (! preg_match('/\\|\"|<.*>/',$s_data)){
					if ($opt["filter_$i"] == $s_data){
						$select_list .= "    <option value=\"$s_data\" selected>$s_data</option>\n";
					} else {
						$select_list .= '    <option value="' . $s_data . '" >' . $s_data . "</option>\n";
					}
				}
			}
			$input_text = isset($opt['form_text_off']) ? '' : "<input type=text name=\"text_filter_$i\" value=\"{$opt["filter_$i"]}\" /><br />";
			$form .= <<<EOD
   <td class="style_td">
    $input_text
    <select name="filter_$i">
$select_list
    </select>
   </td>
EOD;
		}
		$form = "  <tr>\n" . $form . "  </tr>\n";
		$table_tag = '<table class="style_table" cellspacing="1" border="0"><thead>';
		$table_source = preg_replace('/<table class="style_table".+<thead>/', $table_tag . $form, $table_source);
		$table_source = filter_form($opt) . $table_source . "</form>\n";
	}
	if ( isset($page) ) $table_source = convert_html("**[[$page]] union_table\n") . $table_source;
}
function filter_form( $opt )
{
	global $script;

//	if (isset($opt['set_filter_form'])){
//		if($opt['set_filter_form'] == 'head'){
	if (isset($opt['form_text_off'])) $form_text_off = "<input type=\"hidden\" name=\"form_text_off\"   value=\"{$opt['form_text_off']}\" />";
	$body = <<<EOD
<form action="$script" method="post">
 <center>
   <input type="hidden" name="plugin"          value="union_table" />
   <input type="hidden" name="refer"           value="{$opt['refer']}" />
   <input type="hidden" name="sort_ad"         value="{$opt['sort_ad']}" />
   <input type="hidden" name="sort_type"       value="{$opt['sort_type']}" />
   <input type="hidden" name="sort"            value="{$opt['sort']}" />
   <input type="hidden" name="sort_sec"        value="{$opt['sort_sec']}" />
   <input type="hidden" name="page_link"       value="{$opt['page_link']}" />
   <input type="hidden" name="section"         value="{$opt['section']}" />
   <input type="hidden" name="set_filter_form" value="{$opt['set_filter_form']}" />
   $form_text_off
   <input type="submit" name="filter"          value="set" />
 </center>
EOD;
	return $body;
//		} else if ($opt['set_filter_form'] == 'foot') {
//			return "</form>\n";
//		}
//	}
}
function sort_type($type)
{
	if ($type == 's'){
		$sort_type =  SORT_STRING;
	} else if ($type == 'n'){
		$sort_type =  SORT_NUMERIC;
	} else {
		$sort_type =  SORT_REGULAR;
	}
	return $sort_type;
}
function sort_table($page,$opt)
{
	if( preg_match('/-/',$opt['sort_ad'])){
		$sort_ad = explode("-", $opt['sort_ad']);
		foreach ($sort_ad as $key => $ad){
			$sort_ad[$key] = ($ad == 'a') ? SORT_ASC : SORT_DESC;
			$sort_ad_s[$key] = $ad;
		}
	} else {
		$sort_ad[$opt['sort']] = ($opt['sort_ad'] == 'd') ? SORT_DESC : SORT_ASC;
		$sort_ad_s[$opt['sort']] = $opt['sort_ad'];
	}
	if( preg_match('/-/',$opt['sort_type'])){
		$sort_type = explode("-", $opt['sort_type']);
		foreach ($sort_type as $key => $type){
			$sort_type[$key] = sort_type($type);
			$sort_type_s[$key] = $type;
		}
	} else {
		$sort_type[$opt['sort']] = sort_type($opt['sort_type']);
		$sort_type_s[$opt['sort']] = $opt['sort_type'];
	}

//	$page_list = auth::get_existpages();	//PukiWiki Plus! i18n
	$page_list = get_existpages();	//PukiWiki

	$table_source = array();
	foreach ( $page_list as $p_l_line ){
		if ( preg_match(']^' . $page . ']', $p_l_line) ){
			$table_source = array_merge( $table_source, get_table($page,$p_l_line,$opt,$sort_ad_s,$sort_type_s));
		}
	}
	$sort = sort_key(& $table_source, $opt['sort']);
	if ( isset($opt['sort_sec']) && $opt['sort_sec'] != '' ) {
		$sort_sec = sort_key($table_source,$opt['sort_sec']);
		array_multisort($sort, $sort_ad[$opt['sort']], $sort_type[$opt['sort']],
					$sort_sec, $sort_ad[$opt['sort_sec']], $sort_type[$opt['sort_sec']], $table_source);
	} else {
		array_multisort($sort, $sort_ad[$opt['sort']], $sort_type[$opt['sort']], $table_source);
	}

	return $table_source;
}
function sort_key($table_source,$sort_key)
{
	foreach ( $table_source as $key => $cells ){
		foreach ( $cells as $key_c => $cell ){
			if ($cell == '~')
				$table_source[$key][$key_c] = $table_source[$key - 1][$key_c];
//					 = "BGCOLOR(#dedeff):" . $table_source[$key - 1][$key_c];
		}
		$sort[$key] = $table_source[$key][$sort_key];
	}
	return $sort;
}
function get_table($page,$page_l,$opt,$sort_ad,$sort_type)
{
	global $script, $vars;
	static $t_count = array();
	$count = $opt['count'];
	if (! isset($t_count[$count])) $t_count[$count] = 0;
	$h_count = 0;
	$section = array();

	$p_source = get_source($page_l);

	$table = array();
	$cells  = array();	//Ver0.2

	foreach ($p_source as $source_line) {
		if (  isset($opt['section']) ){
			$opt['section'] = 'section';
		}
		if ( preg_match('/^(\*{1,3})(.*)\[(#[A-Za-z][\w-]+)\](.*)$/', $source_line, $s_line) ){
			$section = array($s_line[2], $s_line[3]);
		}
		if (preg_match('/^\|(.+)\|([hHfFcC]?)$/', $source_line, $matches)){
			$cells = explode("|", $matches[1]);
			if ($t_count[$count] === 0 && strtolower($matches[2]) == 'h' && $h_count === 0){
				if (isset($opt['section'])) array_unshift($cells, "section");
				if ($opt['page_link'] != 'off') array_unshift($cells, "page");
				foreach ($cells as $key => $cell) {
					if (! isset($sort_ad[$key]) ) {
						$sort_ad[$key] = 'a';
					} else if ($opt['sort'] == $key) {
						$sort_ad[$key] = ($sort_ad[$key] == 'a') ? 'd' : 'a';
					}
					if (! isset($sort_type[$key]) ) {
						$sort_type[$key] = 'r';
					}
					$mark[$key] = strtoupper($sort_ad[$key]);
				}
				$sort_ad_j = join('-', $sort_ad);
				$sort_type_j = join('-', $sort_type);
				foreach ($cells as $key => $cell) {
					if ( $opt['sort'] == $key ) $mark[$key] = "<" . $mark[$key] . ">";
					if (! isset($sort_type[$key]) ) $sort_type[$key] = 'r';
					$cells[$key] = "&union_table(cell=$cell,mark=" . $mark[$key] . ",refer=$page,sort_ad="
						 . $sort_ad_j . ",sort_type=" . $sort_type_j . ",sort=$key,page_link="
						 . $opt['page_link'] . ",section=" . $opt['section'] . ",sort_sec=" . $opt['sort'] . ","
						 . join(',', table_filter( '', $opt, $page_l, 1, 0))
						 . ");";
				}
				$cells[] = 'h';
				$table[] = $cells;
				$h_count++;
			}
			if ($matches[2] == ''){
				if ( isset($opt['section']) )
					 array_unshift($cells, "[[" . $section[0] . ">" . $page_l . $section[1] . "]]");
				if ( $opt['page_link'] == 'short' ) {
					$ln_page = array_pop( explode("/", $page_l) );
					array_unshift($cells, "[[$ln_page>$page_l]]");
				} else if( $opt['page_link'] != 'off'){
					array_unshift($cells, "[[$page_l]]");
				}
				$filter = table_filter( $cells, $opt, $page_l, $section[0], 1);
				if ( $filter ) {
					$cells[] = '';
					$table[] = $cells;
				}
			}
		}
	}
	$t_count[$count]++;

	return $table;
}
function table_filter( $cells, $opt, $page, $section, $change)
{
	$filter = $change ? 1 : array();
	$page_section = array( 'page' => $page, 'section' => $section);
	$cells = array_merge($cells, $page_section);	//array_merge_recursive()
	foreach ( $opt as $key => $chk ){
		if ( preg_match('/^([a-z]+)_(.+)/', $key,$match_key) && ( $match_key[1] == 'except' || $match_key[1] == 'filter' ) && $chk != "" ) {
			if ( $change ) {
				if ( preg_match('|^\[\[(.+)\]\]|',$cells[$match_key[2]],$match_cell) && $i < 2 ){
					$chk_cell = preg_match('|(.+)(?=>)|',$match_cell[1],$m_cell) ? $m_cell[1] : $match_cell[1];
				} else {
					$chk_cell = $cells[$match_key[2]];
				}
				$filter = ($match_key[1] == 'filter') ? 0 : 1;
				if( preg_match('/' . $chk . '/', $chk_cell ) ) {
					if ( $match_key[1] == 'except' ) {
						$filter = 0;
						break;
					} else if ( $match_key[1] == 'filter' ) {
						$filter = 1;
						if (isset($end_filter)) $filter = 0;
					}
				} else if ( $match_key[1] == 'filter' ) {
					$end_filter = 1;
				}
			} else {
				$filter[] = $section ? $key . "=" . encode($chk) : $key . "=" . rawurlencode(decode($chk));
			}
		}
	}
	if (! $change && isset($opt['set_filter_form'])) $filter[] = "set_filter_form={$opt['set_filter_form']}";
	if (! $change && isset($opt['form_text_off'])) $filter[] = "form_text_off={$opt['form_text_off']}";
	return $filter;
}
function plugin_union_table_inline()
{
//	is_freeze(): fopen() failed: http://~

	global $script, $vars;
	$args = func_get_args();
	foreach ($args as $opt_key) {
		list($key, $val) = explode('=', $opt_key);
		$opt[$key] = htmlspecialchars($val);
	}
	$page = rawurlencode($opt['refer']);
//	$page = $opt['refer'];		//chk
	$title = ($opt['sort_ad'] == 'a') ? 'SORT_ASC' : 'SORT_DESC';
	$body .= $opt['cell'] . '<a href="' . $script . "?plugin=union_table&refer=$page&sort_ad="
						 . $opt['sort_ad'] . "&sort_type=" . $opt['sort_type'] . "&sort=" . $opt['sort'] . "&page_link="
						 . $opt['page_link'] . "&sort_sec=" . $opt['sort_sec'] . "&" . $opt['section'] . "&"
						 . join('&', table_filter( '', $opt, $page, 0, 0))
		 				 . '"' . " title=$title>" . "<b>{$opt['mark']}</b></a>";
	return $body;
}

?>
