Extension:SubpageIndex/version 0.9

From MediaWiki.org
Jump to navigation Jump to search
<?

# SubpageIndex, subpage listing extension for MediaWiki
# copyright HonoredSoft 2011, available under LGPL
# version 0.9
#
# USE:
#	For current page: <SubpageIndex />
#	For other page: <SubpageIndex>Pagename</SubpageIndex>
#	For other page and namespace: <SubpageIndex>Namespace:Pagename</SubpageIndex>

require("includes/Title.php");
require("includes/Namespace.php");

$wgExtensionFunctions[] = "wfSubpageIndex";

function list_subPages($text, array $args, Parser $parser, PPFrame $frame) {
	global $wgTitle, $wgDBprefix;
	$dbr =& wfGetDB(DB_MASTER);
	$output = '<div class="embed">';
	$end = '</div>';
	$limit = 1; // reference to limit of 1 on explode and str_replace, just to avoid pass-by-value fatal error
	
	// current title and namespace
	$title = $origTitle = $wgTitle->getDBkey(); # pagename (without namespace)
	$ns = $origNS = $wgTitle->getNamespace(); # namespace as a number

	// if alternate title/namespace supplied, they must be used
	if(!empty($text)) {
		$text = $parser->recursiveTagParse($text, $frame);
		$tokens = explode(':', $text);
		$nid = MWNamespace::getCanonicalIndex(strtolower($tokens[0]));
		if(!empty($nid)) {
			$ns = $nid;
			array_shift($tokens);
		}
		$title = str_replace(' ', '_', join(':', $tokens));
	}

	$sql = "SELECT page_title FROM {$wgDBprefix}page where page_namespace='{$ns}' and page_title LIKE '$title/%' ORDER BY page_title";
	$res = $dbr->query($sql);
	$count = $dbr->numRows($res);
	if($count === 0) {
		$output .= '<em>There are no subpages.</em>';
	} else {
		$output .= "<strong>$title: </strong>";
		while($row = $dbr->fetchRow($res)) {
			$rowTitle = Title::makeTitle($ns, $row[0]);
			$rowURL = $rowTitle->getLocalURL();
			$rowLabel = $rowTitle->getText();
			$rowTitle = str_replace('_', ' ', str_replace($title.'/', '', $row[0], $limit));
			if($row[0] === $origTitle && $ns == $origNS)
				$pages[$row[0]] = "<strong>$rowTitle</strong>";
			else
				$pages[$row[0]] = "<a href='$rowURL'>$rowTitle</a>";
		}
		$output .= join(' - ', $pages);
	}
	return $output . $end;
}

function wfSubpageIndex() {
	global $wgParser, $wgTitle;
	$wgParser->setHook("SubpageIndex", list_subPages);
	$wgParser->setHook("PageTOC", list_subPages);
}

?>