Completely rewritten dir tree generator

Previous dir tree was working via the usual recursive method of scandir
The code was problematic as it was creating 3 dir trees and had an
incorrect UL structure
This now works in a completely different way, using PHPs inbuilt
iterators
Performance results are visibly noticable as file manager loads much
quicker
Tests show around a 100% increase in efficiency on servers with 1000's
of files & folders
There is also much less code, less repitition and it's much cleaner to
work with
The incorrect UL & LI structure has now been fixed and is valid
Loads of junk and redundant code removed also
This commit is contained in:
Matt Pass
2012-07-05 22:33:13 +01:00
parent e4fd3927fa
commit 3eb97098bb

284
files.php
View File

@@ -1,173 +1,137 @@
<?php
function fileManager($directory, $return_link) {
$code = "";
// Generates a list of all directories, sub-directories, and files in $directory
// Remove trailing slash
if(substr($directory, -1) == "/" ) {$directory = substr($directory, 0, strlen($directory)-1);};
$code .= fileManager_dir($directory, $return_link);
return $code;
}
function fileManager_dir($directory, $return_link, $first_call=true) {
if (!isset($_SESSION['restrictedFiles'])) {include("lib/settings.php");};
$restrictedFiles = $_SESSION['restrictedFiles'];
$bannedFiles = $_SESSION['bannedFiles'];
$docRoot = str_replace("\\","/",$_SERVER['DOCUMENT_ROOT']);
if (strrpos($_SERVER['DOCUMENT_ROOT'],":")) {
$serverType = "Windows";
} else {
$serverType = "Linux";
}
// Chop off trailing slash
if (strrpos($docRoot,"/")==strlen($docRoot)-1) {$docRoot = substr($docRoot,0,strlen($docRoot)-1);};
$fileManager = "";
// Recursive function called by fileManager() to list directories/files
// Get and sort directories/files
if(function_exists("scandir")) {$file = scandir($directory);} else {$file = php4_scandir($directory);};
natcasesort($file);
// Make directories first
$files = $dirs = array();
foreach($file as $this_file) {
if(is_dir("$directory/$this_file")) {$dirs[] = $this_file;} else {$files[] = $this_file;};
}
$file = array_merge($dirs, $files);
// Filter unwanted files
if(!empty($bannedFiles)) {
foreach(array_keys($file) as $key) {
$fileFolder = $file[$key];
for ($i=0;$i<count($bannedFiles);$i++) {
if(strpos($fileFolder,$bannedFiles[$i])!==false) {unset($file[$key]);};
}
}
}
if(count($file) > 2) { // To ignore . and .. directories
if($first_call) {
// Root Directory
$dirRep = str_replace("\\","/",$directory);
$link = str_replace("[link]", "$dirRep/", $return_link);
$link = str_replace("//","/",$link);
$fileAtts = "";
if ($serverType=="Linux") {
$chmodInfo = substr(sprintf('%o', fileperms($link)), -3);
$fileAtts = '<span style="color: #888; font-size: 8px" id="|_perms">'.$chmodInfo.'</span>';
}
$fileManager = "<ul class=\"fileManager\">";
$fileManager .= "<li class=\"pft-directory\"><a href=\"#\" onMouseOver=\"top.ICEcoder.overFileFolder('folder','$link')\" onMouseOut=\"top.ICEcoder.overFileFolder('folder','')\" style=\"position: relative; left:-22px\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span id=\"|\">/ [ROOT]</span> ".$fileAtts."</a>";
$fileManager .= $fileManager .= fileManager_dir("$directory/", $return_link ,false);
$fileManager .= "</li>";
$first_call = false;
} else {
$fileManager = "<ul>";
}
foreach( $file as $this_file ) {
$bannedFile=false;
for ($i=0;$i<count($bannedFiles);$i++) {
if (strpos($directory,$bannedFiles[$i])!=""||strpos($this_file,$bannedFiles[$i])!="") {
$bannedFile=true;
}
}
if( $this_file != "." && $this_file != ".." && $bannedFile == false) {
if( is_dir("$directory/$this_file") ) {
// Directory
$dirCount++;
$dirRep = str_replace("\\","/",$directory);
$link = str_replace("[link]", "$dirRep/" . urlencode($this_file), $return_link);
$link = str_replace("//","/",$link);
$restrictedFile=false;
for ($i=0;$i<count($restrictedFiles);$i++) {
if (strpos($link,$restrictedFiles[$i])!="") {
$restrictedFile=true;
}
}
$fileAtts = "";
if ($serverType=="Linux") {
$chmodInfo = substr(sprintf('%o', fileperms($link)), -3);
$fileAtts = '<span style="color: #888; font-size: 8px" id="'.str_replace("/","|",str_replace($docRoot,"",$link)).'_perms">'.$chmodInfo.'</span>';
}
if ($_SESSION['userLevel'] == 10 || ($_SESSION['userLevel'] < 10 && $restrictedFile==false)) {
$fileManager .= "<li class=\"pft-directory\"><a href=\"#\" onMouseOver=\"top.ICEcoder.overFileFolder('folder','$link')\" onMouseOut=\"top.ICEcoder.overFileFolder('folder','')\" style=\"position: relative; left:-22px\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span id=\"".str_replace("/","|",str_replace($docRoot,"",$link))."\">" . htmlspecialchars($this_file) . "</span> ".$fileAtts."</a>";
$fileManager .= fileManager_dir("$directory/$this_file", $return_link , false);
$fileManager .= "</li>";
} else {
$fileManager .= "<li class=\"pft-directory\" style=\"cursor: pointer\"><span style=\"position: relative; left:-22px; color: #888\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; [HIDDEN] ".$fileAtts."</span></li>";
}
} else {
// File
$fileCount++;
$fileBytes+=filesize($link);
// Get extension (prefix 'ext-' to prevent invalid classes from extensions that begin with numbers)
$ext = "ext-" . substr($this_file, strrpos($this_file, ".") + 1);
$dirRep = str_replace("\\","/",$directory);
$link = str_replace("[link]", "$dirRep/" . urlencode($this_file), $return_link);
$link = str_replace("//","/",$link);
$restrictedFile=false;
for ($i=0;$i<count($restrictedFiles);$i++) {
if (strpos($link,$restrictedFiles[$i])!="") {
$restrictedFile=true;
}
}
if ($_SESSION['userLevel'] == 10 || ($_SESSION['userLevel'] < 10 && $restrictedFile==false)) {
$fileAtts = "";
if ($serverType=="Linux") {
$chmodInfo = substr(sprintf('%o', fileperms($link)), -3);
$fileAtts = '<span style="color: #888; font-size: 8px" id="'.str_replace("/","|",str_replace($docRoot,"",$link)).'_perms">'.$chmodInfo.'</span>';
}
$fileManager .= "<li class=\"pft-file " . strtolower($ext) . "\"><a nohref onMouseOver=\"top.ICEcoder.overFileFolder('file','$link')\" onMouseOut=\"top.ICEcoder.overFileFolder('file','')\" style=\"position: relative; left:-22px; cursor: pointer\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span id=\"".str_replace("/","|",str_replace($docRoot,"",$link))."\">" . htmlspecialchars($this_file) . "</span> ".$fileAtts."</a></li>";
} else {
$fileAtts = "<img src=\"images/padlock.png\" style=\"cursor: pointer\" onClick=\"top.ICEcoder.message('Sorry, you need higher admin level rights to view.')\">";
$fileManager .= "<li class=\"pft-file " . strtolower($ext) . "\" style=\"cursor: default\"><span style=\"position: relative; left:-22px; color: #888\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; [HIDDEN] ".$fileAtts."</span></li>";
}
}
}
}
$fileManager .= "</ul>";
}
$varOutput = "";
if ($dirCount) {$varOutput .= "top.ICEcoder.dirCount+=".$dirCount.";".PHP_EOL;};
if ($fileCount) {$varOutput .= "top.ICEcoder.fileCount+=".$fileCount.";".PHP_EOL;};
if ($fileBytes) {$varOutput .= "top.ICEcoder.fileBytes+=".$fileBytes.";".PHP_EOL;};
// After outputting the fileManager, output the JS vars, but only the first time
return $fileManager."<script>if (top.ICEcoder.dirCount==0) {".PHP_EOL.$varOutput."}</script>";
}
// For PHP4 compatibility
function php4_scandir($dir) {
$dh = opendir($dir);
while( false !== ($filename = readdir($dh)) ) {
$files[] = $filename;
}
sort($files);
return($files);
}
?>
<!DOCTYPE html>
<html onMouseDown="top.ICEcoder.mouseDown=true" onMouseUp="top.ICEcoder.mouseDown=false" onMouseMove="top.ICEcoder.getMouseXY(event);top.ICEcoder.canResizeFilesW()" onContextMenu="top.ICEcoder.rightClickedFile=top.ICEcoder.thisFileFolderLink; return top.ICEcoder.showMenu()" onClick="top.ICEcoder.selectFileFolder()">
<head>
<title>ICE Coder File Manager</title>
<title>ICEcoder File Manager</title>
<link rel="stylesheet" type="text/css" href="lib/files.css">
<script src="lib/coder.js" type="text/javascript"></script>
</head>
<body onLoad="top.ICEcoder.fileManager()" onDblClick="top.ICEcoder.openFile()" onKeyDown="return top.ICEcoder.interceptKeys('files', event);" onKeyUp="top.ICEcoder.resetKeys(event);">
<div onClick="top.ICEcoder.refreshFileManager()" class="refresh"><img src="images/refresh.png"></div>
<script>
top.ICEcoder.dirCount = 0;
top.ICEcoder.fileCount = 0;
top.ICEcoder.fileBytes = 0;
</script>
<?php
<div class="refresh" onClick="top.ICEcoder.refreshFileManager()"><img src="images/refresh.png"></div>
echo fileManager($_SERVER['DOCUMENT_ROOT'], "[link]");
<?php
include("lib/settings.php");
$restrictedFiles = $_SESSION['restrictedFiles'];
$bannedFiles = $_SESSION['bannedFiles'];
strrpos($_SERVER['DOCUMENT_ROOT'],":") ? $serverType = "Windows" : $serverType = "Linux";
// Function to sort given values alphabetically
function alphasort($a, $b) {
return strcasecmp($a->getPathname(), $b->getPathname());
}
// Class to put forward the values for sorting
class SortingIterator implements IteratorAggregate {
private $iterator = null;
public function __construct(Traversable $iterator, $callback) {
$array = iterator_to_array($iterator);
usort($array, $callback);
$this->iterator = new ArrayIterator($array);
}
public function getIterator() {
return $this->iterator;
}
}
// Get a full list of dirs & files and begin sorting using above class & function
$path = $_SERVER['DOCUMENT_ROOT'];
$objectList = new SortingIterator(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST), 'alphasort');
// With that done, create arrays for out final ordered list and a temp container of files
$finalArray = $tempArray = array();
// To start, push folders from object into finalArray, files into tempArray
foreach ($objectList as $objectRef) {
$fileFolderName = rtrim(substr($objectRef->getPathname(), strlen($path)),"..");
$canAdd = true;
for ($i=0;$i<count($bannedFiles);$i++) {
if(strpos($fileFolderName,$bannedFiles[$i])!==false) {$canAdd = false;}
}
if ($objectRef->getFilename()!="." && $fileFolderName[strlen($fileFolderName)-1]!="/" && $canAdd) {
$fileFolderName!="/" && is_dir($path.$fileFolderName) ? array_push($finalArray,$fileFolderName) : array_push($tempArray,$fileFolderName);
}
}
// Now push root files onto the end of finalArray and splice from the temp, leaving only files that reside in subdirs
for ($i=0;$i<count($tempArray);$i++) {
if (count(explode("/",$tempArray[$i]))==2) {
array_push($finalArray,$tempArray[$i]);
array_splice($tempArray,$i,1);
$i--;
}
}
// Lastly we push remaining files into the right subdirs in finalArray
for ($i=0;$i<count($tempArray);$i++) {
$insertAt = array_search(dirname($tempArray[$i]),$finalArray)+1;
for ($j=$insertAt;$j<count($finalArray);$j++) {
if ( strcasecmp(dirname($finalArray[$j]), dirname($tempArray[$i]))==0 &&
strcasecmp(basename($finalArray[$j]), basename($tempArray[$i]))<0 ||
strstr(dirname($finalArray[$j]),dirname($tempArray[$i]))) {
$insertAt++;
}
}
array_splice($finalArray, $insertAt, 0, $tempArray[$i]);
}
// Finally, we have our ordered list, so display in a UL
$fileAtts = "";
if ($serverType=="Linux") {
$chmodInfo = substr(sprintf('%o', fileperms($path)), -3);
$fileAtts = '<span style="color: #888; font-size: 8px" id="|_perms">'.$chmodInfo.'</span>';
}
echo "<ul class=\"fileManager\">\n<li class=\"pft-directory\"><a href=\"#\" onMouseOver=\"top.ICEcoder.overFileFolder('folder','$path/')\" onMouseOut=\"top.ICEcoder.overFileFolder('folder','')\" style=\"position: relative; left:-22px\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span id=\"|\">/ [ROOT]</span> ".$fileAtts."</a></li>\n";
$lastPath="";
for ($i=0;$i<count($finalArray);$i++) {
$fileFolderName = str_replace("\\","/",$finalArray[$i]);
is_dir($path.$fileFolderName) ? $type="folder" : $type="file";
$type=="folder" ? $dirCount++ : $fileCount++;
if (!is_dir($path.$fileFolderName)) {
$fileBytes+=filesize($path.$fileFolderName);
// Get extension (prefix 'ext-' to prevent invalid classes from extensions that begin with numbers)
$ext = "ext-".pathinfo($path.$fileFolderName, PATHINFO_EXTENSION);
}
$thisDepth = count(explode("/",$fileFolderName));
$lastDepth = count(explode("/",$lastPath));
if ($thisDepth > $lastDepth) {echo "<ul>\n";}
if ($thisDepth < $lastDepth) {
for ($j=$lastDepth;$j>$thisDepth;$j--) {
echo "</ul>\n";
}
}
$restrictedFile=false;
for ($j=0;$j<count($restrictedFiles);$j++) {
if (strpos($fileFolderName,$restrictedFiles[$j])!="") {
$restrictedFile=true;
}
}
if ($serverType=="Linux") {
$chmodInfo = substr(sprintf('%o', fileperms($path.$fileFolderName)), -3);
$fileAtts = '<span style="color: #888; font-size: 8px" id="'.str_replace("/","|",$fileFolderName).'_perms">'.$chmodInfo.'</span>';
}
$type == "folder" ? $class = 'pft-directory' : $class = 'pft-file '.strtolower($ext);
if ($_SESSION['userLevel'] == 10 || ($_SESSION['userLevel'] < 10 && !$restrictedFile)) {
echo "<li class=\"".$class."\"><a href=\"#\" onMouseOver=\"top.ICEcoder.overFileFolder('$type','$path$fileFolderName')\" onMouseOut=\"top.ICEcoder.overFileFolder('$type','')\" style=\"position: relative; left:-22px\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span id=\"".str_replace("/","|",$fileFolderName)."\">".basename($fileFolderName)."</span> ".$fileAtts."</a>\n";
} else {
if ($type == "file") {$fileAtts = "<img src=\"images/padlock.png\" style=\"cursor: pointer\" onClick=\"top.ICEcoder.message('Sorry, you need higher admin level rights to view.')\">";}
echo "<li class=\"".$class."\" style=\"cursor: default\"><span style=\"position: relative; left:-22px; color: #888\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; [HIDDEN] ".$fileAtts."</span>\n";
}
if ($i<count($finalArray)) {echo "</li>\n";}
$lastPath = $fileFolderName;
}
echo "</ul>\n</ul>\n";
echo "<script>\n";
$varOutput = "top.ICEcoder.dirCount=";
$dirCount ? $varOutput .= $dirCount.";\n" : "0;\n";
$varOutput .= "top.ICEcoder.fileCount=";
$fileCount ? $varOutput .= $fileCount.";\n" : "0;\n";
$varOutput .= "top.ICEcoder.fileBytes=";
$fileBytes ? $varOutput .= $fileBytes.";\n" : "0;\n";
// Output the JS vars
echo $varOutput;
echo "</script>\n";
?>
<iframe name="fileControl" style="display: none"></iframe>