<?php

/**
 * @version     Version 1.2 - 2008-09-18
 * @copyright   Copyright © 200-20086 by Paul Chaplin.
 * @author      Paul Chaplin <http://www.paulchaplin.com/>
 * @license     http://creativecommons.org/licenses/by-sa/2.0/uk/ Released under a Creative Commons licence.
 * 
 * Add this line to your .htaccess file:
 * 	DirectoryIndex (...whatever you had before goes here; index.html etc.) /dirlist.php
 * 
 * Put dirlist.php in your site's root directory, and enjoy valid-markup directory listings.
 * Style it with CSS, attach unobtrusive JavaScript, and anything else you like.
*/

// This breaks in Opera 9! ...Or is it Apache 2.2?!
// Prevents listing of the top-level directory - remove the " || empty(...)" to allow.
if ( !isset($_SERVER['REDIRECT_URL']) || empty($_SERVER['REDIRECT_URL']) )
{
	$_SERVER['REDIRECT_URL'] = $_SERVER['REQUEST_URI'];
	/*
	header('Content-Type: text/plain; charset=UTF-8');
	print_r($_SERVER);
	exit;
	/**/
}

// Create sanitised copies of variables
$httpHost = htmlspecialchars($_SERVER['HTTP_HOST']);
$redirUrl = htmlspecialchars(urldecode($_SERVER['REDIRECT_URL']));

header('Content-Type: text/html; charset=UTF-8');
echo <<<HEADER
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
	<title>{$httpHost}{$redirUrl}</title>
	<link type="text/css" rel="stylesheet" href="/css/dirlist.css" />
</head>
<body>
	<h1>Directory listing for {$redirUrl}</h1>
	<ul>

HEADER;

$thisDir = dirname(__FILE__) . urldecode($_SERVER['REDIRECT_URL']);
$dir = opendir($thisDir);
while ( false !== ($file = readdir($dir)) )
{
	switch ( $file )
	{
		// files to ignore (now ignores dot-prefixed files and directories)
		case '.':
		case '.htaccess':
		case ( 0 === strpos($file, '.', 0) ):
		case 'pmob':
			break;
		// catch '..' and distinguish it from other directories
		case '..':
			$files .= "\t\t"
				 . '<li class="up"><a href="../">../</a></li>'
				 . "\n";
			break;
		// normal execution
		default:
			$fileExt = explode('.', $file);
			$fileExt = htmlspecialchars($fileExt[count($fileExt)-1]);
			if ( is_dir($thisDir . $file) )
			{
				$file .= '/';
				$fileExt = 'dir';
			}
			$file = htmlspecialchars($file);
			$files .= "\t\t"
				 . '<li class="'
				 . $fileExt
				 . '"><a href="'
				 . $redirUrl . $file
				 .'">'
				 . $file
				 . '</a></li>'
				 . "\n";
	}
}
closedir($dir);
echo $files;

echo <<<FOOTER
	</ul>
</body>
</html>
FOOTER;

?>
