<?php
ob_start();
session_start();
// File Browser, v 1.0 beta 2009/09/09 12:40:20 dries Exp $
// Author, sudhir vishwakarma
/**
* @file
* The File Browser system, which controls the file Manupulation.
*
* License
* GNU General Public License version 3 (GPLv3)
*
File Browser (C) 2009 sudhir vishwakarma
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/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
File Browser (C) 2009 sudhir vishwakarma
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an about box.
You should also get your employer (if you work as a programmer) or school, if any, to sign a copyright disclaimer for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/
date_default_timezone_set('Asia/Calcutta');
class Utils {
const cUsername = "admin";
const cPassword = "password";
public $separator, $sMessage = 0, $sError = 0;
private $aPlainText = array('as','asp','aspx','atom','bat','cfm','cmd','hta','htm','html','js','jsp','java','mht','php','pl','py','rb','rss','sh','txt','xhtml','xml','log','out','ini','shtml','xsl','xslt','backup');
private $aImageType = array('bm','bmp','ras','rast','fif','flo','turbot','g3','gif','ief','iefs','jfif','jfif-tbnl','jpe','jpeg','jpg','jut','nap','naplps','pic','pict','jfif','jpe','jpeg','jpg','png','x-png','tif','tiff','mcf','dwg','dxf','svf','fpx','fpx','rf','rp','wbmp','xif','xbm','ras','dwg','dxf','svf','ico','art','jps','nif','niff','pcx','pct','xpm','pnm','pbm','pgm','pgm','ppm','qif','qti','qtif','rgb','tif','tiff','bmp','xbm','xbm','pm','xpm','xwd','xwd');
function __construct($bAuth){
if ($bAuth) {
if ($_POST['button'] == 'Login') {
if (($_POST['username'] == self::cUsername) && ($_POST['password'] == self::cPassword)) {
$_SESSION['auth'] = "1";
}else{
$_SESSION['auth'] = "0";
}
}
if (!$_SESSION['auth']) {
$sHtml = "<form method=\"post\">
<table style=\"background-color:#ffffff; padding: 1em; border:1px solid #000000;\" border=\"0\" cellpadding=\"0\" cellspacing=\"2\" width=\"200\" align=\"center\">
<tr>
<td style=\"background-color:#F1F1F1\" colspan=\"2\">Login</td>
</tr>
<tr>
<td>Username</td>
<td><input type=\"text\" name=\"username\" id=\"username\"/></td>
</tr>
<tr>
<td>Password</td>
<td><input type=\"password\" name=\"password\" id=\"password\"/></td>
</tr>
<tr>
<td></td>
<td><input type=\"submit\" name=\"button\" id=\"button\" value=\"Login\"/></td>
</tr>
</table>
</form>";
echo $sHtml;
die();
}
}
if (strtoupper(substr(PHP_OS, 0, 3) == 'WIN')) {
$this->separator = "\\";
} else {
$this->separator = "/";
}
}
public function downloadFile($file){
header ("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header('Content-Description: File Transfer');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: attachment; filename=' . basename($file));
header('Content-Type: application/octet-stream');
readfile($file);
}
public function fileName($file, $dir){
if (filetype($dir.$file) != "dir") {
$sLink = "<a onmousedown=\"dis()\" href=\"browser.php?view=".$dir.$file."\">$file</a>";
}else{
$aCurrentPath = explode($this->separator, $dir);
$iCount = (count($aCurrentPath) -2);
for ($i = 0; $i < $iCount; ++$i) {
$sFullPath .= $aCurrentPath[$i].$this->separator;
}
if ($file == '.') {
$sLink = "<a onmousedown=\"dis()\" href=\"browser.php?dir=".$this->separator."\">[ ".$this->separator." ]</a>";
}elseif ($file == '..') {
$sLink = "<a onmousedown=\"dis()\" href=\"browser.php?dir=".$sFullPath."\">[ ".$this->separator." ".$this->separator." ]</a>";
}
else{
$sLink = "<a onmousedown=\"dis()\" href=\"browser.php?dir=".$dir.$file."\">$file</a>";
}
}
return $sLink;
}
public function showDownload($file, $dir = ""){
if (filetype($dir.$file) != "dir") {
return "<a onmousedown=\"dis()\" href=\"browser.php?dwl=$dir$file\">Download</a>";
}else{
return '';
}
}
public function showEdit($file, $dir){
if (filetype($dir.$file) != "dir") {
$sExt = strtolower(substr(strrchr($file,'.'),1));
if ($sExt == 'zip') {
$sLink = "<a onmousedown=\"dis()\" href=\"browser.php?extract=$dir$file\">Unpack</a>";
}else{
$sLink = "<a onmousedown=\"dis()\" href=\"browser.php?edit=$dir$file\" target=\"_new\">Edit</a>";
}
}
return $sLink;
}
public function showFileSize($file, $dir, $precision = 2) {
if (filetype($dir.$file) != "dir") {
return $this->formatSize(filesize($dir.$file));
}else{
return "Dir";
}
}
private function formatSize($bytes, $precision = 2) {
$units = array('B', 'KB', 'MB', 'GB', 'TB');
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= pow(1024, $pow);
return round($bytes, $precision) . ' ' . $units[$pow];
}
public function dateFormat($iTimestamp) {
return date("F j, Y, g:i a", $iTimestamp);
}
public function delete_directory($dirname) {
if (is_dir($dirname))
$dir_handle = opendir($dirname);
if (!$dir_handle)
return false;
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file))
if (@unlink($dirname."/".$file)) {
$this->sMessage = "Directory Deleted Successfully: \"".$dirname."\" .";
}else{
$this->sError = "Can't Deleted Directory \"".$dirname."\" .";
}
else
$this->delete_directory($dirname.'/'.$file);
}
}
closedir($dir_handle);
rmdir($dirname);
return true;
}
public function viewFile($file){
$sBaseName = basename($file);
$sExt = strtolower(substr(strrchr($sBaseName,'.'),1));
if ($sExt == "zip") {
$oZip = new ZipArchive;
if ($oZip->open($file) === TRUE) {
echo "<table cellspacing=\"1px\" cellpadding=\"0px\">";
echo "<tr><th>Name</th><th>Uncompressed size</th><th>Compressed size</th><th>Compr. ratio</th><th>Date</th></tr>";
for ($i=0; $i<$oZip->numFiles;$i++) {
$aZipDtls = $oZip->statIndex($i);
$iPercent = round($aZipDtls['comp_size'] * 100 / $aZipDtls['size']);
$iUncompressedSize = $aZipDtls['size'];
$iCompressedSize = $aZipDtls['comp_size'];
$iTotalPercent += $iPercent;
echo "<tr><td>".$aZipDtls['name']."</td><td>".$this->formatSize($iUncompressedSize)."</td><td>".formatSize($iCompressedSize)."</td><td>".$iPercent."%</td><td>".dateFormat($aZipDtls['mtime'])."</td></tr>";
}
echo "</table>";
echo "<p align=\"center\"><b>".$this->showFileSize($file, $dir)." in ".$oZip->numFiles." files in ".basename($oZip->filename).". Compression ratio: ".round($iTotalPercent / $oZip->numFiles)."%</b></p>";
$oZip->close();
} else {
echo 'failed';
}
}elseif (in_array($sExt, $this->aPlainText)) {
header ("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header('Content-Description: File View');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: inline; filename=' . basename($file));
header('Content-Type: text/plain');
readfile($file);
}elseif(in_array($sExt, $this->aImageType)){
header ("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header('Content-Description: File View');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: inline; filename=' . basename($file));
header('Content-Type: image/jpg');
readfile($file);
}else{
$this->downloadFile($file);
}
}
public function deleteFiles($aFiles){
if (is_array($aFiles)) {
foreach ($aFiles as $aFilesNames){
if (is_dir($dir.$aFilesNames)) {
$this->delete_directory($dir.$aFilesNames);
}else{
if (@unlink($dir.$aFilesNames)) {
$this->sMessage = "File Deleted Successfully: \"".$dir.$aFilesNames."\" .";
}else{
$this->sError = "Can't Deleted file \"".$dir.$aFilesNames."\" .";
}
}
}
}
}
public function createFile($dir, $sCreatefile){
if (!file_exists($dir.$sCreatefile)) {
if (is_writable($dir)) {
$handle = fopen($dir.$sCreatefile, "w");
fclose($handle);
$this->sMessage = "File Created Successfully: \"$sCreatefile\" .";
}else{
$this->sError = "Directory Not Writable, Can't Create file.";
}
}else{
$this->sError = " \"$sCreatefile\" File already exist.";
}
}
private function writeBackup($sFileName){
if (!copy($sFileName, $sFileName.".backup")) {
return false;
}
return true;
}
public function fileWriter($sFile, $string, $backup = false) {
if ($backup) {
$this->writeBackup($sFile);
}
$fp = fopen($sFile,"w");
//Writing to a network stream may end before the whole string is written. Return value of fwrite() is checked
for ($written = 0; $written < strlen($string); $written += $fwrite) {
$fwrite = fwrite($fp, substr($string, $written));
if (!$fwrite) {
return $fwrite;
}
}
fclose($fp);
return $written;
}
public function createDirectory($dir, $sCreatefile){
if (!is_dir($dir.$sCreatefile)) {
mkdir($dir.$sCreatefile, 0755);
$this->sMessage = "Directory Created Successfully: \"$dir\" .";
}else{
$this->sError = "\"$dir\" Directory already exist.";
}
}
public function extract($sExtract){
$zip = new ZipArchive;
$path_parts = pathinfo($sExtract);
if ($zip->open($sExtract) === TRUE) {
$zip->extractTo($path_parts['dirname']);
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
}
public function uploadFile($dir, $sFileName){
if (move_uploaded_file($_FILES['myfile']['tmp_name'], $dir.$sFileName)) {
$this->sMessage = "\"$sFileName\" File Successfully Uploaded.";
}else{
$this->sError = "\"$sFileName\" Uploading Error.";
}
}
public function getCurrentDir($dir){
$aCurrentPath = explode($this->separator, $dir);
$iCount = (count($aCurrentPath) -1);
for ($i = 0; $i < $iCount; ++$i) {
$sFullPath .= $aCurrentPath[$i].$this->separator;
echo "<a href=\"browser.php?dir=".urlencode($sFullPath)."\"><strong>".$aCurrentPath[$i]."<strong></a>".$this->separator;
}
}
}
// End of Utils Class
$oUtils = new Utils(true);
$dir = trim($_REQUEST['dir']);
$sEdit = trim($_REQUEST['edit']);
$sExtract = trim($_REQUEST['extract']);
$sViewFile = trim($_REQUEST['view']);
if (!$dir) {
$dir = getcwd().$oUtils->separator;
}else{
$dir = trim($_REQUEST['dir']).$oUtils->separator;
}
$dir = str_replace($oUtils->separator.$oUtils->separator, $oUtils->separator, $dir);
if ($_POST['button'] == "Delete Selected Files") {
$aFiles = $_POST['chkfiles'];
$oUtils->deleteFiles($aFiles);
}
if ($_POST['button'] == "Create File") {
$sCreatefile = trim($_POST['createfile']);
$oUtils->createFile($dir, $sCreatefile);
}
if ($_POST['button'] == "Create Directory") {
$oUtils->createDirectory($dir, trim($_POST['createfile']));
}
$sDownloadFile = trim($_REQUEST['dwl']);
if ($sDownloadFile) {
$oUtils->downloadFile($sDownloadFile);
exit;
}
if ($sExtract != "") {
$oUtils->extract($sExtract);
}
if ($_POST['button'] == 'SAVEFILE') {
$bBackup = trim($_POST['Write_backup']);
$sFileData = trim($_POST['editfile']);
$oUtils->fileWriter($sEdit, $sFileData, $bBackup);
}
$sFileName = $_FILES['myfile']['name'];
if ($sFileName) {
$oUtils->uploadFile($dir, $sFileName);
}
if ($sViewFile) {
$oUtils->viewFile($sViewFile);
exit;
}
$sFiles = scandir(urldecode($dir));
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<meta name="robots" content="noindex">
<meta http-equiv="expires" content="0">
<meta http-equiv="pragma" content="no-cache">
<style type="text/css">
body {font-family:sans-serif; font-size: 10pt; color: #000000;}
input {background-color: #efefef; color: #000000;}
.border {margin: 1px; background-color:#ffffff; padding: 1em; border:1px solid #000000;}
a {text-decoration:none; }
a:hover { color : red; text-decoration : underline; }
table.filelisting {background-color:#000000; width:100%; border:0px none #ffffff;}
th {background-color:#f1f1f1;}
td{background-color:#ffffff;padding-left:5px;font-family:sans-serif; font-size: 9pt; color: #000000;}
.message{border: 1px solid #ffaaaa;background-color: #acffaa;padding:3px 3px 3px 5px;font-size: 9pt;color:#000;text-align:center;}
.error{border: 1px solid #acffaa;background-color: #ffaaaa;padding:3px 3px 3px 5px;font-size: 10pt;color:#000;text-align:center;}
</style>
<script type="text/javascript">
function filter (begriff) {
var suche = begriff.value.toLowerCase();
var table = document.getElementById("filetable");
var ele;
for(var r = 1; r < table.rows.length; r++) {
ele = table.rows[r].cells[1].innerHTML.replace(/<[^>]+>/g,"");
if(ele.toLowerCase().indexOf(suche)>=0 )
table.rows[r].style.display = '';
else table.rows[r].style.display = 'none';
}
}
function selectAll(obj) {
var oFileList = obj.elements['chkfiles[]'];
for(i=0; i < oFileList.length; ++i) {
if(obj.selall.checked == true)
oFileList[i].checked = true;
else
oFileList[i].checked = false;
}
}
</script>
<title>File Browser V. 1.0a</title>
</head>
<body>
<?php
if ($oUtils->sError) {
echo "<p class=\"error\">".$oUtils->sError."</p>";
}
if ($oUtils->sMessage) {
echo "<p class=\"message\">".$oUtils->sMessage."</p>";
}
?>
<?php
if ($_GET['cmd'] == 'ssh') {
$sSsh_command = trim($_POST['ssh_command']);
if ($sSsh_command) {
$aResult = array();
exec($sSsh_command, $aResult);
}
?>
<div>
<div>
<form name="frmSsh" method="post">
Command: <input type="text" value="<?php echo stripslashes($_POST['ssh'])?>" name="ssh_command" size="70"><input type="submit" value="GO"/>
</form>
</div>
<br/>
<div>
<?php
if (is_array($aResult)) {
foreach ($aResult as $resultVal){
echo $resultVal."<br/>";
}
}
?>
</div>
</div>
<?php
}
elseif($sEdit != "") {
$handle = fopen($sEdit, "r");
if ($handle) {
while (!feof($handle)) {
$contents = fgets($handle, 4096);
}
fclose($handle);
}
?>
<div>
<div class="border">
<form name="frmedit" method="post">
<p>
<strong>File Name: <?php echo basename($sEdit)?></strong>
</p>
<textarea name="editfile" style="height:400px;width:100%"><?php echo $contents?></textarea>
<p>
<input type="text" name="button" value="SAVEFILE" style="display:none"/>
<input type="checkbox" name="Write_backup" value="1" id="Write_backup" title="Write backup"/>
<label for="Write_backup">
<strong>Write backup</strong>
</label>
<br/>
</p>
<p>
<input type="submit" value="SAVE"/>
</p>
</form>
</div>
</div>
<?php }else{?>
<div>
<div class="border">
<form action="browser.php" method="POST" enctype="multipart/form-data">
<p>
<input type="text" name="dir" value="<?php echo $dir;?>" style="display:none"/>
<input type="file" onKeypress="event.cancelBubble=true;" name="myfile">
<input title="Upload selected file to the current working directory" type="Submit" name="Submit" value="Upload"/>
</p>
<p>
<input type="button" name="button" value="Launch Shell Program" onclick="window.location = 'browser.php?cmd=ssh'">
</p>
</form>
</div>
<br/>
<form action="browser.php" method="Post" name="filelist" class="border">
Filename filter:
<input name="filt" onKeypress="event.cancelBubble=true;" onkeyup="filter(this)" type="text">
<br />
<br />
<table id="filetable" border="0" cellpadding="0px" cellspacing="1px" width="100%" class="filelisting">
<tr >
<th></th>
<th>Name</th>
<th>Size</th>
<th>Type</th>
<th>Date</th>
<th> </th>
<th> </th>
</tr>
<?php
if (is_array($sFiles)) {
foreach ($sFiles as $file){
//if ($file != "." && $file != "..") {
?>
<tr >
<td>
<?php if ($file != "." && $file != "..") {?><input type="checkbox" id="chkfiles[]" name="chkfiles[]" value="<?php echo $file?>"/><?php } ?>
</td>
<td><?php echo $oUtils->fileName($file, $dir);?></td>
<td><?php echo $oUtils->showFileSize($file, $dir);?></td>
<td><?php echo substr(strrchr($dir.$file,'.'),1);?></td>
<td><?php $aFileInfo = stat($dir.$file); echo $oUtils->dateFormat($aFileInfo['atime'])?></td>
<td><?php echo $oUtils->showDownload($file, $dir);?></td>
<td><?php echo $oUtils->showEdit($file, $dir);?></td>
</tr>
<?php } } ?>
<tr >
<td colspan="7">
<input type="checkbox" id="selall" name="selall" onClick="selectAll(this.form)">
<label for="selall">
Select All
</label>
</td>
</tr>
</table>
<br/>
<p>
<input type="text" name="dir" value="<?php echo $dir;?>" style="display:none"/>
<input title="Delete selected files and directories." type="Submit" onclick="return confirm('Are you sure want to delete selected files');" name="button" value="Delete Selected Files">
<!--input title="Download selected files and directories as one zip file" id="but_Zip" type="Submit" name="Submit" value="Download selected files as zip"-->
</p>
<p>
Current Location: <?php echo $oUtils->getCurrentDir($dir); ?>
</p>
<p>
<input type="text" name="createfile">
<input title="Create directory." type="Submit" name="button" value="Create Directory">
<input title="Create File." type="Submit" name="button" value="Create File">
</p>
</form>
</div>
<?php }?>
</body>
</html>