<?php

$PRESENTATION_TITLE = "Nelson Family Christmas"; // Used in the title of every page along with a page counter.
$HOME_PAGE = urlInThisFolder('home.html'); // Where you go when you hit the "home" nav button. Can be URL.
$END_PAGE = urlInThisFolder('home.html'); // If you hit "back" when you're at beginning or hit "next" at the end.
$IMAGE_ALIGN = "right";

$slides = CreateFileNameArray();
if (empty($slides)) {
	echo "<html><head><title>Error - No Files</title></head>";
	echo "<body>Error - There are no text, picture, or sound files in ";
	echo "the " . urlInThisFolder('') . " folder. </body></html>";
}
else {
	@$slideNumber = $_GET['slide'];
	if (empty($slideNumber)) {
		echo WebPage(0, $slides);
	}
	else {
		echo WebPage($slideNumber, $slides);
	}
}

Function CreateFileNameArray(){
 	// Create 2-D array of base names and picture/sound/text extensions (if they exist). 
 	// Arrays of file extensions are shown with most desired extension on the right.
	$slides = fileArray(array(), array('txt'), 'text');
	$slides = fileArray($slides, array('bmp', 'png', 'jpg', 'jpeg', 'gif', 'htm'), 'picture');
	$slides = fileArray($slides, array('mid', 'wma', 'mp3', 'au', 'wav'), 'sound');
	// Return the array of slides
	if (!empty($slides)) {
		return $slides;
	}
}

Function fileArray($slides, $extensionsArray, $indexName) {
// Add data about file types (in the $extensionArray) to the $slides array
	foreach ($extensionsArray as $extension) {
		if ($handle = opendir('./')) {
			while (false !== ($filepath = readdir($handle))) {
				if (strtolower(substr($filepath, strpos($filepath, ".") + 1)) == $extension) {
					$filebase = basename($filepath, '.' . $extension);
					$fileExt = substr($filepath, strrpos($filepath, ".") + 1);
					if (empty($slides)) {
						$slides[$filebase] = array('name'=>$filebase, 'sound'=>'', 'picture'=>'', 'text'=>'');
					}
					if (!(array_key_exists($filebase, $slides))) {
						$slides[$filebase] = array('name'=>$filebase, 'sound'=>'', 'picture'=>'', 'text'=>'');
					}
					$slides[$filebase][$indexName] = $extension;
				}
			}
			closedir($handle); 
		}
	}
	return $slides;
}

Function WebPage($index, $slidesArray){
// Returns HTML to display the slide in the array element pointed to by the index
	// Get slide data for the slide that matches the desired index
	$slide = slideArray($index, $slidesArray);
	// HTML page header
	$html = "<html>\n<head><title>";
	$html .= $GLOBALS["PRESENTATION_TITLE"];
	$html .= " - Page " . ($index + 1) . " of " . count($slidesArray);
	$html .= "</title></head>\n<body>\n";
	// Nav buttons and sound
	$html .= topHtml($index, $slidesArray);
	$html .= "\n<hr>\n";
	// Slide content
	$html .= slideHtml($index, $slidesArray);
	// Add script to make the "Next" button have focus
	$html .= "<script>setTimeout('document.getElementById(\"Next\").focus();', 1000);</script>";
	$html .= "</body>\n</html>\n";
	return $html;
}

Function topHtml($index, $slidesArray) {
	$html = '';
	$html .= "<table border='0' width='100%'>\n";
	$html .= "<tr><td align='left'>\n";
	// Navigation button code
	$html .= navigationButtons($index, $slidesArray);
	$html .= "</td>\n";
	// Media Player code
	$html .= "<td align='right'>\n";
	$slide = slideArray($index, $slidesArray);
	If ($slide['sound'] != '') {
		$sound = urlInThisFolder($slide['name'] . '.' . $slide['sound']);
		if (isIE()) {
			// The SoundIE function needs to know the URL of the next page
			if ($index == (count($slidesArray) - 1)) {
				$html .= SoundIE($sound, $GLOBALS["END_PAGE"]);
			} 
			else {
				$html .= SoundIE($sound, argumentsForThisUrl('?slide=' . ($index + 1)));
			}
		}
		elseif (IsWin()) {
			$html .= SoundWindows($sound);
		}
		else {
			$html .= SoundGeneric($sound);
		}
	}
	$html .= "</td></tr></table>\n";
	return $html;
}

Function slideHtml($index, $slidesArray) {
// Returns HTML to display the slide
	$slide = slideArray($index, $slidesArray);
	$html = '';
	// Picture
	$html .= pictureHtml($slide);
	// Text
	$html .= textHtml($slide);
	return $html;
}

Function slideArray($desiredIndex, $slidesArray) {
// Returns a one-dimensional array containing data about the slide
	// Sort the slides in "natural" order ("1a" comes before "10a")
	$keys = array_keys($slidesArray);
	natcasesort($keys);
	// Check all slides until the index matches
	$pointer = -1; // Incremented to get the index for each slide in the array
	foreach ($keys as $key) {
		// Increment the pointer
		$pointer = $pointer + 1;
		if ($pointer == $desiredIndex) {
			return $slidesArray[$key];
		}
	}
}

