<?php
/** 
 * 程序说明
 * @package   Drawer
 * @author     Joytou, Pzy
 * @copyright  Copyright (c) 2019
 * @version    1.0.1.1(Release)
 *
 * 设置说明
 * $sitetitle - 标题名称
 * $username - 用户名
 * $password - 密码
 * $timezone - 默认时区
 * $open_basedir - 限制可访问目录。为空字符串即不限制，建议设置为__DIR__，仅可以访问当前目录和子目录。
 * $safe_num - 限制最多可尝试登录次数，为0则不限制，建议设置为3-5
 * $logable - 进行日志记录。true则记录操作日志，false则不记录。日志记录保存在与文件管理器文件同名的.log文件中。例如：filebox.php.log
 */
$sitetitle = "Drawer";
$username = "admin";
$password = "admin";
$timezone = "Asia/Shanghai";
$open_basedir = __DIR__;
$safe_num = 3;
$logable = false;

if( !headers_sent() && // 如果页面头部信息还没有输出
extension_loaded("zlib") && // 而且php已经加载了zlib扩展
strstr($_SERVER["HTTP_ACCEPT_ENCODING"],"gzip")) //而且浏览器接受GZIP
{
	ini_set('zlib.output_compression', 'On');
	ini_set('zlib.output_compression_level', '4');
}
header( 'Content-Type: text/html; charset=utf-8' );
date_default_timezone_set( $timezone ); //设置默认时区
ini_set( 'open_basedir', $open_basedir ); //限制可访问目录，避免恶意修改
define( 'php_self', substr( $_SERVER[ 'PHP_SELF' ], strrpos( $_SERVER[ 'PHP_SELF' ], '/' ) + 1 ) ); //获取文件管理器文件名
session_start();

$version = '1.0.1.1';
$dir = ( isset( $_POST[ 'dir' ] ) && $_POST[ 'dir' ] != '' ) ? $_POST[ 'dir' ] : '.'; //获取当前目录
$dir = htmlspecialchars( $dir );
$dir = dircode( $dir );
$opendfile = ( isset( $_POST[ 'file' ] ) && $_POST[ 'file' ] != '' ) ? $_POST[ 'file' ] : ''; //获取当前打开的文件
$opendfile = htmlspecialchars( $opendfile );
$operate = ( isset( $_POST[ 'op' ] ) && $_POST[ 'op' ] != '' ) ? $_POST[ 'op' ] : ''; //获取要进行的文件夹或文件操作
$extradata = ( isset( $_REQUEST[ 'data' ] ) && $_REQUEST[ 'data' ] != '' ) ? $_REQUEST[ 'data' ] : ''; //获取额外的数据，内容视具体操作而定
$_SESSION[ 'order' ] = ( isset( $_POST[ 'order' ] ) && $_POST[ 'order' ] != '' ) ? $_POST[ 'order' ] : ( isset( $_SESSION[ 'order' ] ) ? $_SESSION[ 'order' ] : '' ); //获取排序字段名
$_SESSION[ 'sort' ] = ( isset( $_POST[ 'sort' ] ) && $_POST[ 'sort' ] != '' ) ? $_POST[ 'sort' ] : ( isset( $_SESSION[ 'sort' ] ) ? $_SESSION[ 'sort' ] : '' ); //获取排序方式
$showNavbar = false; //是否展示导航栏
$isWindows = DIRECTORY_SEPARATOR == '\\';
$msg = "";

/**
 * 错误处理函数
 *
 * @access public
 * @param integer $errno 错误的级别
 * @param string $errstr 错误的信息
 * @param string $errfile 发生错误的文件名
 * @param integer $errline 错误发生的行号
 * @return boolean
 */
function myErrorHandler( $errno, $errstr, $errfile, $errline ) {
	$log_file = "./php_%s_log_" . date( "Ymd" ) . ".log"; //定义日志文件存放目录和文件名  
	$template = '';
	switch ( $errno ) {
		case E_USER_ERROR:
			$template .= "用户ERROR级错误，必须修复 错误编号[$errno] $errstr ";
			$template .= "错误位置 文件$errfile,第 $errline 行\n";
			$log_file = sprintf( $log_file, 'error' );
			exit( 1 ); //系统退出  
			break;
		case E_USER_WARNING:
			$template .= "用户WARNING级错误，建议修复 错误编号[$errno] $errstr ";
			$template .= "错误位置 文件$errfile,第 $errline 行\n";
			$log_file = sprintf( $log_file, 'warning' );
			break;
		case E_USER_NOTICE:
			$template .= "用户NOTICE级错误，不影响系统，可不修复 错误编号[$errno] $errstr ";
			$template .= "错误位置 文件$errfile,第 $errline 行\n";
			$log_file = sprintf( $log_file, 'notice' );
			break;
		default:
			$template .= "未知错误类型: 错误编号[$errno] $errstr  ";
			$template .= "错误位置 文件$errfile,第 $errline 行\n";
			$log_file = sprintf( $log_file, 'unknown' );
			break;
	}
	//    file_put_contents($log_file,$template,FILE_APPEND);  
	return true;
}
$error_handler = set_error_handler( "myErrorHandler" ); //开启自定义错误日志  

/**
 * 将字符串进行UTF-8编码，并返回编码后的字符串以及原字符串的字符集
 *
 * @access public
 * @param string $str 要编码的字符串
 * @return array(["code"], ["string"])
 */
function encode( $str ) {
	$arr = array();
	if ( function_exists( 'mb_detect_encoding' ) )
		$encode = mb_detect_encoding( $str, array( 'ASCII', 'UTF-8', 'GB2312', 'GBK', 'BIG5' ) );
	else
		$encode = 'UTF-8';
	switch ( $encode ) {
		case 'EUC-CN':
			$encode = 'GB2312';
			break;
		case 'CP936':
			$encode = 'GBK';
			break;
	}
	$arr[ "string" ] = mb_convert_encoding( $str, 'utf-8', $encode );
	$arr[ "code" ] = $encode;
	return $arr;
}

/**
 * 将已按照UTF-8编码的字符串进行解码
 *
 * @access public
 * @param string $str 需要解码的字符串
 * @param string $code 字符串默认的字符集
 * @return string
 */
function decode( $str, $code ) {
	return mb_convert_encoding( $str, $code, 'utf-8' );
}

/**
 * 将url地址的特殊符号进行编码
 *
 * @access public
 * @param string $str url地址
 * @return string
 */
function urlcode( $str ) //对URL特殊符号进行编码
{
	$arr_find = array( '+', ' ', '?', '%', '#', '&', '=' );
	$arr_replace = array( '%2B', '%20', '%3F', '%25', '%23', '%26', '%3D' );
	return str_replace( $arr_find, $arr_replace, $str );
}

/**
 * dir路径去除末端"/"符号和"%2F"
 *
 * @access public
 * @param string $dir dir路径
 * @return string
 */
function dircode( $dir ) {
	$rdir = $dir;
	while ( ( substr( $rdir, -1 ) == '/' ) || ( substr( $rdir, -3 ) == '%2F' ) ) {
		if ( substr( $rdir, -1 ) == '/' ) {
			$rdir = substr( $rdir, 0, strlen( $rdir ) - 1 );
		}
		if ( substr( $rdir, -3 ) == '%2F' ) {
			$rdir = substr( $rdir, 0, strlen( $rdir ) - 3 );
		}
	}
	return $rdir;
}

/**
 * 页面头部
 *
 * @access public
 * @global string $sitetitle 页面标题
 * @global string $showNavbar 是否展示导航栏
 */
function maintop() {
	global $sitetitle, $showNavbar;
	$logo = 'data:image/png;base64, ';
	$bg = 'data:image/jpeg;base64, ';
	echo '<!DOCTYPE html>'
		. '<html>'
	. '<head>'
	. "<title>$sitetitle</title>"
	. '<meta name="viewport" content="width=device-width, initial-scale=1.0">'
	. '<!-- 引入 Bootstrap -->'
	. '<link href="./css/bootstrap.min.css" rel="stylesheet">'
	. '<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->'
	. '<link href="./css/ie10-viewport-bug-workaround.css" rel="stylesheet">'
	. '<link rel="stylesheet" href="./css/font-awesome.min.css">'
	. '<!-- Just for debugging purposes. Don\'t actually copy these 2 lines! -->'
	. '<!--[if lt IE 9]><script src="./js/ie8-responsive-file-warning.js"></script><![endif]-->'
	. '<script src="./js/ie-emulation-modes-warning.js"></script>'
	. '<!-- HTML5 Shiv 和 Respond.js 用于让 IE8 支持 HTML5元素和媒体查询 -->'
	. '<!-- 注意： 如果通过 file://  引入 Respond.js 文件，则该文件无法起效果 -->'
	. '<!--[if lt IE 9]>'
	. '<script src="./js/html5shiv.js"></script>'
	. '<script src="./js/respond.min.js"></script>'
	. '<![endif]-->'
	. '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />'
	. '<!-- jQuery (Bootstrap 的 JavaScript 插件需要引入 jQuery) -->'
	. '<script src="./js/jquery.min.js"></script>'
	. '<!-- 包括所有已编译的插件 -->'
	. '<script src="./js/bootstrap.min.js"></script>'
	. '<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->'
	. '<script src="./js/ie10-viewport-bug-workaround.js"></script>'
	. '<style type="text/css">';
	echo 'body{';
	if ( $showNavbar ): echo 'background-color:#eee;padding-right:4px;';
	else :echo 'background:url("' . $bg . '") 0 0 no-repeat;background-size:cover;';
	endif;
	echo '}'
	.'.form-signin{max-width:330px;padding:15px;margin:0 auto}'
	.'.form-signin .checkbox,.form-signin .form-signin-heading{margin-bottom:10px}'
	.'.form-signin .checkbox{font-weight:400}'
	.'.form-signin .form-control{position:relative;height:auto;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:10px;font-size:16px}'
	.'.form-signin .form-control:focus{z-index:2}'
	.'.form-signin input[type=email]{margin-bottom:-1px;border-bottom-right-radius:0;border-bottom-left-radius:0}'
	.'.form-signin input[type=password]{margin-bottom:10px;border-top-left-radius:0;border-top-right-radius:0}'
	.'.blog-footer{padding:40px 0;color:#999;text-align:center;background-color:#f9f9f9;border-top:1px solid #e5e5e5;}'
	.'.blog-footer p:last-child{margin-bottom:0;}'
	.'thead>tr>th>a:link,thead>tr>th>a:hover,thead>tr>th>a:active{color:#000;text-decoration:none;}'
	.'tr.active td{background-color:#ccc!important;}'
	.'.btn-group.operate{position:fixed;left:35%;bottom:1%;}'
	.'@media screen and (max-width:425px){.btn-group.operate{left:0%;}}'
	.'@media screen and (max-width:320px){.btn-group.operate{}#filetable.table>tbody>tr>td, #filetable.table>tbody>tr>th, #filetable.table>tfoot>tr>td, #filetable.table>tfoot>tr>th, #filetable.table>thead>tr>td, #filetable.table>thead>tr>th{padding-left:0;padding-right:0;}}'
	.'div.page-header.text-center span{display:inline-block;height:39px;width:45px;background:url("' . $logo . '");background-repeat:no-repeat;background-size:contain;}'
	.'div.page-header.text-center h1{display:inline;}'
	.'table#filetable td:nth-child(1){word-break:break-all;width:0;}'
	.'</style>'
	. '</head>'
	. '<body>';
	if ( $showNavbar == true ) {
		echo '<nav class="navbar navbar-default" role="navigation">'
		. '<div class="container-fluid">'
		. '<div class="navbar-header">'
		. '<a class="navbar-brand" href="' . php_self . '" onclick="return false;">' . $sitetitle . '</a>'
		. '</div>'
		. '<div>'
		. '<ul class="nav navbar-nav">'
		. '<li class="active"><a href="javascript:void(0);" onclick="opendir(\'.\')"><i class="fa fa-home"></i>主页</a></li>'
		. '<li><a href="javascript:void(0);" onClick="fcreate()"><i class="fa fa-file"></i>新建文件</a></li>'
		. '<li><a href="javascript:void(0);" onClick="fupload()"><i class="fa fa-upload"></i>上传文件</a></li>'
		. '<li><a href="javascript:void(0);" onClick="fremotedownload()"><i class="fa fa-cloud-download"></i>远程下载</a></li>'
		. '<li><a href="javascript:void(0);" onClick="checkVersion()"><i class="fa fa-info-circle"></i>检查更新</a></li>'
		. '<li><a href="javascript:void(0);" onClick="logout()"><i class="fa fa-sign-out"></i>注销</a></li>'
		. '</ul>'
		. '</div>'
		. '</div>'
		. '</nav>';
	}
	echo '<div class="container">'
	. '<div class="page-header text-center">'
	. "<span></span><h1>$sitetitle</h1>"
	. '</div>';
}

/**
 * 页面尾部
 *
 * @access public
 */
function mainbottom() {
	echo '</div>'
	. '<div id="paddingDiv"></div>'
	. '<footer class="blog-footer">'
	. '<p>&copy; 2019 Joytou</p>'
	. '<p>Designed by Pzy</p>'
	. '</footer>'
	. '<script>if($("body").height()<$(window).height()){$("div#paddingDiv").height($(window).height()-$("body").height());}</script>'
	. '</body>'
	. '</html>';
}

/**
 * 规范字符串格式
 *
 * @access public
 * @param string $data 需要规范格式的字符串
 * @return string
 */
function test_input( $data ) {
	$data = trim( $data );
	$data = stripslashes( $data );
	$data = htmlspecialchars( $data );
	return $data;
}

/**
 * 输出日志
 *
 * @access public
 * @param string $log 日志信息
 * @global string $logable 是否输出日志
 */
function writelog( $log ) {
	global $logable;
	if ( $logable ) {
		$myfile = fopen( php_self . ".log", "a" );
		fwrite( $myfile, date( "Y-m-d h:i:s" ) . "	" . "IP地址：" . $_SERVER[ 'REMOTE_ADDR' ] . "	" . $log . "\r\n" );
		fclose( $myfile );
	}
}

/**
 * 计算文件大小
 *
 * @access public
 * @param string $file 要计算大小的文件名
 * @return string
 */
