<?PHP
/**
 * @package: 	ldir()
 * @author:  	Adam Boutcher <adam@aboutcher.co.uk>
 * @link:    	http://webs.aboutcher.co.uk/ldir
 * @version: 	1.8.0
 * @internal:	$GET is deprecated but left to provide BC.
 **/   
/*************************************
  GNU GENERAL PUBLIC LICENSE v3
  
  ldir - PHP Function to list files and directories inside the specified path.
  Copyright (C) 2013  Adam Boutcher

  This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

  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.

  You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*************************************/  
function ldir($ListDir,$hiddentypes=array(NULL),$hiddenfiles=array(NULL),$GET=NULL) {
	$ldir['v'] = "1.8.0";
	$ldir['im'] = "http://dl.dropbox.com/u/14071642/lister/";
	$ldir['ia'] = array("bin","bmp","css","doc","docx","exe","gif","html","iso","jpg","mkv","mp3","mp4","pdf","php","phps","png","ppt","pptx","rar","txt","wav","xls","xlsx","xml","zip");
	$return = 1;
	$self = explode("?", $_SERVER['REQUEST_URI']);
	$self = explode("/", $self[0]);
	$self = array_pop($self);
	if (!empty($_SERVER['QUERY_STRING'])) {
		$GET = "?".$_SERVER['QUERY_STRING']."&amp;";
	} elseif(!empty($GET)) {
		$GET = "?".$GET."&amp;";
	}else {
		$GET = "?";
	}
	function ldir_version_check($current,$latest_location) {
		$latest = explode(".",@file_get_contents($latest_location));
		$current = explode(".",$current);
		$li = count($latest);
		$ci = count($current);
		$i = 0;
		if($li==$ci) {
			do {
				if ($latest[$i] > $current[$i]) {
					return true;
				} else {
					$i++;
				}
			} while (($i != $ci)||($i != $li));
			return false;
		} else {
			// This is if the version numbers are in different formats.
			return false;
		}
	}
	function ldir_url_exists($url,$version=NULL) {
		$handle = curl_init($url);
		if (false === $handle) { return false; }
		curl_setopt($handle, CURLOPT_HEADER, false);
		curl_setopt($handle, CURLOPT_FAILONERROR, true);
		curl_setopt($handle, CURLOPT_HTTPHEADER, Array("User-Agent: Mozilla/5.0 (PHP; U; ldir; en-GB; rv:".$version.") ldir/".$version) );
		curl_setopt($handle, CURLOPT_NOBODY, true);
		curl_setopt($handle, CURLOPT_RETURNTRANSFER, false);
		$connectable = curl_exec($handle);
		curl_close($handle);  
		return $connectable;
	}
	echo "\n<!--\n\tldir()\tv".$ldir['v']."\n\tAuthor:\tAdam Boutcher\n\tWeb:\thttp://webs.aboutcher.co.uk/ldir";
	$update = ldir_version_check($ldir['v'],"http://update.aboutcher.co.uk/ldir-version");
	if($update === true) {
		echo "\n\tUpdate Available!";
	}
	echo "\n-->";
	//Add these onto the list of what to hide and what not to
	$hiddenfiles[] = $self;
	$hiddenfiles[] = ".htpasswd";
	$hiddenfiles[] = ".htaccess";
	$directory = $ListDir."/";
	if(isset($_GET['f'])) {
		if((isset($_GET['f']))&&($_GET['f']=="")) {
			@header("location: ".$self.$GET);
			@ob_flush();
		}
		// Add some checks here eventually!
		$fldr = $_GET['f'];
		//Checking for injection. Now allows ..folder/
		$injection = strpos($fldr, "..");
		if($injection > -1) {
			$inject_temp = substr($fldr,$injection,(strlen($fldr)-$injection));
			if(strlen($inject_temp) > 2) {
				if(strpos($inject_temp, "/")!=2) { $injection = -1;	}
				unset ($inject_temp);
			}
		}
		$directory = $ListDir."/".$fldr."/";
	}
	if (@file_exists($directory)) {
		//Check for PHP version, v4 doesn't support scandir()
		if (!function_exists("scandir")) {
			function scandir($directory) {
				$dtemp = @opendir($directory);
				if($dtemp == true) {
					while (false !== ($ftemp = readdir($dtemp))) { $dir[] = $ftemp;	}
					unset ($ftemp);
					unset ($dtemp);
					return $dir;
				} else {
					return false;
				}
			}
		}
	} else {
		echo "Cannot Display Directory";
	}
	$dir = @scandir($directory);
	if ($dir==false) {
		$here = 1;
		if(!empty($fldr)) {
			$return = 2;
		} else {
			return false;
		}
	}
	//Start Table
	echo "\n<div class=\"files\">";
	echo "\n\t<span class=\"refresh\"><em><a href=\"javascript:document.location.reload();\" title=\"Refresh\" >Refresh</a></em></span>";
	echo "\n\t<h4><img src=\"".$ldir['im']."logo.png\" style=\"vertical-align:middle\" alt=\"Directory Lister Logo\"/>&nbsp;".ucfirst($directory)."</h4>";
	echo "\n\t<table style=\"width:100%;\">";
	echo "\n\t\t<tr>\n\t\t\t<th style=\"text-align: left;\" class=\"type\">Type</th>\n\t\t\t<th style=\"text-align: left;\" class=\"name\">File Name</th>\n\t\t\t<th style=\"text-align: left;\" class=\"size\">File Size</th>\n\t\t</tr>";
	if($injection > -1) {
		//This is when people try to Inject
		$return = 4;
		echo "\n\t\t<tr>\n\t\t\t<td class=\"type\"><a href=\"".$_SERVER['PHP_SELF'].$GET."\" title=\"Error\"><img src=\"".$ldir['im']."error.png\" alt=\"Error\" border=\"0\"/></a></td>\n\t\t\t<td class=\"name\"><a href=\"".$_SERVER['PHP_SELF'].$GET."\" title=\"Error\">Error: No access allowed.</a></td>\n\t\t\t<td class=\"size\"><em>ERROR</em></td>\n\t\t</tr>";
	} else {
		if((isset($_GET['f']))&&($_GET['f']!="")) {
			$backlink = $GET."f=".urlencode(substr($fldr,0,-(strlen(substr($fldr,strrpos($fldr,"/"),strlen($fldr))))));
			echo "\n\t\t<tr><td class=\"type\"><a href=\"".$backlink."\" title=\"Parent Folder\"><img src=\"".$ldir['im']."parent.png\" alt=\"Parent Folder\" border=\"0\" /></a></td><td class=\"name\"><a href=\"".$backlink."\" title=\"Parent Folder\">Parent Folder</a></td><td class=\"size\"><em>&nbsp;</em></td></tr>";
		}
		$URL = "http://".$_SERVER['HTTP_HOST'].rtrim(dirname($_SERVER['PHP_SELF']), '/\\')."/".$extra;
		$i = 0;
		while(isset($dir[$i])) {
			$linkmaker = 0;
			$extt = (strrpos($dir[$i], ".")+1);
			$ext = substr($dir[$i], $extt,((strlen($dir[$i])) - $extt));
			unset($extt);
			if(is_dir($directory."/".$dir[$i])) {
				$img = "folder.png";
				$type = "Folder";	
				$size = "N/A";
				$linky[$i] = $GET."f=".$dir[$i];
				if(isset($_GET['f'])) {
					$linky[$i] = $GET."f=".$fldr."/".$dir[$i];
				}			
			} else {
				$img = "unknown.png";
				$type = "Unknown File";
				//Remove this check to speed things up.
				if((in_array($ext,$ldir['ia']))||(ldir_url_exists($ldir['im'].strtolower($ext).".png",$ldir['v']))) {
					if(!in_array($ext,$ldir['ia'])) {
						$ldir['ia'][] = $ext;
					}
					$img = strtolower($ext).".png";
					$type = strtoupper($ext)." File";
				}
				$size = round(((@filesize($directory."/".$dir[$i]))/1024)/1024,2)." MB";
				$linky[$i] = $URL.$directory.$dir[$i];
			}
			// Hide dot files
			$dott = strpos($dir[$i],".");
			$dott++;
			if (((($dir[$i] == ".")||($dir[$i] == ".."))||((in_array($dir[$i],$hiddenfiles))||(in_array($ext,$hiddentypes))))||((in_array(".?",$hiddentypes))&&($dott == "1"))) {
				// Hide parent folder and self
				echo "";
			} else {
				echo "\n\t\t<tr>\n\t\t\t<td class=\"type\"><a href=\"".$linky[$i]."\" title=\"$dir[$i]\"><img src=\"".$ldir['im'].$img."\" alt=\"".$type."\" style=\"border:0px;\"/></a></td>\n\t\t\t<td class=\"name\"><a href=\"".$linky[$i]."\" title=\"$dir[$i]\">".$dir[$i]."</a></td>\n\t\t\t<td class=\"size\"><em>".$size."</em></td>\n\t\t</tr>";
			}
			$i++;
		}
	}
	echo "\n\t</table>";
	echo "\n\t<br/>";
	if($update === true) { echo "<p class=\"update\" style=\"text-align:left;\"><small><em>ldir() Update Available.</em></small></p>"; }
	echo "\n</div>";
	echo "\n<!--\n\tEND ldir\n-->\n";
	echo '<p style="margin-top: -35px; text-align: right;" class="ldir_link"><a href="http://webs.aboutcher.co.uk/ldir">ldir Powered</a>.</p>';
	if ($return == 0) {
		return false;
	} else if($return == 1) {
		return true;
	} else {
		return $return;
	} 
}
?>