<?php
	require_once('config_modulebuilder.inc.php');
	
	if($_GET['pwd']!==ADMIN_PASS)
		die('Invalid Password');
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Module Builder</title>
<script type="text/javascript">
<!--

function validateAndGeneratePageName() {
	document.getElementById('pageTitle').value=document.getElementById('pageTitle').value.replace(/[^a-z^A-Z^_^ ]/,'');
	document.getElementById('pageName').value='index_'+document.getElementById('pageTitle').value.toLowerCase().replace(/ /,'')+'.php';
}

function validator() {
	if(document.getElementById('pageTitle')==''||document.getElementById('pageName')=='') {
		alert('One of the boxes is empty.');
		return false;
	}
	else
		return true;
}

-->
</script>
</head>

<body>
<?php 

# ******************************** #
# ***** FUNCTION DEFINITIONS ***** #

//extracts the contents of $fileString between 'begin' and 'end' elements of $delimRay inclusive
function extractBetween($fileString, $delimRay)
{
	//finds starting index
	if(($startIndex=strpos($fileString,$delimRay['begin']))===FALSE)
	{
		die("Missing".$delimRay['begin']);
	}

	//finds ending index and returns substring
	if(($endIndex=strrpos($fileString,$delimRay['end']))!==FALSE)
	{
		$outString=substr($fileString,$startIndex,$endIndex-$startIndex+strlen($delimRay['end']));
		//var_dump($outString);
		return $outString;
	}
	else {
		die("Missing".$delimRay['end']);
	}

}

//extracts the contents of $fileString before and including the header delimeter
function extractHeader($fileString, $headerDelim)
{
	$startIndex=0;

	//finds ending index and returns substring
	if(($endIndex=strrpos($fileString,$headerDelim))!==FALSE)
	{
		$outString=substr($fileString,$startIndex,$endIndex-$startIndex+strlen($headerDelim));
		//var_dump($outString);
		return $outString;
	}
	else {
		die("Missing".$headerDelim);
	}

}

//extracts the contents of $fileString between 'begin' and 'end' elements of $delimRay inclusive
function extractFooter($fileString, $footerDelim)
{
	//finds starting index
	if(($startIndex=strpos($fileString,$footerDelim))===FALSE)
	{
		die("Missing".$footerDelim);
	}

	$outString=substr($fileString,$startIndex);
	return $outString;

}

//generates the module specified by the given arguments
function generateModule($moduleName) {
	global $modulesPath;
	global $includesPath;
	global $indexDir;
	global $contentDelims;
	
	global $modulePrependInfo;
	global $newModuleContent;
	
	$moduleIndexPath=$indexDir."index_".$moduleName.".php";
	$moduleFilePath=$indexDir.$modulesPath.$moduleName.".inc.php";
	
	
	
	if(!file_exists($moduleIndexPath)) {
		//create a new index file and populate it with default info
		
		//default content
		$moduleContent=$newModuleContent;
	
	
		$newIndexFileHeader=file_get_contents($indexDir.$includesPath.'header.inc.php');
		$newIndexFileFooter=file_get_contents($indexDir.$includesPath.'footer.inc.php');

		$moduleIndexHandle=fopen($moduleIndexPath,'w');
		fwrite($moduleIndexHandle,$newIndexFileHeader.$moduleContent.$newIndexFileFooter);
		fclose($moduleIndexHandle);
		
	}
	else {
	
		//if index file already exists
		$moduleIndexString=file_get_contents($moduleIndexPath);
		
		//gets the content that is going to go in the module
		$moduleContent=extractBetween($moduleIndexString,$contentDelims);

	
	}
	
		
	$moduleContent=$modulePrependInfo.$moduleContent;
	
	//var_dump($moduleContent);
	$moduleHandle=fopen($moduleFilePath,'w');
	fwrite($moduleHandle,$moduleContent);
	fclose($moduleHandle);
	
}



