<?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-02';

Markup( 'casecorrection', '<{$var}', '/\\(:case-correction:\\)/ei', "URLCaseCorrection()" );
function URLCaseCorrection() {
	global $FmtPV, $DefaultPage;
	
	$url = urldecode( $_SERVER["REQUEST_URI"] );
	$url = substr( $url, 0, strcspn($url,'?$&') );
	$FmtPV['$BadURL'] = "'" . substr($url,1) . "'";

	$url = trim( preg_replace( '#/?(?:index|main)?(?:\.html?|\.php)?$#i', '', $url ), '/' );
	preg_match( '#([^./]*)(?:[./]([^./]*))?$#', $url, $um );
	if ( empty($um[2]) ) $um[2] = $um[1];

	if ( 
		( stripos($url,'pagenotfound') === FALSE ) && 
		( $ls = ListPages("/^{$um[1]}.{$um[2]}$/i") ) 
	) {
		header("HTTP/1.1 301");
		Redirect(reset($ls));
	} else {
		$FmtPV['$BadGroup'] = "'{$um[1]}'";
		$FmtPV['$BadName'] = "'{$um[2]}'";
		$FmtPV['$BadBestGuess'] = "'".MakePageName( $DefaultPage, $um[1].'.'.$um[2] )."'";
	}
}