<?php

// key_page.inc.php, 0.1 2007/01/22	taru        plugin

function plugin_key_page_convert()
{
	global $non_list, $vars;

	$args = func_get_args();
	$source_key = 'section';
	$section_on = 1;
	$short = 0;

	if( isset($args[0])) {
		$page_key =  $args[0];
	} else {
		$page_key_e = explode('/', $vars['page']);
		array_pop( $page_key_e );
		$page_key = '^' . join('/', $page_key_e);
	}
	$section_key = isset($args[1]) ? $args[1] : '';
	$opt_key = (isset($args[2]) && $args[2] != '') ? strtolower($args[2]) : 'list';
	$body = ( $opt_key == 'line' ) ? '' : array();
	if ( isset($args[3]) ) {
		$sub_opt = strtolower($args[3]);
		switch ( $sub_opt ) {
			case 'nosection':
				$section_on = 0;
				break;
			case 'title':
				$source_key = 'title';
				break;
			case 'short':
				$short = 1;
				break;
			case 'short_title':
				$source_key = 'title';
				$short = 1;
				break;
		}
	}

//	$page = isset($vars['page']) ? $vars['page'] : '';
//	$page_end_name = array_pop( explode("/", $page) );

	$page_list = auth::get_existpages();	//PukiWiki Plus! i18n
//	$page_list = get_existpages();			//PukiWiki

	foreach ( $page_list as $page_l ){
		if ( preg_match("/$non_list/", $page_l) ) continue;
		if (! preg_match(']' . $page_key . ']', $page_l) && $page_key !== '' ) continue;
		$page_name = ( $short ) ? array_pop( explode("/", $page_l) ) : $page_l;
		if (! $section_key == '' ) {
			$section = section_filter($page_l, $section_key, & $ank, $source_key);
			if ($section == '' && $source_key == 'section' ) {
				continue;
			} else if ( $section_on ) {
				if ( $opt_key == 'table' ) {
					$link = '[[' . $page_name . '>' . "$page_l$ank" . ']]|' . $section;
				} else {
					$link = '[[' . $section . '>' . "$page_l$ank" . ']]';
				}
			} else {
				$link = '[[' . $page_name . '>' . $page_l . ']]';
			}
		} else {
			$link = '[[' . $page_name . '>' . $page_l . ']]';
		}

		switch ( $opt_key ) {
			case 'list':
				$body[] = '-' . $link . "\n";
				break;
			case 'table':
				$body[] = '|' . $link . "|\n";
				break;
			case 'line':
				$body .= $link . '  ';
				break;
		}
	}

	return convert_html($body);
}
function section_filter($page, $section, $ank, $source_key)
{
	$page_source = get_source($page);
	foreach ($page_source as $line_chk) {
		if ( $source_key == 'section' ) {
			if (preg_match('/^(\*{1,3})(.*?)\[#(.*?)\](.*?)$/m',$line_chk,$match_section) && $section !== '') {
				if ( preg_match("/$section/", $match_section[2]) ) {
					$ank = '#' . $match_section[3];
					return $match_section[2];
				}
			}
		} else {
			if (preg_match('/^TITLE:(.*?)$/m',$line_chk,$match_section)) {
				if ( preg_match("/$section/", $match_section[1]) ) {
					$ank = '';
					return $match_section[1];
				}
			}
		}
	}
	return '';
	
}
?>