function getSize( $file ) {
	$num = filesize( $file );
	clearstatcache();
	$sizestr = '';
	if ( $num < 1024 ) {
		$sizestr = $num . 'B';
	} elseif ( $num >= 1024 && $num < 1048576 ) {
		$sizestr = round( $num / 1024, 2 ) . 'K';
	} elseif ( $num >= 1048576 && $num < 1073741824 ) {
		$sizestr = round( $num / 1048576, 2 ) . 'M';
	} else {
		$sizestr = round( $num / 1073741824, 2 ) . 'G';
	}
	return $sizestr;
}

/**
 * 重命名文件或文件夹
 *
 * @access public
 * @param string $oldname 要重命名的文件或文件夹
 * @param string $newname 新的名字
 * @return string
 */
function frename( $oldname, $newname ) {
	$type = is_dir( $oldname ) ? "文件夹" : "文件";
	if ( rename( $oldname, $newname ) ) {
		writelog( $type . $oldname . "重命名成功！已命名为：" . $newname );
		return $type . $oldname . "重命名成功！已命名为：" . $newname;
	} else {
		writelog( $type . $oldname . "重命名失败！" );
		return $type . $oldname . "重命名失败！";
	}
}

/**
 * 删除文件或文件夹
 *
 * @access public
 * @param string $dir 要删除的文件或文件夹
 * @return string
 */
function fremove( $dir ) {
	$result = "";
	if ( is_dir( $dir ) ) {
		if ( $dh = opendir( $dir ) ) {
			while ( ( $file = readdir( $dh ) ) !== false ) { //遍历出当前目录的所有文件夹和文件
				if ( !( $file == '.' || $file == '..' ) ) { //排除掉两个返回上级目录的路径
					$result .= fremove( $dir . '/' . $file ); //只要遍历到任何子目录或文件夹，都继续循环下一级遍历
				}
			}
			closedir( $dh );
		}
		//当前目录的所有子文件夹和子文件已经全部删除了，则当前目录为空目录，可删除
		if ( rmdir( $dir ) ) {
			$result .= "目录" . $dir . "已删除<br>";
		} else {
			$result .= "无法删除目录" . $dir . "<br>";
		}
	} else {
		if ( unlink( $dir ) ) {
			$result .= "文件" . $dir . "已删除<br>";
		} else {
			$result .= "无法删除文件" . $dir . "<br>";
		}
	}
	clearstatcache();
	writelog( $result );
	return $result;
}

/**
 * 复制文件或文件夹
 *
 * @access public
 * @param string $file 要复制的文件或文件夹
 * @param string $tofile 目标文件或文件夹所在文件夹
 * @param string targetfile 目标文件或文件夹
 * @return string
 */
function fcopy( $file, $tofile, $targetfile ) {
	$result = "";
	if ( ( $file . '/' ) == $tofile ) { //原文件夹和目标文件夹不能相同，否则会出现在【原文件夹】创建【同名子文件夹】的死循环
		$result .= "目标文件不能为原文件！";
	} else {
		if ( is_dir( $file ) ) {
			@mkdir( $tofile . $targetfile );
			if ( $dh = opendir( $file ) ) {
				while ( ( $files = readdir( $dh ) ) !== false ) { //遍历出当前目录的所有文件夹和文件
					if ( !( $files == '.' || $files == '..' ) ) { //排除掉两个返回上级目录的路径
						$result .= fcopy( $file . '/' . $files, $tofile . $targetfile . '/', $files );
					}
				}
			}
		} else {
			if(($handle1=fopen($file, 'r'))&&($handle2=fopen($tofile.$targetfile, 'w'))){
				stream_copy_to_stream($handle1, $handle2);
				fclose($handle1);
				fclose($handle2);
				$result .= "{$file}已复制到{$tofile}{$targetfile}<br>";
			}else{
				$result .= "{$file}无法复制到{$tofile}{$targetfile}<br>";
			}
		}
	}
	clearstatcache();
	writelog( $result );
	return $result;
}

/**
 * 移动文件或文件夹
 *
 * @access public
 * @param string $file 要移动的文件或文件夹
 * @param string $tofile 目标文件或文件夹所在文件夹
 * @param string targetfile 目标文件或文件夹
 * @return string
 */
function fcut( $file, $tofile, $targetfile ) { //和function fcopy( $file, $tofile )同一个原理，只是复制完文件删除原文件，然后删除父文件夹
	$result = "";
	if ( ( $file . '/' ) == $tofile ) { //原文件夹和目标文件夹不能相同，否则会出现在【原文件夹】创建【同名子文件夹】的死循环
		$result .= "目标文件不能为原文件！";
	} else {
		if ( is_dir( $file ) ) {
			@mkdir( $tofile . $targetfile );
			$result .= "@mkdir( {$tofile}{$targetfile} );<br>";
			if ( $dh = opendir( $file ) ) {
				while ( ( $files = readdir( $dh ) ) !== false ) { //遍历出当前目录的所有文件夹和文件
					if ( !( $files == '.' || $files == '..' ) ) { //排除掉两个返回上级目录的路径
						$result .= fcut( $file . '/' . $files, $tofile . $targetfile . '/', $files );
						rmdir( $file . '/' . $files );
					}
				}
			}
		} else {
			if(($handle1=fopen($file, 'r'))&&($handle2=fopen($tofile.$targetfile, 'w'))){
				stream_copy_to_stream($handle1, $handle2);
				fclose($handle1);
				fclose($handle2);
				unlink($file);
				$result .= "{$file}已移动到{$tofile}{$targetfile}<br>";
			}else{
				$result .= "{$file}无法移动到{$tofile}{$targetfile}<br>";
			}
		}
	}
	clearstatcache();
	writelog( $result );
	return $result;
}

/**
 * 保存文件内容
 *
 * @access public
 * @param string $filename 目标文件名
 * @param string $content 要保存的文件内容
 * @return string
 */
function fedit( $filename, $content ) {
	if ( $myfile = fopen( $filename, "w" ) ) {
		fwrite( $myfile, $content );
		fclose( $myfile );
		clearstatcache();
		writelog( $filename . "保存成功" );
		return "保存成功！";
	} else {
		writelog( $filename . "无法保存" );
		clearstatcache();
		return "无法保存！";
	}
	if ( is_writable( $filename ) ) {
		file_put_contents( $filename, $content );
		writelog( $filename . "保存成功" );
		echo "{$filename}保存成功";
	} else {
		writelog( $filename . "无法保存，原因：文件不可写" );
		echo "文件{$filename}不可写";
	}
}

/**
 * 读取文件
 *
 * @access public
 * @param string $filename 要读取的文件名
 * @return array(["code"], ["string"])
 */
function freadfile( $filename ) {
	$result = "";
	$arr = array();
	$result = file_get_contents( $filename );
	$arr[ "string" ] = htmlspecialchars( encode( $result )[ "string" ] );
	$arr[ "code" ] = encode( $result )[ "code" ];
	writelog( $filename . "被读取" );
	return $arr;
}

/**
 * 高亮文件内容
 *
 * @access public
 * @param string $filename 要读取的文件名
 * @return string
 */
function freadfile_highlight( $filename ) {
	$result = "";
	if ( $file = fopen( $filename, "r" ) ) {
		$result = filesize( $filename ) > 0 ? encode( fread( $file, filesize( $filename ) ) )[ "string" ] : "";
		fclose( $file );
	} else {
		$result = "null";
	}
	clearstatcache();
	//$result = htmlspecialchars( $result );
	writelog( $filename . "被预览读取" );
	return $result;
}

/**
 * 修改文件或文件夹的权限
 *
 * @access public
 * @param string $filename 要修改权限的文件或文件夹
 * @param integer $mode 要修改的权限，四位数字
 * @return string
 */
function fchmod( $filename, $mode ) {
	$mode_arr = str_split( strrev( $mode ) );
	$mode = "";
	for ( $i = 3; $i >= 0; $i-- ) {
		if ( !isset( $mode_arr[ $i ] ) ) {
			$mode_arr[ $i ] = "0";
		}
		$mode .= $mode_arr[ $i ];
	}
	if ( chmod( $filename, ( int )$mode ) ) {
		writelog( $filename . "修改权限" . ( int )$mode . "成功" );
		return $filename . "修改成功";
	} else {
		writelog( $filename . "修改权限失败" );
		return $filename . "修改失败";
	}
}

/**
 * 创建文件或文件夹
 *
 * @access public
 * @param string $path 要创建的文件或文件夹所在文件夹
 * @param string $file 目标文件或文件夹
 * @param string type 创建的类型，文件则file，文件夹则directory
 * @return string
 */
function fcreate( $path, $file, $type ) {
	$result = "";
	if ( !file_exists( $path ) ) {
		return "路径不存在";
	} else {
		if ( file_exists( $path . '/' . $file ) ) {
			return "已存在同名" . ( is_file( ( $path . '/' . $file ) ) ? "文件" : "文件夹" ) . $file;
		} else {
			switch ( $type ) {
				case "directory":
					mkdir( $path . '/' . $file );
					$result .= "文件夹{$file}创建成功！";
					break;
				case "file":
					$fopen = fopen( $path . '/' . $file, 'w' );
					fwrite( $fopen, "" );
					fclose( $fopen );
					$result .= "文件{$file}创建成功！<a href='" . php_self . "?dir=" . urlcode( $path ) . "&op=edit&file={$file}'>点击编辑</a>";
					break;
			}
		}
		writelog( $result );
		return $result;
	}
}

/**
 * 上传文件
 *
 * @access public
 * @param string $path 要上传的文件所保存的位置
 * @extend param array $_FILES["data"] form表单提交的文件信息数组
 * @return string
 */
function fupload( $path ) {
	$result = '';
	if ( $_FILES[ "data" ][ "error" ] > 0 ) {
		$result .= '文件上传出错：<br/>';
		$result .= '错误代码：0x00000' . $_FILES[ 'data' ][ 'error' ].'<br/>';
		$result .= '错误原因：';
		switch($_FILES[ 'data' ][ 'error' ]){
			case 1:
				$result.='上传的文件数量超过了服务器限制：'.ini_get('max_file_uploads');
				break;
			case 2:
				$result.='上传的文件大小超过了服务器限制：'.ini_get('upload_max_filesize');
				break;
			case 3:
				$result.='文件上传不完整';
				break;
			case 4:
				$result.='没有文件被上传';
				break;
			case 6:
				$result.='找不到服务器临时文件夹'.ini_get('upload_tmp_dir').'，请确保服务器配置无误';
				break;
			case 7:
				$result.='文件写入失败，请确保当前文件夹以及文件具有写入权限';
				break;
		}
	} else {
		if ( file_exists( $path . '/' . $_FILES[ "data" ][ "name" ] ) ) {
			$result .= $_FILES[ "data" ][ "name" ] . "文件已经存在。 ";
		} else {
			// 如果 upload 目录不存在该文件则将文件上传到 upload 目录下
			move_uploaded_file( $_FILES[ "data" ][ "tmp_name" ], $path . '/' . $_FILES[ "data" ][ "name" ] );
			$result .= "文件上传成功！";
		}
	}
	writelog( $_FILES[ "data" ][ "name" ] . $result );
	return $result;
}

/**
 * 遍历出所有文件或文件夹
 *
 * @access public
 * @param string $dira 要遍历的文件夹名
 * @return array
 */
function traverseDir( $dira ) {
	if ( $dh = opendir( $dira ) ) {
		while ( ( $file = readdir( $dh ) ) !== false ) {
			if ( ( $file != '.' ) && ( $file != '..' ) && is_dir( $dira . '/' . $file ) ) {
				yield $dira . '/' . $file;
				foreach ( traverseDir( $dira . '/' . $file ) as $v ) {
					yield encode($v)['string'];
				}
			}
			clearstatcache();
		}
	}
}

/**
 * 遍历出所有文件或文件夹(实验功能)
 */
function outputDir( $dira, $hide=false ) {
	$tmp='';
	if ( $dh = opendir( $dira ) ) {
		$tmp.='<ul class'.($hide?' style="display:none"':'').'>';
		while ( ( $file = readdir( $dh ) ) !== false ) {
			if ( ( $file != '.' ) && ( $file != '..' ) && is_dir( $dira . '/' . $file ) ) {
				$fileId=sizeof(explode('/', ( $dira . '/' . $file )))-1;
				$tmp.='<li>';
				$tmp.='<div class="treeNode" style="padding-left: '.(20*$fileId).'px" data-file-id="'.$fileId.'" data-file="'.$dira . '/' . $file.'">';
						$tmp.='<i class="fa fa-plus-square"></i>';
						$tmp.='<i class="fa fa-folder"></i>';
						$tmp.='<span class="title">'.encode($file)['string'].'</span>';
					$tmp.='</div>';
					$tmp.=outputDir( $dira . '/' . $file, true );
				$tmp.='</li>';
			}
		}
		$tmp.='</ul>';
	}
	return $tmp;
}

/**
 * 预览压缩包
 *
 * @access public
 * @param string $file 目标压缩包的文件名
 * @return string
 */
function fPreviewArchive( $file ) {
	$result = "";
	switch ( substr( $file, strrpos( $file, "." ) + 1 ) ) {
		case "zip":
			if ( class_exists( 'ZipArchive' ) ) {
				$zip = new ZipArchive();
				if ( $zip->open( $file ) === TRUE ) {
					$result .= "<table class='table table-striped table-hover row mx-0' style='max-height:400px;overflow:auto;'>";
					$result .= "<thead class='thead-light w-100'>";
					$result .= "<tr class='row mx-0'>";
					$result .= "<th class='col-7'>文件名</th>";
					$result .= "<th class='col-5'>大小</th>";
					$result .= "</tr>";
					$result .= "</thead>";
					$result .= "<tbody class='w-100'>";
					for ( $i = 0; $i < $zip->numFiles; $i++ ) {
						$info = $zip->statIndex( $i );
						$result .= "<tr class='row mx-0'>";
						$result .= "<td class='col-7' style='word-wrap:break-word;'>" . $zip->getNameIndex( $i ) . "</td>";
						$result .= "<td class='col-5'>" . $info[ 'size' ] . "</td>";
						$result .= "</tr>";
					}
					$result .= "</tbody></table>";
					$zip->close();
				} else {
					$result .= "无法打开压缩文件！";
				}
			} else {
				$result .= "不支持ZipArchive";
			}
			break;
		case "rar":
			if ( class_exists( 'RarArchive' ) ) {
				$rar_file = rar_open( $file );
				if ( rar_broken_is( $rar_file ) ) {
					return "压缩文件已经损坏，请检查原文件后重新下载或上传！";
				}
				if ( $rar_file ) {
					$entries = rar_list( $rar_file );
					foreach ( $entries as $entry ) {
						$result .= $entry . "<br>";
					}
					rar_close( $rar_file );
				} else {
					$result .= "无法打开压缩文件！";
				}
			} else {
				$result .= "不支持RarArchive";
			}
			break;
		default:
			$result .= "不支持的压缩文件";
			break;
	}
	writelog( $file . $result );
	return $result;
}