//page is new
if(isset($_POST['submit'])) {


//needed only for creating new modules
$pageTitle=$_POST['pageTitle'];
$inFileName=$_POST['pageName'];


//extracts the name of the module for use in index.php
preg_match($inFilePathRegex, $inFileName, $matches);
$inFileModuleName=$matches[1];


/* ====adds file to list in index==== */
//gets the index file into a string
$indexFileStr=file_get_contents($indexDir.'index.php');

//a generic case
$caseToAdd=<<<EOD


	case '$inFileModuleName':
		\$page = '$inFileModuleName.inc.php';
		\$page_title = '$pageTitle';
		\$page_name = '$pageTitle';
		break;
EOD;

//prepends $caseToAdd onto the list of cases
$indexFileStr=str_replace($indexDelims['begin'],$indexDelims['begin'].$caseToAdd,$indexFileStr);
$indexHandle=fopen($indexDir."index.php",'w');
fwrite($indexHandle,$indexFileStr);
fclose($indexHandle);


/* ===creates the module file=== */
generateModule($inFileModuleName);
echo "Module $inFileModuleName created.";
}

//refreshes all existing modules
elseif(isset($_POST['refreshexistingmodules'])) {

	//looks through all files in $indexDir, looking for those that match the $inFilePathRegex
	$allFiles=scandir($indexDir);
	foreach($allFiles as $file) {
		
		if(preg_match($inFilePathRegex,$file, $matches))
		{
			//extracts the name of the module for use in module generator function
			$inFileModuleName=$matches[1];
			
			echo "Updated module <b>$inFileModuleName</b> from <b>$file</b> .   ";
			
			//regenerates the module
			generateModule($inFileModuleName);

		}
			
	}

}

//refresh header and footer
elseif(isset($_POST['updateheadersandfooters'])) {

	/* ====updates the .inc.php files==== */
	
	//get the header and footer template file into a string
	$moduleTemplateFileStr=file_get_contents($indexDir.'index_moduletemplate.php');
	
	//update the header module
	$headerHandle=fopen($indexDir.$includesPath.'header.inc.php','w');	
	$newHeaderContent=extractHeader($moduleTemplateFileStr, HEADER_END_DELIM);
	fwrite($headerHandle,$newHeaderContent);
	fclose($headerHandle);
	
	//update the footer module
	$footerHandle=fopen($indexDir.$includesPath.'footer.inc.php','w');	
	$newFooterContent=extractFooter($moduleTemplateFileStr, FOOTER_BEGIN_DELIM);
	fwrite($footerHandle,$newFooterContent);
	fclose($footerHandle);

	/* ====updates the index_ files files==== */
	
	//looks through all files in $indexDir, looking for those that match the $inFilePathRegex
	$allFiles=scandir($indexDir);
	foreach($allFiles as $file) {
	
		if(preg_match($inFilePathRegex,$file, $matches))
		{
			//extracts the name of the module for use in module generator function
			$inFileModuleName=$matches[1];
			if($inFileModuleName=='moduletemplate')
				continue;
			$moduleIndexPath=$indexDir."index_".$inFileModuleName.".php";
			$moduleIndexString=file_get_contents($moduleIndexPath);
			$moduleContent=extractBetween($moduleIndexString,$contentDelims);

			$moduleIndexHandle=fopen($moduleIndexPath,'w');	
			fwrite($moduleIndexHandle,$newHeaderContent.$moduleContent.$newFooterContent);
			fclose($moduleIndexHandle);
			echo "Updated header and footer of <b>index_$inFileModuleName.php</b> from <b>index_moduletemplate.php</b>.   ";
			
			//regenerates the module
			//generateModule($inFileModuleName);

		}
			
	}

}


?>
<form action="<?php echo $_SERVER['PHP_SELF']."?pwd={$_GET['pwd']}"; ?>" method="post">
	<input type="submit" name="refreshexistingmodules" value="Refresh All Existing Modules" />
</form>

<form action="<?php echo $_SERVER['PHP_SELF']."?pwd={$_GET['pwd']}"; ?>" onSubmit="return validator()" method="post">
<br />	
<br />
Page Title (e.g. About Us)
<input type="text" name="pageTitle" id="pageTitle" onKeyUp="javascript:validateAndGeneratePageName()" /><br />
Page Name (e.g. index_aboutus.php, must start with &quot;index_&quot; and end with &quot;.php&quot;)
<input type="text" name="pageName" id="pageName" /><br />
<input type="submit" name="submit" value="Create New Module" />

</form>
<br />
<form action="<?php echo $_SERVER['PHP_SELF']."?pwd={$_GET['pwd']}"; ?>" method="post">
	<input type="submit" name="updateheadersandfooters" value="Update all headers and footers from index_moduletemplate.php" />
</form>

</body>
</html>
