<?php if (!defined('PmWiki')) exit();
/*
+----------------------------------------------------------------------+
| Copyright 2008 Hans Bracker
| 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
| This program is distributed in the hope that it will be useful,
| but WITHOUT ANY WARRANTY; without even the implied warranty of
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
| GNU General Public License for more details.
+----------------------------------------------------------------------+
| redirectmap.php add-on recipe module for PmWiki
| for creating shortcut redirect urls
| Instructions on how to use it see page Cookbook.RedirectMap on pmwiki.org
+----------------------------------------------------------------------+
*/

$RecipeInfo['RedirectMap']['Version'] = '2008-07-11';

//do nothing if we don't have a 'goto' input
if (!isset($_REQUEST['goto'])) return '';

//get goto parameter from input
$goto = htmlspecialchars(stripmagic($_REQUEST['goto']), ENT_NOQUOTES);

//set $SiteGroup in case it is not (for older PmWiki versions)
if(!isset($SiteGroup)) $SiteGroup = 'Site';

//set array with files and pages which could contain redirect mappings
$RedirectMapFiles = array("$FarmD/local/redirectmap.txt", 
		'$SiteGroup.RedirectMap', 'local/redirectmap.txt');

foreach((array)$RedirectMapFiles as $f) {
	$f = FmtPageName($f, $pagename);
	if (($v = @file($f))) 
		$v = preg_replace('/^\\s*(?>\\w[-\\w]*)(?!:)/m', '$0:', implode('', $v));
	else if (PageExists($f)) {
		$p = ReadPage($f, READPAGE_CURRENT);
		$v = $p['text'];
	} else continue;
	//extract entries
	if (!preg_match_all("/^\\s*(\\w[-\\w]*):[^\\S\n]+(\\S*)/m", $v, 
                      $match, PREG_SET_ORDER)) continue;
	foreach($match as $m) {
		//check if entry key matches goto input
		if ($m[1]!=$goto) continue;
			//resolve any variable sorincomplete pagenames in the mapping value
			$urlfmt = FmtPageName($m[2], $pagename);
			//set a wiki Group.PageName url if url does not start with 'http'
			if (strpos($m[2], 'http') === false) 
				$urlfmt = ($EnablePathInfo) 
					? $ScriptUrl."/".$urlfmt 
					: $ScriptUrl."?n=".$urlfmt;
			//do the redirect
			Redirect($pagename, $urlfmt);
			exit;
	}
}