Function urlInThisFolder($document) {
	// Check popular server variables for a URI
	$uri = '';
	foreach (array('PHP_SELF', 'REQUEST_URI', 'SCRIPT_NAME', 'REDIRECT_URL') as $varName) {
		if (empty($uri)) {
			$uri = $_SERVER[$varName];
			if (!empty($uri)) {
				if (substr($uri, 0, 1) != '/') {
					$uri = '';
				}
			}
		}
	}
	// Strip off the script name
	$path = substr($uri, 0, strrpos($uri, "/"));
	// Assemble the new URL
	return "http://" . $_SERVER["SERVER_NAME"] . $path . "/" . str_replace(" ", "%20", $document);
}

Function argumentsForThisUrl($args) {
// Adds HTTP GET arguments to the existing script. Typical $args = '?foo=bar&afu=yes'
	$uri = '';
	// Check popular server variables for a URI
	foreach (array('PHP_SELF', 'REQUEST_URI', 'SCRIPT_NAME', 'REDIRECT_URL') as $varName) {
		if (empty($uri)) {
			$uri = $_SERVER[$varName];
			if (!empty($uri)) {
				if (substr($uri, 0, 1) != '/') {
					$uri = '';
				}
			}
		}
	}
	$urlArray = explode('?', $uri);
	return "http://" . $_SERVER["SERVER_NAME"] . $urlArray[0] . $args;
}

Function isIE(){
	return strpos($_SERVER["HTTP_USER_AGENT"], "MSIE") !== false;
}

Function isWin(){
	return strpos($_SERVER["HTTP_USER_AGENT"], "Windows") !== false;
}

Function pictureHtml($slide){
// Returns the HTML needed to display the picture (if one exists)
	$html = '';
	If ($slide['picture'] != '') {
		if (strtolower($slide['picture']) == 'htm') {
			// Picture is an htm file! Read it so we can use it's text.
			$handle = fopen($slide['name'] . '.' . $slide['picture'], "r");
			$body = fread($handle, filesize($slide['name'] . '.' . $slide['picture']));
			fclose($handle);
			// Use only the text inside the <body> tags
			$pointer = stripos($body, '<body'); // location of body tag
			$body = substr($body, $pointer); // remove all before body tag
			$pointer = strpos($body, '>'); // location of end of body tag
			$body = substr($body, $pointer + 1); // remove through end of body tag
			$pointer = stripos($body, '</body'); // location of end body tag
			$body = substr($body, 0, $pointer - 1); // crop all before end body tag 
			$html .= $body;
		}
		// Picture is a real graphics file, just insert an img tag
		else {
			$html .= "<img src='";
			$html .= urlInThisFolder($slide['name'] . '.' . $slide['picture']);
			$html .= "'";
			// Only use the align property if we have to mix in some text with the image
			If ($slide['text'] != '') {
				$html .= " align=" . $GLOBALS['IMAGE_ALIGN'];
			}
			$html .= ">\n";
			$html .= "<img height=1 width=100><br> \n"; // Makes sure there is room for text under Mozilla
		}
	}
	return $html;
}

Function textHtml($slide){
// Returns the HTML needed to display the text data (if text exists)
	$html = '';
	If ($slide['text'] != '') {
		// Read the text file so we can spit it into our html stream
		$handle = fopen($slide['name'] . '.' . $slide['text'], "r");
		$html = fread($handle, filesize($slide['name'] . '.' . $slide['text']));
		fclose($handle);
		// Escape the text to make it HTML-safe
		$html = htmlentities($html);
		// Make simple text-html formatting decisions
		$html = str_replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;", $html); // TAB characters
		while (strpos($html, "  ")!== false ) {
			$html = str_replace("  ", "&nbsp; ", $html); // Multiple spaces
		}
		while (strpos($html, "\r\n\r\n")!== false ) {
			$html = str_replace("\r\n\r\n", "<p>\r\n", $html); // DOS line terminators
		}
		while (strpos($html, "\n\n")!== false ) {
			$html = str_replace("\n\n", "<p>\n", $html); // Unix line terminators
		}
		while (strpos($html, "\r\r")!== false ) {
			$html = str_replace("\r\r", "<p>\r", $html); // Apple line terminators
		}
	}
	return $html;
}