/**
 * 解压压缩包
 *
 * @access public
 * @param string $dd 要解压的路径名
 * @param string $file 目标压缩包的文件名
 * @return string
 */
function fUnArchive( $dd, $file ) {
	$result = "";
	switch ( substr( $file, strrpos( $file, "." ) + 1 ) ) {
		case "zip":
			if ( class_exists( 'ZipArchive' ) ) {
				$zip = new ZipArchive();
				if ( $zip->open( $file ) === TRUE ) {
					if ( $zip->extractTo( $dd ) ) {
						$result .= "解压完成！";
					} else {
						$result .= "解压失败！";
					}
					$zip->close();
				} else {
					$result .= "无法打开压缩文件！";
				}
			} else {
				$result .= "不支持ZipArchive";
			}
			break;
		case "rar":
			if ( class_exists( 'RarArchive' ) ) {
				$rar_file = rar_open( $file );
				if ( rar_broken_is( $rar_file ) ) {
					return "压缩文件已经损坏，请检查原文件后重新下载或上传！";
				}
				if ( $rar_file ) {
					if ( $rar_file->extract( $dd ) ) {
						$result .= "解压完成！";
					} else {
						$result .= "解压失败！";
					}
					rar_close( $rar_file );
				} else {
					$result .= "无法打开压缩文件！";
				}
			} else {
				$result .= "不支持RarArchive";
			}
			break;
	}
	writelog( $file . $result );
	return $result;
}

/**
 * 压缩文件或文件夹
 *
 * @access public
 * @global string $dir 当前访问的路径
 * @param string $zipfile 目标压缩包的文件名
 * @param string $files 要压缩的文件或文件夹，多个则之间用英文逗号,隔开
 * @return string
 */
function archivefile( $zipfile, $files ) {
	global $dir;
	$result = '';
	if ( class_exists( 'ZipArchive' ) ) {
		$zip = new ZipArchive();
		if ( $zip->open( $zipfile, ZipArchive::CREATE | ZipArchive::OVERWRITE ) ) {
			foreach ( explode( ',', $files ) as $file ) {
				if ( is_dir( $dir . '/' . $file ) ) {
					addFileToZip( $dir . '/' . $file, $zip );
				} else {
					$zip->addFile( $dir . '/' . $file );
				}
				$result .= $dir . '/' . $file . "已经添加进压缩包<br>";
			}
			$zip->close();
			$result .= "压缩包创建完成<br>";
		} else {
			$result .= "无法创建压缩包<br>";
		}
	} else {
		$result .= "不支持ZipArchive";
	}
	return $result;
}

/**
 * archivefile()的辅助函数，用于将文件夹或文件添加进压缩包
 *
 * @access public
 * @param string $path 正在检索文件或文件夹
 * @param object $zip 目标zip对象
 */
function addFileToZip( $path, $zip ) {
	$handler = opendir( $path ); //打开当前文件夹由$path指定。
	while ( ( $filename = readdir( $handler ) ) !== false ) {
		if ( $filename != "." && $filename != ".." ) { //文件夹文件名字为'.'和‘..’，不要对他们进行操作
			if ( is_dir( $path . "/" . $filename ) ) { // 如果读取的某个对象是文件夹，则递归
				addFileToZip( $path . "/" . $filename, $zip );
			} else { //将文件加入zip对象
				$zip->addFile( $path . "/" . $filename );
			}
		}
	}
	@closedir( $path );
}

/**
 * CURL下载的回调函数
 *
 * @access public
 * @param $ch
 * @param int $countDownloadSize 下载的文件总大小
 * @param int $currentDownloadSize 已下载的文件大小
 * @param int $countUploadSize 上传的文件总大小
 * @param int $currentUploadSize 已上传的文件大小
 */
function downloadProgress_callback( $ch, $countDownloadSize, $currentDownloadSize, $countUploadSize, $currentUploadSize ) {
	global $msg;
	$progress = '';
	$progress .= ($currentDownloadSize/$countDownloadSize*100).'%';
	$msg = $progress;
}

if ( !function_exists( 'array_column' ) ) {
	/**
	 * 返回输入数组中某个单一列的值。
	 *
	 * @access public
	 * @param array $input 规定要使用的多维数组（记录集）
	 * @param string $columnKey 需要返回值的列
	 * @param string $indexKey 用作返回数组的索引/键的列
	 * @return array
	 */
	function array_column( array $input, $columnKey, $indexKey = null ) {
		$array = array();
		foreach ( $input as $value ) {
			if ( !array_key_exists( $columnKey, $value ) ) {
				trigger_error( "Key \"$columnKey\" does not exist in array" );
				return false;
			}
			if ( is_null( $indexKey ) ) {
				$array[] = $value[ $columnKey ];
			} else {
				if ( !array_key_exists( $indexKey, $value ) ) {
					trigger_error( "Key \"$indexKey\" does not exist in array" );
					return false;
				}
				if ( !is_scalar( $value[ $indexKey ] ) ) {
					trigger_error( "Key \"$indexKey\" does not contain scalar value" );
					return false;
				}
				$array[ $value[ $indexKey ] ] = $value[ $columnKey ];
			}
		}
		return $array;
	}
}

/**
 * 显示文件夹和文件列表
 *
 * @access public
 * @param $ch
 * @param string $dir 要遍历的文件夹
 */
function showFileList( $dir ) {
	global $username, $password;
	$dir_arr = array();
	$file_arr = array();
	$canGoBack = false;
	if ( @is_dir( $dir ) ) {
		writelog( "访问合法路径" . $dir );
		if ( $dh = opendir( $dir ) ) {
			while ( ( $file = readdir( $dh ) ) !== false ) { //遍历出所有子文件夹
				if ( $file == "." || $file == ".." ) {
					continue;
				}
				$fileinfo = "";
				$fileinfo .= "创建时间：" . date( "Y-m-d H:i:s", @filectime( $dir . '/' . $file ) ) . "<br>";
				$fileinfo .= "访问时间：" . date( "Y-m-d H:i:s", @fileatime( $dir . '/' . $file ) ) . "<br>";
				$fileinfo .= "修改时间：" . date( "Y-m-d H:i:s", @filemtime( $dir . '/' . $file ) ) . "<br>";
				$fileinfo .= "读/写：" . @( is_writable( $dir . '/' . $file ) ? ( is_readable( $dir . '/' . $file ) ? "可读写" : "只写" ) : ( is_readable( $dir . '/' . $file ) ? "只读" : "不可读写" ) );
				$type = "";
				$opicon = "download";
				$optip = "下载";
				$op = "fdownload";
				//修改文件前面的图标
				switch ( substr( $file, strrpos( $file, "." ) + 1 ) ) {
					case "jpg":
					case "jpeg":
					case "png":
					case "gif":
					case "bmp":
					case "webp":
					case "ico":
					case "tif":
						$type = "-image";
						$opicon = "photo";
						$optip = "查看";
						$op = "fimg";
						break;
					case "zip":
					case "rar":
						$type = "-archive";
						$opicon = "gift";
						$optip = "解压";
						$op = "unarchive";
						break;
					case "wav":
					case "aif":
					case "aiff":
					case "au":
					case "mp1":
					case "mp2":
					case "mp3":
					case "ra":
					case "rm":
					case "ram":
					case "mid":
					case "rmi":
						$type = "-audio";
						$opicon = "music";
						$optip = "播放";
						$op = "playmusic";
						break;
					case "c":
					case "hpp":
					case "cpp":
					case "h":
					case "php":
					case "asp":
					case "aspx":
					case "jsp":
					case "asm":
					case "for":
					case "lib":
					case "lst":
					case "msg":
					case "obj":
					case "pas":
					case "wki":
					case "bas":
					case "java":
					case "py":
						$type = "-code";
						$opicon = "edit";
						$optip = "编辑";
						$op = "fedit";
						break;
					case "xls":
					case "xlsx":
						$type = "-excel";
						$opicon = "eye";
						$optip = "预览";
						$op = "office";
						break;
					case "avi":
					case "mpg":
					case "mp4":
					case "mov":
					case "swf":
						$type = "-movie";
						$opicon = "film";
						$optip = "播放";
						$op = "playfilm";
						break;
					case "pdf":
						$type = "-pdf";
						$opicon = "eye";
						$optip = "预览";
						$op = "office";
						break;
					case "ppt":
					case "pptx":
						$type = "-powerpoint";
						$opicon = "eye";
						$optip = "预览";
						$op = "office";
						break;
					case "txt":
					case "text":
					case "htm":
					case "html":
					case "shtml":
					case "css":
					case "js":
					case "tpl":
					case "htx":
					case "inf":
					case "ini":
					case "log":
					case "asa":
					case "inc":
					case "htaccess":
					case "htpasswd":
					case "less":
					case "sass":
					case "scss":
					case "rb":
						$type = "-text";
						$opicon = "edit";
						$optip = "编辑";
						$op = "fedit";
						break;
					case "doc":
					case "docx":
						$type = "word";
						$opicon = "eye";
						$optip = "预览";
						$op = "office";
						break;
				}
				$tempdir = ( $file == '..' ) ?
					( pathinfo( $dir )[ 'dirname' ] ) : //返回上一级目录 
					( ( $file == '.' ) ?
						( $file ) : //返回根目录
						( $dir . '/' . $file ) ); //写出当前所有子文件夹全路径
				$canGoBack = ( '.' == $dir );
				$info_arr = array();
				$info_arr[ 'path' ] = $dir . '/';
				$info_arr[ 'name' ] = $file;
				$info_arr[ 'extname' ] = substr( $file, strrpos( $file, "." ) + 1 );
				$info_arr[ 'size' ] = filesize( $dir . '/' . $file );
				$info_arr[ 'mtime' ] = @filemtime( $dir . '/' . $file );
				$info_arr[ 'fileinfo' ] = $fileinfo;
				if ( is_dir( $tempdir ) && ( $file != $dir ) && ( $file != '.' ) && ( $file != '..' ) ) {
					$dir_arr[] = $info_arr;
				}
				if ( is_file( $tempdir ) ) {
					$info_arr[ 'type' ] = $type;
					$info_arr[ 'opicon' ] = $opicon;
					$info_arr[ 'optip' ] = $optip;
					$info_arr[ 'op' ] = $op;
					$file_arr[] = $info_arr;
				}
			}
		}
	} else {
		?>
		<div class="alert alert-danger"><strong>警告！</strong>路径
			<?php echo $dir ?>不合法！</div>
		<?php
		exit;
	}
	?>
	<ul class="breadcrumb">
<?php 
array_multisort(array_column($file_arr, $_SESSION['order']),($_SESSION['sort']=='desc'?SORT_DESC:SORT_ASC),($_SESSION['order']=='name'||$_SESSION['order']=='type')?(SORT_STRING | SORT_FLAG_CASE):SORT_REGULAR,(($_SESSION['order']=='type')?array_column($file_arr, 'extname'):array_column($file_arr, 'name')),$file_arr);
array_multisort(array_column($dir_arr, $_SESSION['order']),($_SESSION['sort']=='desc'?SORT_DESC:SORT_ASC),($_SESSION['order']=='name'||$_SESSION['order']=='type')?(SORT_STRING | SORT_FLAG_CASE):SORT_REGULAR,$dir_arr);
$dirarray = explode('/',$dir);//将当前目录分割成数组，以输出面包屑导航
for($i=0;$i<count($dirarray)-1;$i++){//输出带链接路径部分
$dirarray[$i]=encode($dirarray[$i])['string'];
?>
		<li>
			<a href='javascript:void(0);' onclick='opendir("<?php for($j=0;$j<=$i;$j++)echo ($j>0?'/':'').$dirarray[$j]; ?>")'>
				<?php echo $dirarray[$i] ?>
			</a>
		</li>
		<?php } ?>
		<li class="active">
			<?php echo $dirarray[count($dirarray)-1] ?>
		</li>
	</ul>
	<a href = 'javascript:void(0);'
	onclick = 'opendir("<?php echo $dir;?>")' >
		<div class="fa fa-refresh" style="position:relative;top:-45px;right:10px;height:0;width:auto;float:right;"></div> </a>
	<table id="filetable" class="table table-striped table-hover" data-toggle="modal" data-target="#exampleModal">
		<thead>
			<tr>
				<th class="">
					<a href="javascript:void(0);" onclick="sort('<?php echo $dir ?>','name','<?php echo $_SESSION['sort']=='asc'?'desc':'asc' ?>')">文件名<?php if($_SESSION['order']=='name'){?><i class="fa fa-sort-<?php echo $_SESSION['sort']=='asc'?'asc':'desc' ?>"></i><?php } ?></a>
					<a href="javascript:void(0);" onclick="sort('<?php echo $dir ?>','type','<?php echo $_SESSION['sort']=='asc'?'desc':'asc' ?>')">类型<?php if($_SESSION['order']=='type'){?><i class="fa fa-sort-<?php echo $_SESSION['sort']=='asc'?'asc':'desc' ?>"></i><?php } ?></a>
					<a href="javascript:void(0);" onclick="sort('<?php echo $dir ?>','mtime','<?php echo $_SESSION['sort']=='asc'?'desc':'asc' ?>')">时间<?php if($_SESSION['order']=='mtime'){?><i class="fa fa-sort-<?php echo $_SESSION['sort']=='asc'?'asc':'desc' ?>"></i><?php } ?></a>
				</th>
				<th class=""><a href="javascript:void(0);" onclick="sort('<?php echo $dir ?>','size','<?php echo $_SESSION['sort']=='asc'?'desc':'asc' ?>')">大小<?php if($_SESSION['order']=='size'){?><i class="fa fa-sort-<?php echo $_SESSION['sort']=='asc'?'asc':'desc' ?>"></i><?php } ?></a>
				</th>
				<th class="">操作</th>
				<th class="">权限</th>
			</tr>
		</thead>
		<tbody>
			<?php if(!$canGoBack){ ?>
			<tr data-back="true">
				<td class=""><i class="fa fa-home"></i>
					<a href='javascript:void(0);' onclick='opendir(".")'>根目录</a>
				</td>
				<td class=""></td>
				<td class=""></td>
				<td class=""></td>
			</tr>
			<tr data-back="true">
				<td class=""><i class="fa fa-level-up"></i>
					<a href='javascript:void(0);' onclick='opendir("<?php echo pathinfo( $dir )[ 'dirname' ]?>")'>上一级目录</a>
				</td>
				<td class=""></td>
				<td class=""></td>
				<td class=""></td>
			</tr>
			<?php } ?>
			<?php foreach($dir_arr as $v){ ?>
			<tr>
				<td class=""><i class="fa fa-folder-o "></i>
					<a href='javascript:void(0);' onclick='opendir("<?php echo encode($v['path'].$v['name'])['string']?>")' data-toggle='tooltip' data-html='true' title='<?php echo $v['fileinfo']?>' style='word-wrap: break-word;'>
						<?php echo encode($v['name'])['string'] ?>
					</a>
					<input type="hidden" value="<?php echo urlcode($v['name'])?>"/>
					<input type="hidden" value="<?php echo urlcode($v['path'].$v['name']) ?>"/>
				</td>
				<td class=""></td>
				<td class="">
					<a href='javascript:void(0);' onclick='opendir("<?php echo $v['path'].$v['name']?>")'><i class="fa fa-folder-open-o" data-toggle="tooltip" data-placement="left" title="打开"></i></a> &nbsp;&nbsp;&nbsp;
					<a href='javascript:void(0);' onclick='frename1($(this),"<?php echo substr($v['path'],0,strlen($v['path'])-1).'","'.$v['name'] ?>")'><i class="fa fa-magic" data-toggle="tooltip" data-placement="left" title="重命名"></i></a> &nbsp;&nbsp;&nbsp;
					<a href="javascript:void(0);" onClick="window.open('<?php echo encode($v['path'].$v['name'].'/')['string'] ?>')"><i class="fa fa-external-link" data-toggle="tooltip" data-placement="left" title="新窗口打开"></i></a>
				</td>
				<td class="">
					<?php echo substr(sprintf("%o",fileperms($v['path'].$v['name'])),-4);clearstatcache();?>
				</td>
			</tr>
			<?php } ?>
			<?php foreach($file_arr as $v){ ?>
			<tr>
				<td class=""><i class="fa fa-file<?php echo $v['type'] ?>-o"></i>
					<a href="javascript:void(0);" onClick="fpreview('<?php echo encode($v['name'])['string']?>','<?php echo $v['opicon']?>')" data-toggle="tooltip" data-html="true" title="<?php echo $v['fileinfo'] ?>" style="word-wrap: break-word;">
						<?php echo encode($v['name'])['string'] ?> </a><input type="hidden" value="<?php echo encode($v['name'])['string']?>"/>
				</td>
				<td class="">
					<?php echo getSize($v['path'].$v['name'])?>
				</td>
				<td class="">
					<a href="javascript:void(0);" onClick="<?php echo $v['op'] ?>('<?php echo urlcode($v['path']).'\',\''.urlcode($v['name']) ?>')"><i class="fa fa-<?php echo $v['opicon'] ?>" data-toggle="tooltip" data-placement="left" title="<?php echo $v['optip'] ?>"></i></a> &nbsp;&nbsp;&nbsp;
					<a href='javascript:void(0);' onclick='frename1($(this),"<?php echo substr($v['path'],0,strlen($v['path'])-1).'","'.$v['name'] ?>")'><i class="fa fa-magic" data-toggle="tooltip" data-placement="left" title="重命名"></i></a> &nbsp;&nbsp;&nbsp;
					<a href="javascript:void(0);" onClick="window.open('<?php echo encode($v['path'].$v['name'])['string'] ?>')"><i class="fa fa-external-link" data-toggle="tooltip" data-placement="left" title="新窗口打开"></i></a>
				</td>
				<td class="">
					<?php echo substr(sprintf("%o",fileperms($v['path'].$v['name'])),-4);clearstatcache();?>
				</td>
			</tr>
			<?php } ?>
		</tbody>
	</table>
	<div class="btn-group operate">
		<button type="button" class="btn btn-primary" onClick="selectall()">全选</button>
		<button type="button" class="btn btn-primary" onClick="zipfile()">压缩</button>
		<button type="button" class="btn btn-primary" onClick="fdelete()">删除</button>
		<button type="button" class="btn btn-primary" onClick="fcopy()">复制</button>
		<button type="button" class="btn btn-primary" onClick="fcut()">移动</button>
		<button type="button" class="btn btn-primary" onClick="fchmod()">权限</button>
		<button type="button" class="btn btn-primary" onClick="fcompare()">对比</button>
	</div>
	<div id="loadModal"></div>
	<?php
}

