<?php
/** \disctab.php
* \wikipedialike discussion tab for pmwiki
*
* see also http://www.pmwiki.org/wiki/Cookbook/DiscussionTab
* Provide a tabbed skin with the possibility to have an "discussion"-tab 
* and an "article"-tab as a kind of backlink to the Main Article.
*This one works for me but it's not well coded I think. I am not a programmer
* and I haven't the time to improve my small php knowledge to get it work better.
* Maybe someone find it usefull. If there is some help to improve this ifeel free to publish it.
* -----------------------------------------------------------------------------------------------
*/

/** This provides the action=discuss
*   the regexp was necessary because $Name didn't work for me in the function I wonder why ?? 
*/
SDV($HandleActions['discuss'], 'HandleDiscuss');
SDV($DiscussionAllowedGroup,array());
SDV($DiscussionExceptGroup,array());
SDV($DiscussionString,'-Discuss-');
SDV($DiscussionGroup,'Comments');
$Conditions['hasDiscuss'] = "hasDiscuss(\$pagename)";
function hasDiscuss($pagename){
	$motherPageExist = PageExists(FmtPageName('$Group.$Name', getBaseName($pagename))); 
	$discussionAllowed = discussionAllowed(getBaseName($pagename));
	return ($motherPageExist && $discussionAllowed); 
}
function HandleDiscuss($pagename) {
	global $DiscussionGroup, $DiscussionString;
	$string = $pagename;
	if(!discussionAllowed($string)){ 
		redirect($pagename);
	}else{
		redirect($DiscussionGroup.'.'.preg_replace('/\./', $DiscussionString, $string));
	}
}
function discussionAllowed($pagename){
	global $DiscussionAllowedGroup, $DiscussionExceptGroup;
	$matchGroup = false;
	if(count($DiscussionAllowedGroup)==0){
			$matchGroup = true;
	}else{
		for($c=0; $c<count($DiscussionAllowedGroup); $c++){
			if(preg_match('/^'.$DiscussionAllowedGroup[$c].'/',$pagename)){
				$matchGroup = true; break;
			}
		}
	}
		
	for($c=0; $c<count($DiscussionExceptGroup); $c++){
		if(preg_match('/^'.$DiscussionExceptGroup[$c].'/',$pagename)){
			$matchGroup = false; break;
		}
	}
	return $matchGroup;
}
function getBaseName($arg){
	global $DiscussionString, $DiscussionGroup;
	$patterns[0] = '/'.$DiscussionGroup.'./';
	$patterns[1] = '/'.$DiscussionString.'/';
	$replacements[0] = '';
	$replacements[1] = '.';
	return preg_replace($patterns, $replacements, $arg);
}
$BaseName = getBaseName($pagename);
Markup('{$BaseName}', '>{$fmt}',
	'/{\\$BaseName}/', preg_replace('/-Discuss-/', '.', FmtPageName('$Name', $pagename),1));
?>