Function navigationButtons($index, $slidesArray) {
// Supplies the HTML code for back, home, and next navigation buttons
// See http://www.ericphelps.com/unicode/ for other unicode values
	$html = '';
	// Back button URL
	$html .= "\t<font size=+2><a href=";
	if ($index == 0) {
		$html .= "'" . $GLOBALS["END_PAGE"] . "'";
	}
	else {
		$html .= "'" . argumentsForThisUrl('?slide=' . ($index - 1)) . "'";
	}
	$html .= cssStyle(); //$html .= " style='text-decoration:none'";
	$html .= " title='Previous' tabIndex='2'>&#9668;</a></font>&nbsp;\n";
	//Home button URL
	$html .= "\t<font size=+2><a href=";
	$html .= "'" . $GLOBALS["HOME_PAGE"] . "'";
	$html .= " title='Home' tabIndex='3'";
	$html .= cssStyle(); //$html .= " style='text-decoration:none'";
	$html .= ">&#9650;</a></font>&nbsp;\n";
	// Next button URL
	$html .= "\t<font size=+2><a href=";
	if ($index == (count($slidesArray) - 1)) {
		$html .= "'" . $GLOBALS["END_PAGE"] . "'";
	} else {
		$html .= "'" . argumentsForThisUrl('?slide=' . ($index + 1)) . "'";
	}
	$html .= cssStyle(); //$html .= " style='text-decoration:none'";
	// Add id, name, and tabindex attributes to next button so we can give it focus later
	$html .= " title='Next' id='Next' name='Next' tabIndex='1'>&#9658;</a></font>";
	$html .="</td>\n";
	return $html;
}

Function cssStyle(){
//Returns style code that can be inserted into an "a" tag to make it into a button
	$css = '';
	$css .= ' style="';
	$css .= "color: black; ";
	$css .= "border: 1px solid; ";
	$css .= "background-color: gray; ";
	$css .= "padding: 2px; ";
	$css .= "padding-left: 3px; ";
	$css .= "text-decoration: none; ";
	$css .= "border-color: silver black black silver; ";
	$css .= "margin: 0px; ";
	$css .= "text-align: center; ";
	$css .= '" ';
	return $css;
}

Function SoundIE($soundUrl, $nextUrl) {
	$html = "";
	$html .= "	<OBJECT ID='MediaPlayer' width='144' height='45'\n";
	$html .= "		classid='CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95'\n";
	$html .= "		CODEBASE='http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=6,4,5,715'\n";
	$html .= "		standby='Loading Microsoft® Windows® Media Player components...'\n";
	$html .= "		type='application/x-oleobject'>\n";
	$html .= "		<PARAM NAME='FileName' VALUE='" . $soundUrl . "'\n";
	$html .= "		<PARAM NAME='ShowControls' VALUE='True'>\n";
	$html .= "		<EMBED type='application/x-mplayer2'\n";
	$html .= "			pluginspage='http://www.microsoft.com/windows/windowsmedia/download/plugin.aspx'\n";
	$html .= "			height='45' width='144'\n";
	$html .= "			src='" . $soundUrl . "'\n";
	$html .= "			autostart='True' autoplay='True'\n";
	$html .= "			showcontrols='1'\n";
	$html .= "			visible='True' hidden='False'>\n";
	$html .= "		</EMBED>\n";
	$html .= "	</OBJECT></td>\n";
	// The following code causes IE to auto-advance if scripting is enabled.
	if ($nextUrl != ''){ // The nextUrl should be empty at the end of the presentation
		$html .= "	<script LANGUAGE='JavaScript' FOR='MediaPlayer' EVENT='PlayStateChange(OldPlayState, NewPlayState)'>\n";
		$html .= "		 if(OldPlayState == 2 && NewPlayState == 0) {\n";
		$html .= "		 	window.setTimeout('top.location.href=\"" . $nextUrl . "\"', 1000);\n";
		$html .= "		 }\n";
		$html .= "	</script>\n";
	}
	return $html;
}

Function SoundWindows($soundUrl) {
	$html = "";
	$html .= "	<EMBED type='application/x-mplayer2'\n";
	$html .= "		pluginspage='http://www.microsoft.com/windows/windowsmedia/download/plugin.aspx'\n";
	$html .= "		height='45' width='144'\n";
	$html .= "		src='" . $soundUrl . "'\n";
	$html .= "		autostart='True' autoplay='True'\n";
	$html .= "		showcontrols='1'\n";
	$html .= "		visible='True' hidden='False'>\n";
	$html .= "	</EMBED>\n";
	return $html;
}

Function SoundGeneric($soundUrl) {
	$extension = substr($soundUrl, strrpos($soundUrl, ".") + 1);
	$extension = strtolower($extension);
	$mimes = array('au'=>'audio/basic', 'mid'=>'audio/midi', 'mp3'=>'audio/mpeg', 'wav'=>'audio/wav', 'wma'=>'audio/x-wma');
	$html = "";
	$html .= "	<EMBED type='" . $mimes[$extension] . "'\n";
	$html .= "		height='45' width='144'\n";
	$html .= "		src='" . $soundUrl . "'\n";
	$html .= "		autostart='True' autoplay='True'\n";
	$html .= "		showcontrols='1'\n";
	$html .= "		visible='True' hidden='False'>\n";
	$html .= "	</EMBED>\n";
	return $html;
}

?>