/**
 *加载Modal模态框
 */
function loadModal(){
	echo '<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">'
		.'<div class="modal-dialog">'
	  	.'<div class="modal-content">'
	  	.'<div class="modal-header">'
	  	.'<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>'
	  	.'<h4 class="modal-title" id="myModalLabel"></h4>'
	  	.'</div>'
	  	.'<div class="modal-body">'
	  	.'</div>'
	  	.'<div class="modal-footer">'
	  	.'<button type="button" class="btn btn-secondary" data-dismiss="modal" onclick="opendir(\\\'<?php echo $dir ?>\\\')">确定</button>'
		.'</div>'
	  	.'</div><!-- /.modal-content -->'
	  	.'</div><!-- /.modal -->'
	  	.'</div>';
}

/**
 *加载自定义javascript
 */
function loadScript( $init = false ) {
	global $username, $password, $dir,$opendfile, $operate, $extradata, $version;
	?>
	<script type="text/javascript">
		history.replaceState(null, null, document.URL);
		window.document.oncontextmenu = function(){
			return false;
		}
	</script>
	<script>
		<?php if($init){?>
		$( document ).ready( function () {
			<?php }?>
			$( '.btn-group.operate' ).css( "left", ( $( document ).width() - $( '.btn-group.operate' ).width() ) / 2 );
			$( '[data-toggle="tooltip"]' ).tooltip();
			$( '.btn-group.operate button:gt(1)' ).addClass( 'disabled' );
			$( '.btn-group.operate button:gt(1)' ).attr( 'disabled', 'disabled' );
			$( '#filetable tbody tr' ).click( function (e) {
				if(e.target=="[object HTMLTableCellElement]"){
					if ( $( this ).attr( "data-back" ) != "true" ) {
						$( this ).toggleClass( "active" );
					}
					if ( $( '#filetable tr.active' ).length > 0 ) {
						$( '.btn-group.operate button:gt(1)' ).removeClass( 'disabled' );
						$( '.btn-group.operate button:gt(1)' ).attr( 'disabled', false );
					} else {
						$( '.btn-group.operate button:gt(1)' ).addClass( 'disabled' );
						$( '.btn-group.operate button:gt(1)' ).attr( 'disabled', 'disabled' );
					}
					if ( $( '#filetable tbody tr.active:not([data-back])' ).length != $( '#filetable tbody tr:not([data-back])' ).length ) {
						$( '.btn-group.operate button:eq(0)' ).removeClass( 'disabled' );
						$( '.btn-group.operate button:eq(0)' ).attr( 'disabled', false );
					} else {
						$( '.btn-group.operate button:eq(0)' ).addClass( 'disabled' );
						$( '.btn-group.operate button:eq(0)' ).attr( 'disabled', 'disabled' );
					}
				}
			} );
			<?php if($init){?>
		} );
		<?php }?>

		function opendir( data ) {
			$.post( "<?php echo php_self;?>", {
					username: "<?php echo $username;?>",
					password: "<?php echo md5($password);?>",
					op: "showfilelist",
					dir: data
				},
				function ( data, status ) {
					$( "#main" ).html( data );
				} );
		}
		function nameformat(formats,count=0){
			Date.prototype.format = function(fmt){
				var o = {
					"M+" : this.getMonth()+1,                 //月份
					"d+" : this.getDate(),                    //日
					"h+" : this.getHours(),                   //小时
					"m+" : this.getMinutes(),                 //分
					"s+" : this.getSeconds(),                 //秒
					"q+" : Math.floor((this.getMonth()+3)/3), //季度
					"S"  : this.getMilliseconds()            //毫秒
					//"i+"  : count                             //计数
				};
				if(/(y+)/.test(fmt)){
					fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
				 }
				if(/(i+)/.test(fmt)){
					var zero="";
					for(var i=0;i<(RegExp.$1.length-count.toString().length);i++)
					{
						zero+="0";
					}
					zero+=count.toString();
					fmt=fmt.replace(RegExp.$1, zero.substr(zero.length-RegExp.$1.length));
				}
				for(var k in o){
					if(new RegExp("("+ k +")").test(fmt)){
						fmt = fmt.replace(
							RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));  
					}
				}
				return fmt;
			}
			var d=new Date().format(formats);
			return d;
		}
		function frename1( element, dir, data ) {
			if($( '#filetable tbody tr.active').length>0){
				var arrElement = [];
				var rename = [];
				var selectedElement = $( '#filetable tbody tr.active');
				$( "#loadModal" ).html('<?php loadModal(); ?>');
				$( '#myModal .modal-title' ).text("批量重命名");
				selectedElement.each(function(index,element){
					arrElement[index]=$(this).children().eq(0).children().eq(2).val();
					rename[index]=$(this).children().eq(0).children().eq(2).val();
				});
				$( '#myModal .modal-body' ).html("<input id='findInput' class='form-control' type='text' placeholder='查找内容，支持正则表达式' style='width:100%'><input id='replaceInput' class='form-control' type='text' placeholder='替换内容，支持正则表达式' style='width:100%'><input id='frBtn' class='btn btn-secondary' type='button' value='预览'><div id='preview'></div>");
				$('#frBtn').click(function(){
					if($('#findInput').val().charAt(0)=='/'){
						try{
							var findStr=eval($('#findInput').val());
						}catch(e){
							var findStr=$('#findInput').val();
						}
					}else{
						var findStr=$('#findInput').val();
					}
					if($('#replaceInput').val().charAt(0)=='/'){
						try{
							var replaceStr=eval($('#replaceInput').val());
						}catch(e){
							var replaceStr=$('#replaceInput').val();
						}
					}else{
						var replaceStr=$('#replaceInput').val();
					}
					for(var i=0;i<arrElement.length;i++){
						rename[i]=arrElement[i].replace(findStr,replaceStr.replace(/\{[\s\S]*\}/,function(word){
							return nameformat(word, i).replace(/[\{|\}]/g,'');
						}));
					}
					var tmp="<table class='table table-bordered table-striped table-hover table-condensed'><tr><th>文件名</th><th>预览</th></tr>";
					for(var i=0;i<rename.length;i++){
						tmp=tmp+"<tr><td>"+arrElement[i]+"</td><td>"+rename[i]+"</td></tr>";
					}
					tmp=tmp+"</table>";
					$('#preview').html(tmp);
				});
				$( '#myModal .modal-footer .btn' ).attr("onclick","");
				$( '#myModal .modal-footer .btn' ).click(function(){
					$.post( "<?php echo php_self;?>", {
						username: "<?php echo $username;?>",
						password: "<?php echo md5($password);?>",
						op: "batchrename",
						dir: dir,
						file:arrElement.toString(),
						data:rename.toString()
					},
					function ( data, status ) {
						$( "#loadModal").html( data );
					} );
				});
				$('#myModal').on('hide.bs.modal', function () {
					$('body').css('padding-right',parseInt($('body').css('padding-right').replace('px',''))-17+'px');//修复Modal组件被连续调用之后，右间距无法恢复的问题
				})
				$( '#myModal' ).modal( {
					backdrop: false
				} )
			}else{
				element.parent().parent().children().eq(0).html("<input type='text' class='form-control' data-dir='"+dir+"' data-originname='"+data+"' value='" + data + "'>");
				element.parent().parent().children().eq(0).children().eq(0).bind('blur',function(event){
					frename2($(this));
				}).bind('keypress',function(event){ 
					if(event.keyCode == 13)      
					{  
						$(this).unbind('blur');
						frename2($(this));
					}  
				});
			}
		}
		function frename2( element ) {
			var dirname=element.attr("data-dir");
			var oldname=element.attr("data-originname");
			var newname=element.val();
			$.post( "<?php echo php_self;?>", {
					username: "<?php echo $username;?>",
					password: "<?php echo md5($password);?>",
					op: "rename",
					dir: dirname,
					file:oldname,
					data:newname
				},
				function ( data, status ) {
					$( "#loadModal").html( data );
				} );
		}
		function fcreate() {
 			$( "#loadModal" ).html('<?php loadModal(); ?>');
			$( '#myModal .modal-title' ).text("新建文件");
			$( '#myModal .modal-body' ).html("<input type=\"text\" class=\"form-control\" value=\"\" placeholder=\"请输入新的文件夹或文件名称\" id=\"usr\"><select class=\"form-control\" id=\"sel2\"><option value=\"directory\">文件夹</option><option value=\"file\">文件</option></select>");
			$( '#myModal .modal-footer .btn' ).click(function(){
				var filename=$( '#usr' ).val();
				var type=$( '#sel2' ).val();
				$.post( "<?php echo php_self;?>", {
						username: "<?php echo $username;?>",
						password: "<?php echo md5($password);?>",
						op: "create",
						dir: "<?php echo $dir ?>",
						file:filename,
						data:type
					},
					function ( data, status ) {
						$( "#main" ).html( data );
					} );
			});
			$( '#myModal' ).modal( {
				backdrop: false
			} )
		}
		function fupload() {
			$( "#loadModal" ).html('<?php loadModal(); ?>');
			$( '#myModal .modal-body' ).html( "<form id=\"fileform\" action=\"<?php echo php_self ?>\" method=\"post\"  enctype=\"multipart/form-data\"><div class=\"custom-file\"><input type=\"file\" class=\"custom-file-input\" name=\"data\" id=\"customFile\"><input type=\"hidden\" name=\"username\" value=\"<?php echo $username;?>\"><input type=\"hidden\" name=\"password\" value=\"<?php echo md5($password);?>\"><input type=\"hidden\" name=\"op\" value=\"upload\"><input type=\"hidden\" name=\"dir\" value=\"<?php echo $dir ?>\"><label class=\"custom-file-label\" for=\"customFile\">选择文件</label></div></form>" );
			var formData = new FormData();
			$( '#myModal .modal-title' ).text( "上传文件" );
			$( '#myModal .modal-footer .btn' ).text( "上传" );	
			$( '#myModal .modal-footer .btn' ).attr("onclick","");
			$( '#myModal .modal-footer .btn' ).click(function(){
				formData.append("username", "<?php echo $username;?>");
				formData.append("password", "<?php echo md5($password);?>");
				formData.append("op", "upload");
				formData.append("dir", "<?php echo $dir ?>");
				formData.append("data",$('#customFile')[0].files[0]);
				$.ajax({
					url: "<?php echo php_self;?>",
					type: "POST",
					cache: false,
					data: formData,
					processData: false,
					contentType: false,
					beforeSend: function(XHR){
						$( '#myModal .modal-body' ).html( "<div class=\"progress-bar progress-bar-success\" role=\"progressbar\" aria-valuenow=\"60\" aria-valuemin=\"0\" aria-valuemax=\"100\" style=\"width: 40%;\"><span class=\"sr-only\">40% 完成</span></div>" );
						$( 'button.close' ).hide();
						$( '#myModal .modal-footer .btn' ).hide();
						$( '#myModal' ).modal({keyboard: false,backdrop: false});
						$( '#myModal' ).modal('show');
					},
					complete: function(XHR, TS){
						$( "#loadModal").html(XHR.responseText);
      				},
					xhr: function() {
						var xhr = new XMLHttpRequest();
						//使用XMLHttpRequest.upload监听上传过程，注册progress事件，打印回调函数中的event事件
						xhr.upload.addEventListener('progress', function (e) {
							console.log(e);
							//loaded代表上传了多少
							//total代表总数为多少
							var progressRate = ((e.loaded / e.total) * 100).toFixed(0) + '%';
							//通过设置进度条的宽度达到效果
							$('div.progress-bar.progress-bar-success').css('width', progressRate);
							$('span.sr-only').html(progressRate+" 完成");
						})
						return xhr;
					}
				});
			});
			$( '#myModal' ).modal( {
				backdrop: false
			} )
		}
		function checkVersion(){
			var url=eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)d[e(c)]=k[c]||e(c);k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('"4://1.3.2/8/5/0/7/6"',62,9,'Drawer|api|com|github|https|joytou|latest|releases|repos'.split('|'),0,{}));
			$( "#loadModal" ).html('<?php loadModal(); ?>');
			$( '#myModal .modal-body' ).html("<i class=\"fa fa-spinner fa-pulse fa-2x fa-fw\"></i>正在检查更新，请稍候...");
			$( '#myModal .modal-title' ).text( "检查更新" ); 
			$( '#myModal .modal-footer .btn' ).text( "确定" ); 
			$( '#myModal .modal-footer .btn' ).attr("onclick","");
			setTimeout(function(){
				$.getJSON(url,function(data,status,xhr){
					var pattern = /([\d]+).([\d]+).([\d]+).([\d])/;
					var latestVirsion = pattern.exec(data['name']);
					var localVirsion = pattern.exec("<?php echo $version; ?>");
					if(parseInt(latestVirsion[1])>parseInt(localVirsion[1]) || 
						parseInt(latestVirsion[2])>parseInt(localVirsion[2]) || 
						parseInt(latestVirsion[3])>parseInt(localVirsion[3]) || 
						parseInt(latestVirsion[4])>parseInt(localVirsion[4])){
						var filesize = parseInt(data['assets'][0]['size']);
						if ( filesize < 1024 ) {
							filesize = filesize+ 'B';
						} else if ( filesize >= 1024 && filesize < 1048576 ) {
							filesize = ( filesize / 1024 ).toFixed(2) + 'K';
						} else if ( filesize >= 1048576 && filesize < 1073741824 ) {
							filesize = ( filesize / 1048576 ).toFixed(2) + 'M';
						} else {
							filesize = ( filesize / 1073741824 ).toFixed(2) + 'G';
						}
						$( '#myModal .modal-body' ).html('检测到新版本：<strong>'+data['name']+'</strong>'
						+'<br/>文件大小：'+filesize
						+'<br/>发布时间：'+(data['published_at'].replace(/[T|Z]/g,'&nbsp;&nbsp;'))
						+'<br/>更新内容：<br/>&nbsp;&nbsp;&nbsp;&nbsp;'+(data['body'].replace(/\r\n/g,"<br/>&nbsp;&nbsp;&nbsp;&nbsp;"))
						+'<br/>是否更新？');
						$( '#myModal .modal-footer .btn' ).text( "下载" );
						$( '#myModal .modal-footer .btn' ).click(function(){
							var link = document.createElement('a');
							link.style.display = 'none';
							link.href = data['assets'][0]['browser_download_url'];
							document.body.appendChild(link);
							link.click();
							document.body.removeChild(link);
						});
					}else{
						$( '#myModal .modal-body' ).html("当前已经是最新版本<br/>版本号："+data['name']);
					}
				});
			},1000);
			$( '#myModal' ).modal( {
				backdrop: false
			} )
		}
		function fremotedownload(){
			$( "#loadModal" ).html('<?php loadModal(); ?>');
			$( '#myModal .modal-body' ).html("什么是远程下载？<br>远程下载是从其它服务器获取文件并直接下载到当前服务器的一种功能。<br>类似于SSH的Wget功能，免去我们下载再手动上传所浪费的时间。<select class='form-control' id='sel1'><option>.</option><?php foreach(traverseDir(".") as $v){echo "<option".($v==$dir?" selected='selected'":"").">{$v}</option>"; } ?></select><input type='text' class='form-control' id='usre' value=\"\" placeholder='请输入远程文件的下载地址'>");
			$( '#myModal .modal-title' ).text( "远程下载" ); 
			$( '#myModal .modal-footer .btn' ).text( "确定" ); 
			$( '#myModal .modal-footer .btn' ).attr("onclick","");
			$( '#myModal .modal-footer .btn' ).click(function(){
				var dirname=$('#sel1').val();
				var filename=$('input[type=text]#usre').val();
				var formData = new FormData();
				formData.append("username", "<?php echo $username;?>");
				formData.append("password", "<?php echo md5($password);?>");
				formData.append("op", "remotedownload");
				formData.append("dir", $('#sel1').val());
				formData.append("file",$('input[type=text]#usre').val());
				$.ajax({
					url: "<?php echo php_self;?>",
					type: "POST",
					cache: false,
					data: formData,
					processData: false,
					contentType: false,
					beforeSend: function(XHR){
						$( '#myModal .modal-body' ).html( "<div class=\"progress-bar progress-bar-success\" role=\"progressbar\" aria-valuenow=\"60\" aria-valuemin=\"0\" aria-valuemax=\"100\" style=\"width: 100%;\"><span class=\"sr-only\">0% 完成</span></div>" );
						$( 'button.close' ).hide();
						$( '#myModal .modal-footer .btn' ).hide();
						$( '#myModal' ).modal({keyboard: false,backdrop: false});
						$( '#myModal' ).modal('show');
					},
					complete: function(XHR, TS){
						$( "#main").html(XHR.responseText);
      				}
				});
			});
			$( '#myModal' ).modal( {
				backdrop: false
			} )
		}
		function logout(){
			history.replaceState(null, null, document.URL);
			location.reload(true);
		}
		function selectall() {
			$( '#filetable tbody tr' ).each( function () {
				if ( !$( this ).attr( "data-back" ) && !$( this ).hasClass( "active" ) ) {
					$( this ).addClass( "active" );
				}
			} );
			if($( '#filetable tbody tr.active:not([data-back])' ).length==$( '#filetable tbody tr:not([data-back])' ).length){
				$('.btn-group.operate button:gt(1)').removeClass('disabled');
				$('.btn-group.operate button:gt(1)').attr('disabled',false);
				$('.btn-group.operate button:eq(0)').addClass('disabled');
				$('.btn-group.operate button:eq(0)').attr('disabled','disabled');
			}
		}
		function zipfile() {
			var arr = "";
			$( '#filetable tr' ).filter( ".active" ).each( function () {
				arr += $( $( this ).find( "td" )[ 0 ] ).find( "input[type=hidden]" )[ 0 ].value.trim() + ",";
			} );
			arr = arr.substr( 0, arr.length - 1 );
			$( "#loadModal" ).html('<?php loadModal(); ?>');
			$( '#myModal .modal-body' ).html( "确定压缩以下文件或文件夹吗？<br>" + arr.replace( /,/g, "<br>" ) );
			$( '#myModal .modal-title' ).text( "压缩文件" );
			$( '#myModal .modal-footer .btn' ).text( "确定" );
			$( '#myModal .modal-footer .btn' ).attr( "onclick", "" );
			$( '#myModal .modal-footer .btn' ).click(function(){
				$.post( "<?php echo php_self;?>", {
					username: "<?php echo $username;?>",
					password: "<?php echo md5($password);?>",
					op: "zip",
					dir: "<?php echo $dir ?>",
					file:arr
				},
				function ( data, status ) {
					$( "#main" ).html( data );
				} );
			});
			$( '#myModal' ).modal( {
				backdrop: false
			} )
		}
		function fdelete() {
			var arr = "";
			$( '#filetable tr' ).filter( ".active" ).each( function () {
				arr += $( $( this ).find( "td" )[ 0 ] ).find( "input[type=hidden]" )[ 0 ].value.trim() + ",";
			} );
			arr = arr.substr( 0, arr.length - 1 );
			$( "#loadModal" ).html('<?php loadModal(); ?>');
			$( '#myModal .modal-body' ).html( "确定删除以下文件或文件夹吗？<br>" + arr.replace( /,/g, "<br>" ) );
			$( '#myModal .modal-title' ).text( "删除文件" );
			$( '#myModal .modal-footer .btn' ).text( "确定" );
			$( '#myModal .modal-footer .btn' ).attr( "onclick", "" );
			$( '#myModal .modal-footer .btn' ).click(function(){
				$.post( "<?php echo php_self;?>", {
					username: "<?php echo $username;?>",
					password: "<?php echo md5($password);?>",
					op: "del",
					dir: "<?php echo $dir ?>",
					file:arr
				},
				function ( data, status ) {
					$( "#main" ).html( data );
				} );
			});
			$( '#myModal' ).modal( {
				backdrop: false
			} )
		}
		function fcopy() {
			var arr = "";
			$( '#filetable tr' ).filter( ".active" ).each( function () {
				arr += $( $( this ).find( "td" )[ 0 ] ).find( "input[type=hidden]" )[ 0 ].value.trim() + ",";
			} );
			arr = arr.substr( 0, arr.length - 1 );
			$( "#loadModal" ).html('<?php loadModal(); ?>');
			$( '#myModal .modal-body' ).html( "将复制以下文件或文件夹到<select class=\"form-control\" id=\"sel1\"><option<?php echo $dir=='.'?" disabled='disabled'":""?>>.</option><?php foreach(traverseDir(".") as $v){echo "<option".($v==$dir?" disabled='disabled'":"").">{$v}</option>";}?></select><br>"+arr.replace(/,/g,"<br>"));
			$( '#myModal .modal-title' ).text( "复制文件" ); 
			$( '#myModal .modal-footer .btn' ).text( "确定" );
			$( '#myModal .modal-footer .btn' ).attr( "onclick", "" );
			$( '#myModal .modal-footer .btn' ).click(function(){
				$.post( "<?php echo php_self;?>", {
					username: "<?php echo $username;?>",
					password: "<?php echo md5($password);?>",
					op: "copy",
					dir: "<?php echo $dir ?>",
					file:arr,
					data:$( '#sel1' ).val()
				},
				function ( data, status ) {
					$( "#main" ).html( data );
				} );
			});
			$( '#myModal' ).modal( {
				backdrop: false
			} )
		}
		function fcut() {
			var arr = "";
			$( '#filetable tr' ).filter( ".active" ).each( function () {
				arr += $( $( this ).find( "td" )[ 0 ] ).find( "input[type=hidden]" )[ 0 ].value.trim() + ",";
			} );
			arr = arr.substr( 0, arr.length - 1 );
			$( "#loadModal" ).html('<?php loadModal(); ?>');
			$( '#myModal .modal-body' ).html( "将以下文件或文件夹移动到<select class=\"form-control\" id=\"sel1\"><option<?php echo $dir=='.'?" disabled='disabled'":""?>>.</option><?php foreach(traverseDir(".") as $v){echo "<option".($v==$dir?" disabled='disabled'":"").">{$v}</option>"; } ?></select><br>"+arr.replace(/,/g,"<br>"));
			$( '#myModal .modal-title' ).text( "移动文件" ); 
			$( '#myModal .modal-footer .btn' ).text( "确定" );  
			$( '#myModal .modal-footer .btn' ).attr( "onclick", "" );
			$( '#myModal .modal-footer .btn' ).click(function(){
				$.post( "<?php echo php_self;?>", {
					username: "<?php echo $username;?>",
					password: "<?php echo md5($password);?>",
					op: "cut",
					dir: "<?php echo $dir ?>",
					file:arr,
					data:$( '#sel1' ).val()
				},
				function ( data, status ) {
					$( "#main" ).html( data );
				} );
			});
			$( '#myModal' ).modal( {
				backdrop: false
			} )
		}
		function fchmod(){
			arr = "";
			$( '#filetable tr' ).filter( ".active" ).each( function () {
				arr += $( $( this ).find( "td" )[ 0 ] ).find( "input[type=hidden]" )[ 0 ].value.trim() + ",";
			} );
			arr = arr.substr( 0, arr.length - 1 );
			chmod1=0;
			chmod2=0;
			chmod3=0;
			chmod4=0;
			chmodstr = "";
			$( "#loadModal" ).html('<?php loadModal(); ?>');
			$('#myModal .modal-body').html("<table id='chmodtable' width='100%' border='0' cellspacing='0' cellpadding='0' align='center'><tbody><tr><td align='center' scope='col'>&nbsp;</td><td align='center' scope='col'>读</td><td align='center' scope='col'>写</td><td align='center' scope='col'>执行</td></tr><tr><td align='center' scope='row'>所有者</td><td align='center'><input type='checkbox' name='checkbox1' id='checkbox1' value='4'></td><td align='center'><input type='checkbox' name='checkbox2' id='checkbox2' value='2'></td><td align='center'><input type='checkbox' name='checkbox3' id='checkbox3' value='1'></td></tr><tr><td align='center' scope='row'>用户组</td><td align='center'><input type='checkbox' name='checkbox4' id='checkbox4' value='4'></td><td align='center'><input type='checkbox' name='checkbox5' id='checkbox5' value='2'></td><td align='center'><input type='checkbox' name='checkbox6' id='checkbox6' value='1'></td></tr><tr><td align='center' scope='row'>其它</td><td align='center'><input type='checkbox' name='checkbox7' id='checkbox7' value='4'></td><td align='center'><input type='checkbox' name='checkbox8' id='checkbox8' value='2'></td><td align='center'><input type='checkbox' name='checkbox9' id='checkbox9' value='1'></td></tr><tr><td colspan='4' align='center'>----特殊权限----</td></tr><tr><td align='center' scope='row'>&nbsp;</td><td align='center'><input type='checkbox' name='checkbox10' id='checkbox10' value='4'><label for='checkbox10'>设置GID </label></td><td align='center'><input type='checkbox' name='checkbox11' id='checkbox11' value='2'><label for='checkbox11'>设置UID </label></td><td align='center'><input type='checkbox' name='checkbox12' id='checkbox12' value='1'><label for='checkbox12'>粘滞 </label></td></tr><tr><td colspan='4' align='center'>&nbsp;</td></tr></tbody></table>"+arr.replace(/,/g,"<br>"));
			$( 'table#chmodtable tbody tr input[type=checkbox]' ).click( function () {
				switch($(this).parent().parent().index())
				{
					case 1:
						if($( this ).is( ":checked" )){
							chmod2+=parseInt($(this).attr("value"));	
						}else{
							chmod2-=parseInt($(this).attr("value"));
						}
						break;
					case 2:
						if($( this ).is( ":checked" )){
							chmod3+=parseInt($(this).attr("value"));	
						}else{
							chmod3-=parseInt($(this).attr("value"));
						}
						break;
					case 3:
						if($( this ).is( ":checked" )){
							chmod4+=parseInt($(this).attr("value"));	
						}else{
							chmod4-=parseInt($(this).attr("value"));
						}
						break;
					case 5:
						if($( this ).is( ":checked" )){
							chmod1+=parseInt($(this).attr("value"));	
						}else{
							chmod1-=parseInt($(this).attr("value"));
						}
						break;
				}
				chmodstr = chmod1.toString()+chmod2.toString()+chmod3.toString()+chmod4.toString()+"";
				$( 'table#chmodtable tbody tr:eq(6) td' ).html(chmodstr);
			} );
			chmodstr = chmod1.toString()+chmod2.toString()+chmod3.toString()+chmod4.toString()+"";
			$( '#myModal .modal-title' ).text( "修改权限" );
			$( '#myModal .modal-footer .btn' ).text( "确定" );
			$( '#myModal .modal-footer .btn' ).attr("onclick","");
			$( '#myModal .modal-footer .btn' ).click(function(){
				$.post( "<?php echo php_self;?>", {
					username: "<?php echo $username;?>",
					password: "<?php echo md5($password);?>",
					op: "chmod",
					dir: "<?php echo $dir ?>",
					file:arr,
					data:chmodstr
				},
				function ( data, status ) {
					$( "#main" ).html( data );
				} );
			});
			$( '#myModal' ).modal( {
				backdrop: false
			} )
		}
		function fcompare(){
			$( "#loadModal" ).html('<?php loadModal(); ?>');
			$( '#myModal .modal-body' ).html('<div id="edit_div_title" style="border-bottom: 1px solid #e5e5e5;"></div><div id="edit_div" style="overflow-y: scroll;"><div id="edit_div1" style="float:left;width:45%;overflow-wrap: break-word;"></div><div id="edit_div2" style="float:left;margin-left:10px;width:45%;overflow-wrap: break-word;"></div><div style="float:none;clear:both;"></div></div>');
			$('#edit_div').css('height',$(window).height()*0.65);
			$('#edit_div_title').html($($('#filetable tr').filter(".active").eq(0).find("td")[0]).find("input[type=hidden]")[0].value.trim()+"&nbsp;&nbsp;>&nbsp;&nbsp;"+$($('#filetable tr').filter(".active").eq(1).find("td")[0]).find("input[type=hidden]")[0].value.trim());
			$.ajaxSettings.async = false;
			$.post( "<?php echo php_self;?>", {
				username: "<?php echo $username;?>",
				password: "<?php echo md5($password);?>",
				op: "readfile",
				dir: "<?php echo $dir ?>",
				file:$($('#filetable tr').filter(".active").eq(0).find("td")[0]).find("input[type=hidden]")[0].value.trim()
			},
			function ( data, status ) {
				$('#edit_div1').html(data.string.replace(/\r\n/g,"<br/>"));
			},"json");
			$.post( "<?php echo php_self;?>", {
				username: "<?php echo $username;?>",
				password: "<?php echo md5($password);?>",
				op: "readfile",
				dir: "<?php echo $dir ?>",
				file:$($('#filetable tr').filter(".active").eq(1).find("td")[0]).find("input[type=hidden]")[0].value.trim()
			},
			function ( data, status ) {
				$('#edit_div2').html(data.string.replace(/\r\n/g,"<br/>"));
			},"json");
			var op = eq({ 
				value1: document.getElementById("edit_div1").innerHTML, 
				value2: document.getElementById("edit_div2").innerHTML 
			});
			document.getElementById("edit_div1").innerHTML=op.value1+"\r\n";
			document.getElementById("edit_div2").innerHTML=op.value2+"\r\n";
			$.ajaxSettings.async = true;
			$( '#myModal' ).modal( {
				backdrop: false
			} )
		}
		function fpreview( fname, op ) {
			<?php writelog("预览文件".$opendfile);?>
			switch ( op ) {
				case "edit":
					$( "#loadModal" ).html('<?php loadModal(); ?>');
					$.post( "<?php echo php_self;?>", {
						username: "<?php echo $username;?>",
						password: "<?php echo md5($password);?>",
						op: "previewedit",
						dir: "<?php echo $dir ?>",
						file:fname
					},
					function ( data, status ) {
						$( '#myModal .modal-body' ).html( "<div style='width:100%;height:400px;overflow:auto;'>"+data+"</div>");
					} );
					$( '#myModal .modal-footer .btn' ).text( "编辑" );
					$( '#myModal .modal-footer .btn' ).attr( "onclick", "fedit('<?php echo $dir ?>','"+fname+"')" );
					$( '#myModal' ).modal( {
						backdrop: false
					} )
					break;
				case "photo":
					$( "#loadModal" ).html('<?php loadModal(); ?>');
					$( '#myModal .modal-body' ).html( "<img src='<?php echo $dir.'/' ?>"+fname+"' class='img-thumbnail' style='width:100%;'>");
					$( '#myModal .modal-title' ).text( "查看图片" );
					$( '#myModal .modal-footer .btn' ).text( "查看原图" );
					$( '#myModal .modal-footer .btn' ).attr( "onclick", "window.open('<?php echo $dir.'/' ?>"+fname+"')" );
					$( '#myModal' ).modal( {
						backdrop: false
					} )
					break;
				case "music":
					$( "#loadModal" ).html('<?php loadModal(); ?>');
					$( '#myModal .close' ).click(function(){
						$( "#loadModal" ).html('');
					});
					$( '#myModal .modal-body' ).html( "<audio src='<?php echo $dir.'/' ?>"+fname+"' style='width:100%' controls='controls' preload='auto'>Your browser does not support the audio element.</audio>");
					$( '#myModal .modal-title' ).text( "播放音乐" );
					$( '#myModal .modal-footer .btn' ).text( "下载" );
					$( '#myModal .modal-footer .btn' ).attr( "onclick", "fdownload('<?php echo $dir ?>',fname)");
					$( '#myModal' ).modal( {
						backdrop: false
					} )
					break;
				case "film":
					$( "#loadModal" ).html('<?php loadModal(); ?>');
					$( '#myModal .close' ).click(function(){
						$( "#loadModal" ).html('');
					});
					$( '#myModal .modal-body' ).html( "<video src='<?php echo $dir.'/' ?>"+fname+"' style='width:100%' controls='controls' preload='auto'>Your browser does not support the video element.</video>");
					$( '#myModal .modal-title' ).text( "播放视频" );
					$( '#myModal .modal-footer .btn' ).text( "下载" );
					$( '#myModal .modal-footer .btn' ).attr( "onclick", "fdownload('<?php echo $dir ?>',fname)");
					$( '#myModal' ).modal( {
						backdrop: false
					} )
					break;
				case "download":
					$.post( "<?php echo php_self;?>", {
						username: "<?php echo $username;?>",
						password: "<?php echo md5($password);?>",
						op: "download",
						dir: "<?php echo $dir ?>",
						file:fname
					},
					function ( data, status ) {
						if ('msSaveOrOpenBlob' in navigator){
							window.navigator.msSaveOrOpenBlob(new Blob([data]), '<?php echo php_self.'/'.$dir.'/' ?>'+fname);
						}else{
						   	var url = window.URL.createObjectURL(new Blob([data], { type: "application/octet-stream" }));
						   	var link = document.createElement('a');
						   	link.style.display = 'none';
							link.href = url;
						   	link.setAttribute('download', fname);
						   	document.body.appendChild(link);
							link.click();
							document.body.removeChild(link);
						}
					} );
					break;
				case "gift":
					$( "#loadModal" ).html('<?php loadModal(); ?>');
					$.post( "<?php echo php_self;?>", {
						username: "<?php echo $username;?>",
						password: "<?php echo md5($password);?>",
						op: "pzip",
						dir: "<?php echo $dir ?>",
						file:fname
					},
					function ( data, status ) {
						$( '#myModal .modal-body' ).html(data);
					} );
					$( '#myModal .modal-footer .btn' ).text( "解压" );
					$( '#myModal .modal-footer .btn' ).attr("onclick","");
					$( '#myModal .modal-footer .btn' ).click(function(){
						unarchive2("<?php echo $dir;?>",fname);
					});
					$( '#myModal' ).modal( {
						backdrop: false
					} )
					break;
				case "eye":
					window.open("https://view.officeapps.live.com/op/view.aspx?src=<?php echo $_SERVER['SERVER_NAME'].'/'.$dir.'/'.$file ?>");
					break;
			}
		}
		function fdownload(dirname, filename){
			$.post( "<?php echo php_self;?>", {
				username: "<?php echo $username;?>",
				password: "<?php echo md5($password);?>",
				op: "download",
				dir: dirname,
				file:filename
			},
			function ( data, status ) {
				if ('msSaveOrOpenBlob' in navigator){
					window.navigator.msSaveOrOpenBlob(new Blob([data]), '<?php echo php_self.'/' ?>'+dirname+'/'+filename);
				}else{
				   	var url = window.URL.createObjectURL(new Blob([data], { type: "application/octet-stream" }));
				   	var link = document.createElement('a');
				   	link.style.display = 'none';
					link.href = url;
				   	link.setAttribute('download', fname);
				   	document.body.appendChild(link);
					link.click();
					document.body.removeChild(link);
				}
			} );
		}
		function fimg(dirname, filename){
			$( "#loadModal" ).html('<?php loadModal(); ?>');
			$( '#myModal .modal-body' ).html( "<img src='"+dirname+"/"+filename+"' class='img-thumbnail' style='width:100%;'>");
			$( '#myModal .modal-title' ).text( "查看图片" );
			$( '#myModal .modal-footer .btn' ).text( "查看原图" );
			$( '#myModal .modal-footer .btn' ).attr( "onclick", "window.open('"+dirname+"/"+filename+"')" );
			$( '#myModal' ).modal( {
				backdrop: false
			} )
		}
		function unarchive(dirname, filename){
			$( "#loadModal" ).html('<?php loadModal(); ?>');
			$.post( "<?php echo php_self;?>", {
				username: "<?php echo $username;?>",
				password: "<?php echo md5($password);?>",
				op: "pzip",
				dir: dirname,
				file:filename
			},
			function ( data, status ) {
				$( '#myModal .modal-body' ).html(data);
			} );
			$( '#myModal .modal-footer .btn' ).text( "解压" );
			$( '#myModal .modal-footer .btn' ).attr("onclick","");
			$( '#myModal .modal-footer .btn' ).click(function(){
				unarchive2(dirname, filename);
			});
			$( '#myModal' ).modal( {
				backdrop: false
			} )
		}
		function unarchive2(dirname, filename){
			$.post( "<?php echo php_self;?>", {
						username: "<?php echo $username;?>",
						password: "<?php echo md5($password);?>",
						op: "unarchive",
						dir: dirname,
						file:filename
					},
					function ( data, status ) {
						$( "#loadModal").html( data );
					} );
		}
		function playmusic(dirname, filename){
			$( "#loadModal" ).html('<?php loadModal(); ?>');
					$( '#myModal .close' ).click(function(){
						$( "#loadModal" ).html('');
					});
					$( '#myModal .modal-body' ).html( "<audio src='"+dirname+"/"+filename+"' style='width:100%' controls='controls' preload='auto'>Your browser does not support the audio element.</audio>");
					$( '#myModal .modal-title' ).text( "播放音乐" );
					$( '#myModal .modal-footer .btn' ).text( "下载" );
					$( '#myModal .modal-footer .btn' ).attr( "onclick", "fdownload('<?php echo $dir ?>',fname)");
					$( '#myModal' ).modal( {
						backdrop: false
					} )
		}
		function playfilm(dirname, filename){
			$( "#loadModal" ).html('<?php loadModal(); ?>');
			$( '#myModal .close' ).click(function(){
				$( "#loadModal" ).html('');
			});
			$( '#myModal .modal-body' ).html( "<video src='"+dirname+"/"+filename+"' style='width:100%' controls='controls' preload='auto'>Your browser does not support the video element.</video>");
			$( '#myModal .modal-title' ).text( "播放视频" );
			$( '#myModal .modal-footer .btn' ).text( "下载" );
			$( '#myModal .modal-footer .btn' ).attr( "onclick", "fdownload('<?php echo $dir ?>',fname)");
			$( '#myModal' ).modal( {
				backdrop: false
			} )
		}
		function fedit(dirname, filename){
			$( "#loadModal" ).html('<?php loadModal(); ?>');
			$.post( "<?php echo php_self;?>", {
				username: "<?php echo $username;?>",
				password: "<?php echo md5($password);?>",
				op: "readfile",
				dir: dirname,
				file:filename
			},
			function ( data, status ) {
				$( '#myModal .modal-body' ).html("<form id=\"fileform\"><input type=\"text\" class=\"form-control\" value=\""+filename+"\" id=\"usr\" disabled><input type=\"text\" name=\"code\" id=\"code\" value=\"\"><label class=\"form-check-label\"><input type=\"checkbox\" class=\"form-check-input\" checked=\"checked\" id=\"autowrap\">自动换行</label><br><div id=\"textareadiv\" style=\"position: relative;\"><textarea style=\"position: absolute;top: 0;left: 0; resize: none;\" class=\"form-control\" rows=\"12\" id=\"comment\" name=\"data\"></textarea><textarea style=\"position: absolute;top: 1px;left: 1px;font-size: 14px;resize: none;overflow: hidden;padding:6px 0;border:none;\" rows=\"12\" id=\"commentline\" wrap=\"off\" readonly disabled></textarea></div></form>");
				$('#code').val(data.code);
				$('#comment').html(data.string);
				fedit2();
			},"json" );
			$( '#myModal .modal-title' ).text( "编辑文件" );
			$( '#myModal .modal-footer .btn' ).text( "保存" );
			$( '#myModal .modal-footer .btn' ).attr( "onclick", "" );
			$( '#myModal .modal-footer .btn' ).click(function(){
				var tmpJson={};
				tmpJson.code=$('#code').val();
				tmpJson.string=$('#comment').val();
				$( "#loadModal" ).html('<?php loadModal(); ?>');
				$.post( "<?php echo php_self;?>", {
					username: "<?php echo $username;?>",
					password: "<?php echo md5($password);?>",
					op: "save",
					dir: dirname,
					file:filename,
					data:JSON.stringify(tmpJson)
				},
				function ( data, status ) {
					$( '#loadModal' ).html(data);
				});
			});
			$('#myModal').on('hidden.bs.modal', function () {
				$('body').css('padding-right',parseInt($('body').css('padding-right').replace('px',''))-17+'px');//修复Modal组件被连续调用之后，右间距无法恢复的问题
			})
			$( '#myModal' ).modal( {
				backdrop: false
			} )
		}
		function fedit2(){
			$( '#autowrap' ).click( function () {
				if ( $( this ).is( ":checked" ) ) {
					$( '#comment' ).attr( "wrap", "virtual" ); // style="overflow:scroll;"
					$( '#commentline' ).attr( "wrap", "virtual" );
				} else {
					$( '#comment' ).attr( "wrap", "off" );
					$( '#commentlline' ).attr( "wrap", "off" );
				}
				$( '#textareadiv' ).css("height",$( '#comment' ).css("height"));//将textarea的父容器高度设置为textarea的高度，不然弹出的对话框会变形
			} );
			$('#comment').bind( 'input propertychange',function(){
				var lines = $('#comment').val().split("\n").length;//计算总行数
				$('#commentline').val('');
				for(var i=1;i<=lines;i++){
					$('#commentline').val($('#commentline').val()+i+"\r\n");//逐行输出行数
				}
				$('#commentline').attr("cols",lines.toString().split("").length);//设置显示行数的文本框宽度自适应
				$('#comment').css("padding-left",$('#commentline').css("width"));//设置显示内容的文本框左边空出位置以显示行数
			});
			if($('#commentline')){
				$( '#commentline' ).css("height",parseInt($( '#comment' ).css("height").replace("px",""))-2+"px");//显示行数的文本框高度为显示内容的文本框高度减去二
				$( '#textareadiv' ).css("height",$( '#comment' ).css("height"));//将textarea的父容器高度设置为textarea的高度，不然弹出的对话框会变形
				var lines = $('#comment').val().split("\n").length;//计算总行数
				for(var i=1;i<=lines;i++){
					$('#commentline').val($('#commentline').val()+i+"\r\n");//逐行输出行数
				}
				$('#commentline').attr("cols",lines.toString().split("").length);//设置显示行数的文本框宽度自适应
				$('#comment').css("padding-left",$('#commentline').css("width"));//设置显示内容的文本框左边空出位置以显示行数
			}
			$('#comment').scroll(function(){
				$('#commentline').scrollTop($(this).scrollTop());
			});
		}
		function office(dirname, filename){
			window.open("https://view.officeapps.live.com/op/view.aspx?src=<?php echo $_SERVER['SERVER_NAME'];?>/"+dirname+"/"+filename);
		}
		function sort(dirname, ordername, sortname){
			$.post( "<?php echo php_self;?>", {
					username: "<?php echo $username;?>",
					password: "<?php echo md5($password);?>",
					op: "showfilelist",
					dir: dirname,
					order: ordername,
					sort: sortname
				},
				function ( data, status ) {
					$( "#main" ).html( data );
				} );
		}
		function eq(op) {
                if(!op){
                    return op;
                }
                if(!op.value1_style){
                    op.value1_style="background-color:#FEC8C8;";
                }
                if(!op.value2_style){
                    op.value2_style="background-color:#FEC8C8;";
                }
                if(!op.eq_min){
                    op.eq_min=3;
                }
                if(!op.eq_index){
                    op.eq_index=5;
                }
                if (!op.value1 || !op.value2) {
                    return op;
                }
                var ps = {
                    v1_i: 0,
                    v1_new_value: "",
                    v2_i: 0,
                    v2_new_value: ""
                };
                while (ps.v1_i < op.value1.length && ps.v2_i < op.value2.length) {
                    if (op.value1[ps.v1_i] == op.value2[ps.v2_i]) {
                        ps.v1_new_value += op.value1[ps.v1_i].replace(/</g,"<").replace(">",">");
                        ps.v2_new_value += op.value2[ps.v2_i].replace(/</g,"<").replace(">",">");
                        ps.v1_i += 1;
                        ps.v2_i += 1;
                        if (ps.v1_i >= op.value1.length) {
                            ps.v2_new_value += "<span style='" + op.value2_style + "'>" + op.value2.substr(ps.v2_i).replace(/</g,"<").replace(">",">") + "</span>";
                            break;
                        }
                        if (ps.v2_i >= op.value2.length) {
                            ps.v1_new_value += "<span style='" + op.value1_style + "'>" + op.value1.substr(ps.v1_i).replace(/</g,"<").replace(">",">") + "</span>";
                            break;
                        }
                    } else {
                        ps.v1_index = ps.v1_i + 1;
                        ps.v1_eq_length = 0;
                        ps.v1_eq_max = 0;
                        ps.v1_start = ps.v1_i + 1;
                        while (ps.v1_index < op.value1.length) {
                            if (op.value1[ps.v1_index] == op.value2[ps.v2_i + ps.v1_eq_length]) {
                                ps.v1_eq_length += 1;
                            } else if (ps.v1_eq_length > 0) {
                                if (ps.v1_eq_max < ps.v1_eq_length) {
                                    ps.v1_eq_max = ps.v1_eq_length;
                                    ps.v1_start = ps.v1_index - ps.v1_eq_length;
                                }
                                ps.v1_eq_length = 0;
                                break;//只寻找最近的
                            }
                            ps.v1_index += 1;
                        }
                        if (ps.v1_eq_max < ps.v1_eq_length) {
                            ps.v1_eq_max = ps.v1_eq_length;
                            ps.v1_start = ps.v1_index - ps.v1_eq_length;
                        }
 
                        ps.v2_index = ps.v2_i + 1;
                        ps.v2_eq_length = 0;
                        ps.v2_eq_max = 0;
                        ps.v2_start = ps.v2_i + 1;
                        while (ps.v2_index < op.value2.length) {
                            if (op.value2[ps.v2_index] == op.value1[ps.v1_i + ps.v2_eq_length]) {
                                ps.v2_eq_length += 1;
                            } else if (ps.v2_eq_length > 0) {
                                if (ps.v2_eq_max < ps.v2_eq_length) {
                                    ps.v2_eq_max = ps.v2_eq_length;
                                    ps.v2_start = ps.v2_index - ps.v2_eq_length;
                                }
                                ps.v1_eq_length = 0;
                                break;//只寻找最近的
                            }
                            ps.v2_index += 1;
                        }
                        if (ps.v2_eq_max < ps.v2_eq_length) {
                            ps.v2_eq_max = ps.v2_eq_length;
                            ps.v2_start = ps.v2_index - ps.v2_eq_length;
                        }
                        if (ps.v1_eq_max < op.eq_min && ps.v1_start - ps.v1_i > op.eq_index) {
                            ps.v1_eq_max = 0;
                        }
                        if (ps.v2_eq_max < op.eq_min && ps.v2_start - ps.v2_i > op.eq_index) {
                            ps.v2_eq_max = 0;
                        }
                        if ((ps.v1_eq_max == 0 && ps.v2_eq_max == 0)) {
                            ps.v1_new_value += "<span style='" + op.value1_style + "'>" + op.value1[ps.v1_i].replace(/</g,"<").replace(">",">") + "</span>";
                            ps.v2_new_value += "<span style='" + op.value2_style + "'>" + op.value2[ps.v2_i].replace(/</g,"<").replace(">",">") + "</span>";
                            ps.v1_i += 1;
                            ps.v2_i += 1;
 
                            if (ps.v1_i >= op.value1.length) {
                                ps.v2_new_value += "<span style='" + op.value2_style + "'>" + op.value2.substr(ps.v2_i).replace(/</g,"<").replace(">",">") + "</span>";
                                break;
                            }
                            if (ps.v2_i >= op.value2.length) {
                                ps.v1_new_value += "<span style='" + op.value1_style + "'>" + op.value1.substr(ps.v1_i).replace(/</g,"<").replace(">",">") + "</span>";
                                break;
                            }
                        } else if (ps.v1_eq_max > ps.v2_eq_max) {
                            ps.v1_new_value += "<span style='" + op.value1_style + "'>" + op.value1.substr(ps.v1_i, ps.v1_start - ps.v1_i).replace(/</g,"<").replace(">",">") + "</span>";
                            ps.v1_i = ps.v1_start;
                        } else {
                            ps.v2_new_value += "<span style='" + op.value2_style + "'>" + op.value2.substr(ps.v2_i, ps.v2_start - ps.v2_i).replace(/</g,"<").replace(">",">") + "</span>";
                            ps.v2_i = ps.v2_start;
                        }
                    }
                }
                op.value1 = ps.v1_new_value;
                op.value2 = ps.v2_new_value;
                return op;
            }
	</script>
	<?php
}
?>
<?php
if ( !isset( $_POST[ 'username' ] ) ||
	 !isset( $_POST[ 'password' ] ) || 
	 ( htmlspecialchars( $_POST[ 'username' ] ) != $username ) || 
	 ( htmlspecialchars( $_POST[ 'password' ] ) != md5($password) ) ) {
	//检测出未登录。或者是直接传送操作数据，没有用户名密码，屏蔽恶意攻击或篡改系统
	maintop();
	?>
	<form class="form-signin" method="post">
		<h2 class="form-signin-heading">登录</h2>
		<label for="username" class="sr-only">用户名</label>
		<input type="text" id="username" class="form-control" name="username" <?php if(isset($_COOKIE[ 'username'])){echo ' value="'.$_COOKIE[ 'username']. '"';}?> placeholder="请输入用户名" required autofocus>
		<label for="password" class="sr-only">密码</label>
		<input type="password" id="password" class="form-control" name="password" <?php if(isset($_COOKIE[ 'password'])){echo ' value="'.$_COOKIE[ 'password']. '"';}?> placeholder="请输入密码" required>
		<div class="checkbox">
			<label>
	            <input type="checkbox" id="remember-me" name="remember-me"<?php if(isset($_COOKIE['username'])||isset($_COOKIE['password'])){echo ' checked="checked"';}?>> 记住我
	          </label>
		
		</div>
		<button class="btn btn-lg btn-primary btn-block" type="submit">登录</button>
	</form>
	<script>
	var str="";
		$('#password').focus(function(){
			str=$(this).val();
		});
		$('#password').blur(function(){
			if(str!=$(this).val()){
				$(this).val(MD5($(this).val()));
			}
		});
		$('#password').keypress(function(event){
			var keycode = (event.keyCode ? event.keyCode : event.which);
			if(keycode == '13'){
				$(this).val(MD5($(this).val()));
			}
		});
		
var MD5 = function (string) {
 function RotateLeft(lValue, iShiftBits) {
  return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits));
 }
 function AddUnsigned(lX,lY) {
  var lX4,lY4,lX8,lY8,lResult;
  lX8 = (lX & 0x80000000);
  lY8 = (lY & 0x80000000);
  lX4 = (lX & 0x40000000);
  lY4 = (lY & 0x40000000);
  lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF);
  if (lX4 & lY4) {
   return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
  }
  if (lX4 | lY4) {
   if (lResult & 0x40000000) {
    return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
   } else {
    return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
   }
  } else {
   return (lResult ^ lX8 ^ lY8);
  }
  }
  function F(x,y,z) { return (x & y) | ((~x) & z); }
  function G(x,y,z) { return (x & z) | (y & (~z)); }
  function H(x,y,z) { return (x ^ y ^ z); }
 function I(x,y,z) { return (y ^ (x | (~z))); }
 function FF(a,b,c,d,x,s,ac) {
  a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
  return AddUnsigned(RotateLeft(a, s), b);
 };
 function GG(a,b,c,d,x,s,ac) {
  a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
  return AddUnsigned(RotateLeft(a, s), b);
 };
 function HH(a,b,c,d,x,s,ac) {
  a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
  return AddUnsigned(RotateLeft(a, s), b);
 };
 function II(a,b,c,d,x,s,ac) {
  a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
  return AddUnsigned(RotateLeft(a, s), b);
 };
 function ConvertToWordArray(string) {
  var lWordCount;
  var lMessageLength = string.length;
  var lNumberOfWords_temp1=lMessageLength + 8;
  var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64;
  var lNumberOfWords = (lNumberOfWords_temp2+1)*16;
  var lWordArray=Array(lNumberOfWords-1);
  var lBytePosition = 0;
  var lByteCount = 0;
  while ( lByteCount < lMessageLength ) {
   lWordCount = (lByteCount-(lByteCount % 4))/4;
   lBytePosition = (lByteCount % 4)*8;
   lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount)<<lBytePosition));
   lByteCount++;
  }
  lWordCount = (lByteCount-(lByteCount % 4))/4;
  lBytePosition = (lByteCount % 4)*8;
  lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition);
  lWordArray[lNumberOfWords-2] = lMessageLength<<3;
  lWordArray[lNumberOfWords-1] = lMessageLength>>>29;
  return lWordArray;
 };
 function WordToHex(lValue) {
  var WordToHexValue="",WordToHexValue_temp="",lByte,lCount;
  for (lCount = 0;lCount<=3;lCount++) {
   lByte = (lValue>>>(lCount*8)) & 255;
   WordToHexValue_temp = "0" + lByte.toString(16);
   WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length-2,2);
  }
  return WordToHexValue;
 };
 function Utf8Encode(string) {
  string = string.replace(/\r\n/g,"\n");
  var utftext = "";
  for (var n = 0; n < string.length; n++) {
   var c = string.charCodeAt(n);
   if (c < 128) {
    utftext += String.fromCharCode(c);
   }
   else if((c > 127) && (c < 2048)) {
    utftext += String.fromCharCode((c >> 6) | 192);
    utftext += String.fromCharCode((c & 63) | 128);
   }
   else {
    utftext += String.fromCharCode((c >> 12) | 224);
    utftext += String.fromCharCode(((c >> 6) & 63) | 128);
    utftext += String.fromCharCode((c & 63) | 128);
   }
  }
  return utftext;
 };
 var x=Array();
 var k,AA,BB,CC,DD,a,b,c,d;
 var S11=7, S12=12, S13=17, S14=22;
 var S21=5, S22=9 , S23=14, S24=20;
 var S31=4, S32=11, S33=16, S34=23;
 var S41=6, S42=10, S43=15, S44=21;
 string = Utf8Encode(string);
 x = ConvertToWordArray(string);
 a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;
 for (k=0;k<x.length;k+=16) {
  AA=a; BB=b; CC=c; DD=d;
  a=FF(a,b,c,d,x[k+0], S11,0xD76AA478);
  d=FF(d,a,b,c,x[k+1], S12,0xE8C7B756);
  c=FF(c,d,a,b,x[k+2], S13,0x242070DB);
  b=FF(b,c,d,a,x[k+3], S14,0xC1BDCEEE);
  a=FF(a,b,c,d,x[k+4], S11,0xF57C0FAF);
  d=FF(d,a,b,c,x[k+5], S12,0x4787C62A);
  c=FF(c,d,a,b,x[k+6], S13,0xA8304613);
  b=FF(b,c,d,a,x[k+7], S14,0xFD469501);
  a=FF(a,b,c,d,x[k+8], S11,0x698098D8);
  d=FF(d,a,b,c,x[k+9], S12,0x8B44F7AF);
  c=FF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);
  b=FF(b,c,d,a,x[k+11],S14,0x895CD7BE);
  a=FF(a,b,c,d,x[k+12],S11,0x6B901122);
  d=FF(d,a,b,c,x[k+13],S12,0xFD987193);
  c=FF(c,d,a,b,x[k+14],S13,0xA679438E);
  b=FF(b,c,d,a,x[k+15],S14,0x49B40821);
  a=GG(a,b,c,d,x[k+1], S21,0xF61E2562);
  d=GG(d,a,b,c,x[k+6], S22,0xC040B340);
  c=GG(c,d,a,b,x[k+11],S23,0x265E5A51);
  b=GG(b,c,d,a,x[k+0], S24,0xE9B6C7AA);
  a=GG(a,b,c,d,x[k+5], S21,0xD62F105D);
  d=GG(d,a,b,c,x[k+10],S22,0x2441453);
  c=GG(c,d,a,b,x[k+15],S23,0xD8A1E681);
  b=GG(b,c,d,a,x[k+4], S24,0xE7D3FBC8);
  a=GG(a,b,c,d,x[k+9], S21,0x21E1CDE6);
  d=GG(d,a,b,c,x[k+14],S22,0xC33707D6);
  c=GG(c,d,a,b,x[k+3], S23,0xF4D50D87);
  b=GG(b,c,d,a,x[k+8], S24,0x455A14ED);
  a=GG(a,b,c,d,x[k+13],S21,0xA9E3E905);
  d=GG(d,a,b,c,x[k+2], S22,0xFCEFA3F8);
  c=GG(c,d,a,b,x[k+7], S23,0x676F02D9);
  b=GG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);
  a=HH(a,b,c,d,x[k+5], S31,0xFFFA3942);
  d=HH(d,a,b,c,x[k+8], S32,0x8771F681);
  c=HH(c,d,a,b,x[k+11],S33,0x6D9D6122);
  b=HH(b,c,d,a,x[k+14],S34,0xFDE5380C);
  a=HH(a,b,c,d,x[k+1], S31,0xA4BEEA44);
  d=HH(d,a,b,c,x[k+4], S32,0x4BDECFA9);
  c=HH(c,d,a,b,x[k+7], S33,0xF6BB4B60);
  b=HH(b,c,d,a,x[k+10],S34,0xBEBFBC70);
  a=HH(a,b,c,d,x[k+13],S31,0x289B7EC6);
  d=HH(d,a,b,c,x[k+0], S32,0xEAA127FA);
  c=HH(c,d,a,b,x[k+3], S33,0xD4EF3085);
  b=HH(b,c,d,a,x[k+6], S34,0x4881D05);
  a=HH(a,b,c,d,x[k+9], S31,0xD9D4D039);
  d=HH(d,a,b,c,x[k+12],S32,0xE6DB99E5);
  c=HH(c,d,a,b,x[k+15],S33,0x1FA27CF8);
  b=HH(b,c,d,a,x[k+2], S34,0xC4AC5665);
  a=II(a,b,c,d,x[k+0], S41,0xF4292244);
  d=II(d,a,b,c,x[k+7], S42,0x432AFF97);
  c=II(c,d,a,b,x[k+14],S43,0xAB9423A7);
  b=II(b,c,d,a,x[k+5], S44,0xFC93A039);
  a=II(a,b,c,d,x[k+12],S41,0x655B59C3);
  d=II(d,a,b,c,x[k+3], S42,0x8F0CCC92);
  c=II(c,d,a,b,x[k+10],S43,0xFFEFF47D);
  b=II(b,c,d,a,x[k+1], S44,0x85845DD1);
  a=II(a,b,c,d,x[k+8], S41,0x6FA87E4F);
  d=II(d,a,b,c,x[k+15],S42,0xFE2CE6E0);
  c=II(c,d,a,b,x[k+6], S43,0xA3014314);
  b=II(b,c,d,a,x[k+13],S44,0x4E0811A1);
  a=II(a,b,c,d,x[k+4], S41,0xF7537E82);
  d=II(d,a,b,c,x[k+11],S42,0xBD3AF235);
  c=II(c,d,a,b,x[k+2], S43,0x2AD7D2BB);
  b=II(b,c,d,a,x[k+9], S44,0xEB86D391);
  a=AddUnsigned(a,AA);
  b=AddUnsigned(b,BB);
  c=AddUnsigned(c,CC);
  d=AddUnsigned(d,DD);
 }
 var temp = WordToHex(a)+WordToHex(b)+WordToHex(c)+WordToHex(d);
 return temp.toLowerCase();
}
	</script>
	<?php
	mainbottom();
	exit;
} else { //已经传进来正确的用户名和密码
	if ( isset( $_POST[ 'op' ] ) && $_POST[ 'op' ] != '' ) {
		//如果接收到op，则表示接收ajax请求，直接返回操作结果
		switch ( $_POST[ 'op' ] ) {
			case 'showfilelist':
				showFileList( $dir );
				loadScript();
				break;
			case 'rename':
				$msg=frename($dir.'/'.$opendfile,$dir.'/'.$extradata);
				break;
			case 'create':
				$msg=fcreate( $dir, $opendfile, $extradata );
				break;
			case 'upload':
				$msg=fupload($dir);
				break;
			case 'remotedownload':
				$dirarr = explode( '/', $opendfile );
				$targetfile = $dirarr[ count( $dirarr ) - 1 ];
				ignore_user_abort(true);
				set_time_limit(24*60*60);
				$ch = curl_init();
				$timeout = 50;
				curl_setopt($ch, CURLOPT_URL, $opendfile);
				curl_setopt($ch, CURLOPT_HEADER, 0);
				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
				//curl_setopt($ch, CURLOPT_NOPROGRESS, false);
				//curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, "downloadProgress_callback");
				curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
				curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
				curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
				$content = curl_exec($ch);
				curl_close($ch);
				writelog("远程下载文件".$opendfile);
				$msg.=fedit($dir.'/'.$targetfile,$content);
				break;
			case 'zip':
				$msg=archivefile($dir.'/'.date("Ymdhis").'.zip', $opendfile);
				break;
			case 'del':
				foreach ( explode( ',', $opendfile ) as $v ) {
					$msg .= fremove( $dir . '/' . $v );
				}
				break;
			case 'copy':
				foreach ( explode( ',', $opendfile ) as $v ) {
					$dirarr = explode( '/', $dir . '/' . $v );
					$targetdir = $dirarr[ count( $dirarr ) - 1 ];
					$msg .= fcopy( $dir . '/' . $v, $extradata . '/', $targetdir );
				}
				break;
			case 'cut':
				foreach ( explode( ',', $opendfile ) as $v ) {
					$dirarr = explode( '/', $dir . '/' . $v );
					$targetdir = $dirarr[ count( $dirarr ) - 1 ];
					$msg .= fcut( $dir . '/' . $v, $extradata . '/', $targetdir );
				}
				break;
			case 'chmod':
				foreach ( explode( ',', $opendfile ) as $v ) {
					$dirarr = explode( '/', $dir . '/' . $v );
					$targetdir = $dirarr[ count( $dirarr ) - 1 ];
					$msg .= fchmod( $dir . '/' . $v, $extradata);
				}
				break;
			case 'previewedit':
				echo str_replace(["\n","\r","\""], [ "", "", "'"], encode(highlight_file( $dir.'/'.$opendfile, true ) ))["string"];
				break;
			case 'download':
				if(!file_exists($dir.'/'.$opendfile)){
					header('HTTP/1.1 404 NOT FOUND');
				}else{
					Header("Content-type: application/octet-stream");
					Header("Accept-Ranges: bytes");
					Header("Accept-Length: ".filesize($dir.'/'.$opendfile));
					Header("Content-Disposition: attachment; filename=".$file_name);
					Header("Content-Transfer-Encoding: binary"); 
					echo file_get_contents($dir.'/'.$opendfile);
				}
				break;
			case 'pzip':
				echo fPreviewArchive($dir . '/' . $opendfile);
				break;
			case 'unarchive':
				$msg = fUnArchive($dir, $opendfile);
				break;
			case 'readfile':
				echo json_encode(freadfile($dir.'/'.$opendfile));
				break;
			case 'save':
				$extradata= json_decode($extradata,true);
				$msg=fedit( $dir . '/' . $opendfile, decode($extradata['string'], $extradata['code']));
				break;
			case 'batchrename':
				$opendfile_arr=explode( ',', $opendfile );
				$extradata_arr=explode( ',', $extradata );
				for($i=0;$i<sizeof($opendfile_arr);$i++){
					$msg.=frename($dir.'/'.$opendfile_arr[$i], $dir.'/'.$extradata_arr[$i]).'<br>';
				}
				break;
		}
		if(isset($msg) && $msg!=''){
			?>
			<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
				<div class="modal-dialog">
					<div class="modal-content">
						<div class="modal-header">
							<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
							<h4 class="modal-title" id="myModalLabel">系统提示</h4>
						</div>
						<div class="modal-body">
							系统提示消息
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-secondary" data-dismiss="modal" aria-hidden="true">确定</button>
						</div>
					</div><!-- /.modal-content -->
				</div><!-- /.modal -->
			</div>
			<script>
			$( '#myModal .modal-body' ).html( "<?php echo $msg; ?>" );
			$( '#myModal .modal-title' ).text( "系统提示" );
			$( '#myModal .close' ).hide();
			<?php if(isset($jsop)&&$jsop!=''){?>
			$('#myModal').on('hide.bs.modal', function () {
				<?php echo $jsop;?>
			})
			<?php }?>
			$('#myModal').on('hidden.bs.modal', function () {
				$( "#loadModal").html("");
  				opendir('<?php echo $dir;?>');
			})
			$( '#myModal' ).modal( {
				backdrop: false,
				show:false
			} )
			$('#myModal').modal('show');
			</script>
			<?php
		}
		exit;
	}
	//如果不是ajax请求，则正常显示界面
	if(isset($_POST['remember-me'])){
		setcookie('username',$_POST[ 'username' ]);
		setcookie('password',md5($_POST[ 'password' ]));
	}else{
		setcookie('username','',time()-3600);
		setcookie('password','',time()-3600);
	}
	$showNavbar = true;
	maintop();
	?>
	<div id="main">
		<?php
		showFileList( $dir );
		loadScript();
		?>
	</div>
	<?php
	mainbottom();
}
?>