<?php if (!defined('PmWiki')) exit();

/*	=== CaseCorrection ===
 *	Copyright 2008 Eemeli Aro <eemeli@gmail.com>
 *
 *	Makes PmWiki intelligently case-insensitive
 *
 *	Developed and tested using the PmWiki 2.2.0-beta series.
 *
 *	To install, add the following line to your configuration file :
		include_once("$FarmD/cookbook/casecorrect.php");
 *	and add the directive (:case-correction:) to your 404 page, by 
 *	default located at Site.PageNotFound
 *
 *	For more information, please see the online documentation at
 *		http://www.pmwiki.org/wiki/Cookbook/CaseCorrection
 *
 *	This program is free software; you can redistribute it and/or
 *	modify it under the terms of the GNU General Public License,
 *	Version 2, as published by the Free Software Foundation.
 *	http://www.gnu.org/copyleft/gpl.html
 */

$RecipeInfo['CaseCorrection']['Version'] = '2008-09-03';

Markup( 'casecorrection', '<{$var}', '/\\(:case-correction:\\)/ei', "URLCaseCorrection(\$pagename)" );
function URLCaseCorrection( $pagename ) {
	global $FmtPV, $ScriptUrl, $DefaultPage, $PageNotFoundPageName;

	SDV( $PageNotFoundPageName, 'PageNotFound' );
		
	$url = urldecode( $_SERVER["REQUEST_URI"] );
	$url = substr( $url, 0, strcspn($url,'?$&') );

	$rel_s = preg_replace( '!^[a-z]+://[^/]*!i', '', $ScriptUrl );
	$clean_url = strncmp( $url, $rel_s, strlen($rel_s) ) ? $url : substr( $url, strlen($rel_s) );
	$clean_url = trim( preg_replace( '#(?:index|main)?\.(?:html?|php)$#i', '', $clean_url ), '/' );

	preg_match( '!([^./]*)(?:[./]([^./]*))?$!', $clean_url, $um );
	$fn = MakePageName($DefaultPage,$um[1].'.'.@$um[2]);

	if ( 
		( strpos($url,$PageNotFoundPageName) === FALSE ) && 
		( $ls = ListPages("/^$fn$/i") ) 
	) {
		header("HTTP/1.1 301");
		Redirect(reset($ls));
	} else if ( $pagename == FmtPageName( "{\$SiteGroup}.$PageNotFoundPageName", $DefaultPage ) ) {
		$wn = explode('.',$fn);
		$FmtPV['$Group'] = "(\$pn=='$pagename')?'{$wn[0]}':\$group";
		$FmtPV['$Name'] = "(\$pn=='$pagename')?'{$wn[1]}':\$name";
		$FmtPV['$FullName'] = "(\$pn=='$pagename')?'$fn':\"\$group.\$name\"";
		$FmtPV['$RequestedPage'] = "'".htmlspecialchars($um[0],ENT_QUOTES)."'";
	}
	$FmtPV['$RequestedUrl'] = "'".htmlspecialchars($url,ENT_QUOTES)."'";
}