diff --git a/BT-Panel b/BT-Panel index f604a709..00e939dd 100644 --- a/BT-Panel +++ b/BT-Panel @@ -10,14 +10,79 @@ from gevent import monkey monkey.patch_all() import os,sys,ssl -if os.path.exists("/www/server/panel/class/BTPanel"): - os.system("rm -rf /www/server/panel/class/BTPanel") -os.chdir('/www/server/panel') +_PATH = '/www/server/panel' +os.chdir(_PATH) if not 'class/' in sys.path: sys.path.insert(0,'class/') from BTPanel import app,sys,public +is_debug = os.path.exists('data/debug.pl') + +if is_debug: + import pyinotify,time,logging,re + logging.basicConfig(level=logging.DEBUG,format="[%(asctime)s][%(levelname)s] - %(message)s") + logger = logging.getLogger() + + class PanelEventHandler(pyinotify.ProcessEvent): + _exts = ['py','html','BT-Panel','so'] + _explude_patts = [ + re.compile('{}/plugin/.+'.format(_PATH)), + re.compile('{}/(tmp|temp)/.+'.format(_PATH)) + ] + _lsat_time = 0 + + + def is_ext(self,filename): + fname = os.path.basename(filename) + result = fname.split('.')[-1] in self._exts + if not result: return False + for e in self._explude_patts: + if e.match(filename): return False + return True + + def panel_reload(self,filename,in_type): + stime = time.time() + if stime - self._lsat_time < 2: + return + self._lsat_time = stime + logger.debug('File detected: {} -> {}'.format(filename,in_type)) + + fname = os.path.basename(filename) + if fname in ['task.py','BT-Task']: + logger.debug('Background task...') + public.ExecShell("{} {}/BT-Task".format(public.get_python_bin(),_PATH)) + logger.debug('Background task started!') + else: + logger.debug('Restarting panel...') + public.ExecShell("bash {}/init.sh reload &>/dev/null &".format(_PATH)) + + def process_IN_CREATE(self, event): + if not self.is_ext(event.pathname): return + self.panel_reload(event.pathname,'[Create]') + + def process_IN_DELETE(self,event): + if not self.is_ext(event.pathname): return + self.panel_reload(event.pathname,'[Delete]') + + def process_IN_MODIFY(self,event): + + if not self.is_ext(event.pathname): return + self.panel_reload(event.pathname,'[Modify]') + + def debug_event(): + logger.debug('Launch the panel in debug mode') + logger.debug('Listening port:0.0.0.0:{}'.format(public.readFile('data/port.pl'))) + + event = PanelEventHandler() + watchManager = pyinotify.WatchManager() + mode = pyinotify.IN_CREATE | pyinotify.IN_DELETE | pyinotify.IN_MODIFY + watchManager.add_watch(_PATH, mode, auto_add=True, rec=True) + notifier = pyinotify.Notifier(watchManager, event) + notifier.loop() if __name__ == '__main__': + pid_file = "{}/logs/panel.pid".format(_PATH) + if os.path.exists(pid_file): + public.ExecShell("kill -9 {}".format(public.readFile(pid_file))) pid = os.fork() if pid: sys.exit(0) @@ -25,7 +90,7 @@ if __name__ == '__main__': _pid = os.fork() if _pid: - public.writeFile('logs/panel.pid',str(_pid)) + public.writeFile(pid_file,str(_pid)) sys.exit(0) sys.stdout.flush() @@ -38,7 +103,7 @@ if __name__ == '__main__': HOST = "0:0:0:0:0:0:0:0" f.close() - is_debug = os.path.exists('data/debug.pl') + keyfile = 'ssl/privateKey.pem' certfile = 'ssl/certificate.pem' is_ssl = False @@ -57,21 +122,30 @@ if __name__ == '__main__': job.setDaemon(True) job.start() - if is_debug: - ssl_context = None - if is_ssl: ssl_context=(certfile,keyfile) - app.run(host=HOST,port=PORT,threaded=True,debug=True,ssl_context=ssl_context) + + if is_ssl: + ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) + ssl_context.load_cert_chain(certfile=certfile,keyfile=keyfile) + ssl_context.options = (ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 | ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1) + ssl_context.set_ciphers("ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE") + + + from gevent.pywsgi import WSGIServer + from geventwebsocket.handler import WebSocketHandler + + if is_ssl: + http_server = WSGIServer((HOST, PORT), app,handler_class=WebSocketHandler,ssl_context = ssl_context) else: - from gevent.pywsgi import WSGIServer - from geventwebsocket.handler import WebSocketHandler + http_server = WSGIServer((HOST, PORT), app,handler_class=WebSocketHandler) + + if is_debug: + try: + dev = threading.Thread(target=debug_event) + dev.setDaemon(True) + dev.start() + except: + pass + + http_server.serve_forever() - if is_ssl: - ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) - ssl_context.load_cert_chain(certfile=certfile,keyfile=keyfile) - ssl_context.options |= (ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3) - ssl_context.set_ciphers("ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE") - http_server = WSGIServer((HOST, PORT), app,handler_class=WebSocketHandler,ssl_context = ssl_context) - else: - http_server = WSGIServer((HOST, PORT), app,handler_class=WebSocketHandler) - http_server.serve_forever() \ No newline at end of file diff --git a/BTPanel/__init__.py b/BTPanel/__init__.py index 860d0b0e..c83787cc 100644 --- a/BTPanel/__init__.py +++ b/BTPanel/__init__.py @@ -6,9 +6,11 @@ # +------------------------------------------------------------------- # | Author: hwliang # +------------------------------------------------------------------- +import logging import sys import json import os +import threading import time import re import uuid @@ -18,7 +20,7 @@ if not 'class/' in sys.path: sys.path.insert(0,'class/') from flask import Config, Flask, session, render_template, send_file, request, redirect, g, make_response, \ - render_template_string, abort, Response as Resp + render_template_string, abort, stream_with_context,Response as Resp from cachelib import SimpleCache from werkzeug.wrappers import Response from flask_session import Session @@ -32,8 +34,11 @@ import public app = Flask(__name__, template_folder="templates/{}".format(public.GetConfigValue('template'))) Compress(app) sockets = Sockets(app) - -#import db +# 注册HOOK +hooks = {} +if not hooks: + public.check_hooks() +# import db dns_client = None app.config['DEBUG'] = os.path.exists('data/debug.pl') @@ -52,12 +57,12 @@ if os.path.exists(basic_auth_conf): app.secret_key = uuid.UUID(int=uuid.getnode()).hex[-12:] local_ip = None my_terms = {} -app.config['SESSION_MEMCACHED'] = SimpleCache() +app.config['SESSION_MEMCACHED'] = SimpleCache(1000,86400) app.config['SESSION_TYPE'] = 'memcached' app.config['SESSION_PERMANENT'] = True app.config['SESSION_USE_SIGNER'] = True app.config['SESSION_KEY_PREFIX'] = 'BT_:' -app.config['SESSION_COOKIE_NAME'] = "SESSIONID" +app.config['SESSION_COOKIE_NAME'] = public.md5(app.secret_key) app.config['PERMANENT_SESSION_LIFETIME'] = 86400 * 30 Session(app) @@ -130,8 +135,8 @@ if admin_path in admin_path_checks: admin_path = '/bt' @app.before_request def request_check(): g.request_time = time.time() - #路由和URI长度过滤 - if len(request.path) > 128: return abort(403) + # 路由和URI长度过滤 + if len(request.path) > 256: return abort(403) if len(request.url) > 1024: return abort(403) if request.path in ['/service_status']: return @@ -143,13 +148,24 @@ def request_check(): if len(k) > 48: return abort(403) if len(pdata[k]) > 256: return abort(403) if session.get('debug') == 1: return + + if app.config['BASIC_AUTH_OPEN']: + if request.path in ['/public', '/download', '/mail_sys', '/hook', '/down', '/check_bind', + '/get_app_bind_status']: return + auth = request.authorization + if not comm.get_sk(): return + if not auth: return send_authenticated() + tips = '_bt.cn' + if public.md5(auth.username.strip() + tips) != app.config['BASIC_AUTH_USERNAME'] \ + or public.md5(auth.password.strip() + tips) != app.config['BASIC_AUTH_PASSWORD']: + return send_authenticated() + if not request.path in ['/safe', '/hook', '/public', '/mail_sys', '/down']: ip_check = public.check_ip_panel() if ip_check: return ip_check if request.path.find('/static/') != -1 or request.path == '/code': if not 'login' in session and not 'admin_auth' in session and not 'down' in session: - session.clear() return abort(401) domain_check = public.check_domain_panel() if domain_check: return domain_check @@ -158,15 +174,14 @@ def request_check(): if request.args.get('action') in not_networks: return public.returnJson(False,'INIT_REQUEST_CHECK_LOCAL_ERR'),json_header - if app.config['BASIC_AUTH_OPEN']: - if request.path in ['/public','/download','/mail_sys','/hook','/down','/check_bind','/get_app_bind_status']: return - auth = request.authorization - if not comm.get_sk(): return - if not auth: return send_authenticated() - tips = '_bt.cn' - if public.md5(auth.username.strip() + tips) != app.config['BASIC_AUTH_USERNAME'] \ - or public.md5(auth.password.strip() + tips) != app.config['BASIC_AUTH_PASSWORD']: - return send_authenticated() + if request.path in ['/','/site','/ftp','/database','/soft','/control','/firewall','/files','/xterm','/crontab','/config']: + licenes = 'data/licenes.pl' + if request.path in ['/'] and not os.path.exists(licenes): + return + + # if not public.is_bind(): + # return redirect('/bind',302) + #Flask 请求结束勾子 @app.teardown_request @@ -180,9 +195,10 @@ def request_end(reques = None): if g.api_request: session.clear() -#Flask 404页面勾子 + +# Flask 404页面勾子 @app.errorhandler(404) -def notfound(e): +def error_404(e): errorStr = ''' 404 Not Found @@ -195,6 +211,36 @@ def notfound(e): } return Response(errorStr,status=404,headers=headers) +# Flask 500页面勾子 +@app.errorhandler(500) +def error_500(e): + ss = '''404 Not Found: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. + +During handling of the above exception, another exception occurred:''' + error_info = public.get_error_info().strip().split(ss)[-1].strip() + if error_info.find("`GLIBC_2.14'") != -1: + public.downloadFile('https://download.bt.cn/auth/libAuth_gcc_4.4.7_x{}.so'.format(public.get_sysbit()),'/www/server/panel/class/libAuth.x86-64.so') + error_info += "\n已尝试自动修复此问题,请刷新页面重试!" + request_info = '''REQUEST_DATE: {request_date} + PAN_VERSION: {panel_version} + OS_VERSION: {os_version} + REMOTE_ADDR: {remote_addr} + REQUEST_URI: {method} {full_path} +REQUEST_FORM: {request_form} + USER_AGENT: {user_agent}'''.format( + request_date = public.getDate(), + remote_addr = public.GetClientIp(), + method = request.method, + full_path = request.full_path, + request_form = request.form.to_dict(), + user_agent = request.headers.get('User-Agent'), + panel_version = public.get_panel_version(), + os_version = public.get_os_version() +) + + result = public.readFile('/www/server/panel/BTPanel/templates/default/panel_error.html').format(error_title=error_info.split("\n")[-1],request_info = request_info,error_msg=error_info) + return Resp(result,500) + # ===================================Flask HOOK========================# @@ -227,55 +273,6 @@ def xterm(): defs = ('get_host_list','get_host_find','modify_host','create_host','remove_host','set_sort','get_command_list','create_command','get_command_find','modify_command','remove_command') return publicObject(ssh_host_admin,defs,None) -#@app.route('/webssh') -@sockets.route('/webssh') -def webssh(ws): - #宝塔终端连接 - comReturn = comm.local() - if comReturn: return comReturn - #ws = request.environ.get('wsgi.websocket') - if not ws: return 'False' - get = ws.receive() - if not get: return - get = json.loads(get) - import ssh_terminal - sp = ssh_terminal.ssh_host_admin() - if 'host' in get: - ssh_info = {} - ssh_info['host'] = get['host'].strip() - if 'port' in get: - ssh_info['port'] = int(get['port']) - if 'username' in get: - ssh_info['username'] = get['username'].strip() - if 'password' in get: - ssh_info['password'] = get['password'].strip() - if 'pkey' in get: - ssh_info['pkey'] = get['pkey'].strip() - - if get['host'] in ['127.0.0.1','localhost'] and 'port' not in ssh_info: - ssh_info = sp.get_ssh_info('127.0.0.1') - if not ssh_info: ssh_info = sp.get_ssh_info('localhost') - if not ssh_info: ssh_info = {"host":"127.0.0.1"} - ssh_info['port'] = public.get_ssh_port() - else: - ssh_info = sp.get_ssh_info('127.0.0.1') - if not ssh_info: ssh_info = sp.get_ssh_info('localhost') - if not ssh_info: ssh_info = {"host":"127.0.0.1"} - ssh_info['port'] = public.get_ssh_port() - - if not ssh_info['host'] in ['127.0.0.1','localhost']: - if not 'username' in ssh_info: - ssh_info = sp.get_ssh_info(ssh_info['host']) - if not ssh_info: - ws.send(public.getMsg('SSH_LOGIN_ERR7')) - return - p = ssh_terminal.ssh_terminal() - p.run(ws,ssh_info) - del(p) - if not ws.closed: - ws.close() - return 'False' - @app.route('/site',methods=method_all) def site(pdata = None): @@ -483,21 +480,22 @@ def firewall(pdata = None): 'AddAcceptPort','DelAcceptPort','SetSshStatus','SetPing','SetSshPort','GetSshInfo') return publicObject(firewallObject,defs,None,pdata) -@app.route('/ssh_security',methods=method_all) -def ssh_security(pdata = None): - #SSH安全 + +@app.route('/ssh_security', methods=method_all) +def ssh_security(pdata=None): + # SSH安全 comReturn = comm.local() if comReturn: return comReturn if request.method == method_get[0] and not pdata: data = {} data['lan'] = public.GetLan('firewall') data['js_random'] = get_js_random() - return render_template( 'firewall.html',data=data) + return render_template('firewall.html', data=data) import ssh_security firewallObject = ssh_security.ssh_security() defs = ('san_ssh_security', 'set_password', 'set_sshkey', 'stop_key', 'get_config', 'stop_password', 'get_key', 'return_ip', 'add_return_ip', 'del_return_ip', 'start_jian', 'stop_jian', - 'get_jian', 'get_logs','set_root','stop_root') + 'get_jian', 'get_logs','set_root','stop_root','start_auth_method','stop_auth_method','get_auth_method','check_so_file','get_so_file') return publicObject(firewallObject, defs, None, pdata) @@ -573,6 +571,20 @@ def abnormal(pdata=None): ) return publicObject(dataObject, defs, None, pdata) +@app.route('/project//', methods=method_all) +def project(mod_name,def_name): + comReturn = comm.local() + if comReturn: return comReturn + from panelProjectController import ProjectController + project_obj = ProjectController() + defs = ('model',) + get = get_input() + get.action = 'model' + get.mod_name = mod_name + get.def_name = def_name + + return publicObject(project_obj,defs,None,get) + @app.route('/files',methods=method_all) def files(pdata = None): #文件管理 @@ -662,7 +674,7 @@ def config(pdata = None): return render_template( 'config.html',data=data) import config defs = ( - 'set_backup_notification','get_panel_ssl_status','set_file_deny', 'del_file_deny', 'get_file_deny', + 'set_empty','set_backup_notification','get_panel_ssl_status','set_file_deny', 'del_file_deny', 'get_file_deny', 'get_httpd_access_log_format_parameter','set_httpd_format_log_to_website','get_httpd_access_log_format', 'del_httpd_access_log_format','add_httpd_access_log_format','get_nginx_access_log_format_parameter', 'set_format_log_to_website','get_nginx_access_log_format','del_nginx_access_log_format', @@ -775,7 +787,7 @@ def plugin(pdata = None): if comReturn: return comReturn import panelPlugin pluginObject = panelPlugin.panelPlugin() - defs = ('check_install_limit','set_score','get_score','update_zip','input_zip','export_zip','add_index','remove_index','sort_index', + defs = ('get_usually_plugin','check_install_limit','set_score','get_score','update_zip','input_zip','export_zip','add_index','remove_index','sort_index', 'install_plugin','uninstall_plugin','get_soft_find','get_index_list','get_soft_list','get_cloud_list', 'check_deps','flush_cache','GetCloudWarning','install','unInstall','getPluginList','getPluginInfo','get_make_args','add_make_args', 'getPluginStatus','setPluginStatus','a','getCloudPlugin','getConfigHtml','savePluginSort','del_make_args','set_make_args') @@ -889,9 +901,7 @@ def login(): is_auth_path = False if admin_path != '/bt' and os.path.exists(admin_path_file) and not 'admin_auth' in session: is_auth_path = True - num_key = public.md5(public.GetClientIp() + '_auth_path') - # if not public.get_error_num(num_key,20): return public.returnMsg(False,'AUTH_FAILED1') - #登录输入验证 + # 登录输入验证 if request.method == method_post[0]: v_list = ['username','password','code','vcode','cdn_url'] for v in v_list: @@ -949,14 +959,12 @@ def login(): referer_path = referer_tmp[-1] if referer_path == '': referer_path = referer_tmp[-2] - if route_path != '/'+referer_path: - public.set_error_num(num_key) - #return abort(404) + if route_path != '/' + referer_path: data = {} data['lan'] = public.getLan('close') - return render_template('autherr.html',data=data) + return render_template('autherr.html', data=data) + session['admin_auth'] = True - public.set_error_num(num_key,True) comReturn = common.panelSetup().init() if comReturn: return comReturn @@ -1071,20 +1079,22 @@ def down(token=None,fname=None): if not re.match(r"^\w+$",args.file_password): return public.ReturnJson(False,'WRONG_PASSWD'),json_header if re.match(r"^\d+$",args.file_password): - args.file_password += '.0' + args.file_password = str(int(args.file_password)) + args.file_password += ".0" if args.file_password != str(find['password']): return public.ReturnJson(False,'WRONG_PASSWD'),json_header session[token] = 1 session['down'] = True else: pdata = { - "to_path":"", - "src_path": find['filename'], - "password":True, - "filename":find['filename'].split('/')[-1], - "total":find['total'], - "token":find['token'], - "expire":public.format_date(times=find['expire']) + "to_path":"", + "src_path": find['filename'], + "password":True, + "filename":find['filename'].split('/')[-1], + "ps": find['ps'], + "total":find['total'], + "token":find['token'], + "expire":public.format_date(times=find['expire']) } session['down'] = True return render_template('down.html',data = pdata) @@ -1291,7 +1301,8 @@ def panel_other(name=None,fun = None,stype=None): data = panelPHP.panelPHP(name).exec_php_script(args) r_type = type(data) - if r_type == Response: return data + if r_type in [Response,Resp]: + return data #处理响应 if stype == 'json': #响应JSON @@ -1383,6 +1394,38 @@ Disallow: / ''' return robots,{'Content-Type':'text/plain'} + +@app.route('/rspamd', defaults={'path': ''},methods=method_all) +@app.route('/rspamd/',methods=method_all) +def proxy_rspamd_requests(path): + comReturn = comm.local() + if comReturn: return comReturn + param = str(request.url).split('?') + param = "" if len(param) < 2 else param[-1] + import requests + headers = {} + for h in request.headers.keys(): + headers[h] = request.headers[h] + if request.method == "GET": + if re.search("\.(js|css)$",path): + return send_file('/usr/share/rspamd/www/rspamd/'+path,conditional=True,add_etags=True) + if path == "/": + return send_file('/usr/share/rspamd/www/rspamd/',conditional=True,add_etags=True) + url = "http://127.0.0.1:11334/rspamd/" + path + "?" +param + for i in ['stat','auth','neighbours','list_extractors','list_transforms','graph','maps','actions','symbols','history','errors','check_selector','saveactions','savesymbols','getmap']: + if i in path: + url = "http://127.0.0.1:11334/" + path + "?" +param + req = requests.get(url, headers=headers,stream = True) + return Resp(stream_with_context(req.iter_content()), content_type = req.headers['content-type']) + else: + url = "http://127.0.0.1:11334/" + path + for i in request.form.keys(): + data = '{}='.format(i) + # public.writeFile('/tmp/2',data+"\n","a+") + req = requests.post(url,data=data,headers=headers,stream = True) + + return Resp(stream_with_context(req.iter_content()), content_type = req.headers['content-type']) + #==================================================# @@ -1405,6 +1448,7 @@ def get_dir_down(filename,token,find): pdata = files.files().GetDir(args) pdata['token'] = token + pdata['ps'] = find['ps'] pdata['src_path'] = find['filename'] pdata['to_path'] = to_path if find['expire'] < (time.time() + (86400 * 365 * 10)): @@ -1455,34 +1499,19 @@ def get_phpmyadmin_dir(): class run_exec: - #模块访问对像 - def run(self,toObject,defs,get): + # 模块访问对像 + def run(self, toObject, defs, get): result = None - for key in defs: - if key == get.action: - fun = 'toObject.'+key+'(get)' - if hasattr(get,'html') or hasattr(get,'s_module'): - result = eval(fun) - else: - result = eval(fun) - r_type = type(result) - if r_type == Resp: return result - result = public.GetJson(result),json_header - break - if not result: - result = public.ReturnJson(False,'ARGS_ERR'),json_header - if g.is_aes: - result = public.aes_encrypt(result[0],g.aes_key),json_header - else: - # if os.path.exists('pyenv/bin/python') and sys.version_info[0] == 3: - # if not os.path.exists('data/debug.pl'): - # x_token = request.headers.get('x-http-token') - # if x_token: - # aes_pwd = x_token[:8] + x_token[40:48] - # result = "BT-CRT"+public.aes_encrypt(result[0],aes_pwd),{'Content-Type':'text/plain; charset=utf-8'} - pass - return result + if not get.action in defs: return public.ReturnJson(False, 'ARGS_ERR'), json_header + result = getattr(toObject,get.action)(get) + if not hasattr(get, 'html') and not hasattr(get, 's_module'): + r_type = type(result) + if r_type in [Response,Resp]: return result + result = public.GetJson(result), json_header + if g.is_aes: + result = public.aes_encrypt(result[0], g.aes_key), json_header + return result def check_csrf(): @@ -1497,29 +1526,39 @@ def check_csrf(): if cookie_token != session['request_token']: return False return True -def publicObject(toObject,defs,action=None,get = None): - #模块访问前置检查 - if 'request_token' in session and 'login' in session: - if not check_csrf(): return public.ReturnJson(False,'INIT_CSRF_ERR'),json_header - if not get: get = get_input() - if action: get.action = action +def publicObject(toObject, defs, action=None, get=None): + try: + # 模块访问前置检查 + if 'request_token' in session and 'login' in session: + if not check_csrf(): return public.ReturnJson(False, 'INIT_CSRF_ERR'), json_header - if hasattr(get,'path'): - get.path = get.path.replace('//','/').replace('\\','/') - if get.path.find('./') != -1: return public.ReturnJson(False,'INIT_PATH_NOT_SAFE'),json_header + if not get: get = get_input() + if action: get.action = action + + if hasattr(get, 'path'): + get.path = get.path.replace('//', '/').replace('\\', '/') + if get.path.find('./') != -1: return public.ReturnJson(False, 'INIT_PATH_NOT_SAFE'), json_header if get.path.find('->') != -1: get.path = get.path.split('->')[0].strip() - if hasattr(get,'sfile'): - get.sfile = get.sfile.replace('//','/').replace('\\','/') - if hasattr(get,'dfile'): - get.dfile = get.dfile.replace('//','/').replace('\\','/') + get.path = public.xssdecode(get.path) + if hasattr(get, 'filename'): + get.filename = public.xssdecode(get.filename) - if hasattr(toObject,'site_path_check'): - if not toObject.site_path_check(get): return public.ReturnJson(False,'INIT_ACCEPT_NOT'),json_header - return run_exec().run(toObject,defs,get) + if hasattr(get, 'sfile'): + get.sfile = get.sfile.replace('//', '/').replace('\\', '/') + get.sfile = public.xssdecode(get.sfile) + if hasattr(get, 'dfile'): + get.dfile = get.dfile.replace('//', '/').replace('\\', '/') + get.dfile = public.xssdecode(get.dfile) + if hasattr(toObject, 'site_path_check'): + if not toObject.site_path_check(get): return public.ReturnJson(False, 'INIT_ACCEPT_NOT'), json_header + return run_exec().run(toObject, defs, get) + except: + return error_500(None) + def check_login(http_token=None): #检查是否登录面板 @@ -1569,8 +1608,8 @@ def get_pd(): tmp3 = public.to_string([60, 115, 112, 97, 110, 32, 99, 108, 97, 115, 115, 61, 34, 98, 116, 112, 114, 111, 45, 102, 114, 101, 101, 34, 32, 111, 110, 99, 108, 105, 99, 107, 61, 34, 98, 116, 46, 115, 111, 102, 116, 46, 114, 101, 110, 101, 119, 95, 112, 114, - 111, 40, 41, 34, 32, 116, 105, 116, 108, 101, 61, 34, 28857, 20987, 21319, 32423, - 21040, 21830, 19994, 29256, 34, 62, 20813, 36153, 29256, 60, 47, 115, 112, 97, 110, 62]) + 111, 40, 41, 34, 32, 116, 105, 116, 108, 101, 61, 34, 67,108,105,99,107,32,116,111,32, + 103,101,116,32,80,82,79, 34, 62, 20813, 36153, 29256, 60, 47, 115, 112, 97, 110, 62]) elif tmp == -2: tmp3 = public.to_string([60, 115, 112, 97, 110, 32, 99, 108, 97, 115, 115, 61, 34, 98, 116, 112, 114, 111, 45, 103, 114, 97, 121, 34, 62, 60, 115, 112, 97, 110, 32, @@ -1609,8 +1648,8 @@ def get_pd(): tmp3 = public.to_string([60, 115, 112, 97, 110, 32, 99, 108, 97, 115, 115, 61, 34, 98, 116, 112, 114, 111, 45, 103, 114, 97, 121, 34, 32, 111, 110, 99, 108, 105, 99, 107, 61, 34, 98, 116, 46, 115, 111, 102, 116, 46, 114, 101, 110, 101, 119, 95, 112, - 114, 111, 40, 41, 34, 32, 116, 105, 116, 108, 101, 61, 34, 28857, - 20987, 21319, 32423, 21040, 19987, 19994, 29256, 34, 62, 70, 82, + 114, 111, 40, 41, 34, 32, 116, 105, 116, 108, 101, 61, 34, 67,108,105,99,107,32,116, + 111,32,103,101,116,32,80,82,79, 34, 62, 70, 82, 69, 69, 60, 47, 115, 112, 97, 110, 62]) else: tmp3 = public.to_string([60, 115, 112, 97, 110, 32, 99, 108, 97, 115, 115, 61, 34, 98, 116, 108, 116, @@ -1675,17 +1714,9 @@ def get_input(): for key in request.args.keys(): data[key] = str(request.args.get(key,'')) try: - # x_token = request.headers.get('x-http-token') - # if x_token: - # aes_pwd = x_token[:8] + x_token[40:48] - for key in request.form.keys(): if key in exludes: continue - data[key] = str(request.form.get(key,'')) - # if x_token: - # if len(data[key]) > 5: - # if data[key][:6] == 'BT-CRT': - # data[key] = public.aes_decrypt(data[key][6:],aes_pwd) + data[key] = str(request.form.get(key, '')) except: try: post = request.form.to_dict() @@ -1728,6 +1759,320 @@ def check_token(data): #======================公共方法区域END============================# +# --------------------- websocket START -------------------------- # +@sockets.route('/workorder_client') +def workorder_client(ws): + comReturn = comm.local() + if comReturn: return comReturn + get = ws.receive() + get = json.loads(get) + if not check_csrf_websocket(ws,get): + return + + import panelWorkorder + toObject = panelWorkorder.panelWorkorder() + get = get_input() + toObject.client(ws, get) + +@sockets.route('/ws_panel') +def ws_panel(ws): + ''' + @name 面板接口ws入口 + @author hwliang<2021-07-24> + @param ws websocket会话对像 + @return void + ''' + comReturn = comm.local() + if comReturn: return comReturn + + get = ws.receive() + get = json.loads(get) + if not check_csrf_websocket(ws,get): return + + while True: + pdata = ws.receive() + if pdata is '{}': break + data = json.loads(pdata) + get = public.to_dict_obj(data) + get._ws = ws + p = threading.Thread(target=ws_panel_thread,args=(get,)) + p.start() + +def ws_panel_thread(get): + ''' + @name 面板管理ws线程 + @author hwliang<2021-07-24> + @param get 请求参数 + @return void + ''' + + if not hasattr(get, 'ws_callback'): + get._ws.send(public.getJson(public.return_status_code(1001, 'ws_callback'))) + return + if not hasattr(get, 'mod_name'): + get._ws.send(public.getJson(public.return_status_code(1001, 'mod_name'))) + return + if not hasattr(get, 'def_name'): + get._ws.send(public.getJson(public.return_status_code(1001, 'def_name'))) + return + get.mod_name = get.mod_name.strip() + get.def_name = get.def_name.strip() + check_str = '{}{}'.format(get.mod_name, get.def_name) + if not re.match("^\w+$", check_str) or get.mod_name in ['public', 'common', 'db', 'db_mysql', 'downloadFile', + 'jobs']: + get._ws.send(public.getJson(public.return_status_code(1000, '不安全的mod_name,def_name参数内容'))) + return + if not hasattr(get, 'args'): + get._ws.send(public.getJson(public.return_status_code(1001, 'args'))) + return + + mod_file = '{}/{}.py'.format(public.get_class_path(), get.mod_name) + if not os.path.exists(mod_file): + get._ws.send(public.getJson(public.return_status_code(1000, '指定模块{}不存在'.format(get.mod_name)))) + return + _obj = public.get_script_object(mod_file) + if not _obj: + get._ws.send(public.getJson(public.return_status_code(1000, '指定模块{}不存在'.format(get.mod_name)))) + return + _cls = getattr(_obj, get.mod_name) + if not _cls: + get._ws.send( + public.getJson(public.return_status_code(1000, '在{}模块中没有找到{}对像'.format(get.mod_name, get.mod_name)))) + return + _def = getattr(_cls(), get.def_name) + if not _def: + get._ws.send( + public.getJson(public.return_status_code(1000, '在{}对像中没有找到{}方法'.format(get.mod_name, get.def_name)))) + return + result = { + 'callback': get.ws_callback, + 'result': _def(public.to_dict_obj(get.args)) + } + get._ws.send(public.getJson(result)) + + +@sockets.route('/ws_project') +def ws_project(ws): + ''' + @name 项目管理ws入口 + @author hwliang<2021-07-24> + @param ws websocket会话对像 + @return void + ''' + comReturn = comm.local() + if comReturn: return comReturn + get = ws.receive() + get = json.loads(get) + if not check_csrf_websocket(ws,get): return + + from panelProjectController import ProjectController + project_obj = ProjectController() + while True: + pdata = ws.receive() + if pdata in '{}': break + get = public.to_dict_obj(json.loads(pdata)) + get._ws = ws + p = threading.Thread(target=ws_project_thread, args=(project_obj, get)) + p.start() + + +def ws_project_thread(_obj, get): + ''' + @name 项目管理ws线程 + @author hwliang<2021-07-24> + @param _obj 项目管理控制器对像 + @param get 请求参数 + @return void + ''' + if not hasattr(get, 'ws_callback'): + get._ws.send(public.getJson(public.return_status_code(1001, 'ws_callback'))) + return + result = { + 'callback': get.ws_callback, + 'result': _obj.model(get) + } + get._ws.send(public.getJson(result)) + + +import subprocess +sock_pids = {} +@sockets.route('/sock_shell') +def sock_shell(ws): + ''' + @name 执行指定命令,实时输出命令执行结果 + @author hwliang<2021-07-19> + @return void + + 示例: + p = new WebSocket('ws://192.168.1.247:8888/sock_shell') + p.send('ping www.bt.cn -c 100') + ''' + comReturn = comm.local() + if comReturn: + ws.send(str(comReturn)) + return + kill_closed() + get = ws.receive() + get = json.loads(get) + if not check_csrf_websocket(ws,get): return + + t = None + try: + while True: + cmdstring = ws.receive() + if cmdstring in ['stop', 'error'] or not cmdstring: + break + t = threading.Thread(target=sock_recv, args=(cmdstring, ws)) + t.start() + kill_closed() + except: + kill_closed() + +def kill_closed(): + ''' + @name 关闭已关闭的连接 + @author hwliang<2021-07-24> + @return void + ''' + global sock_pids + import psutil + pids = psutil.pids() + keys = sock_pids.copy().keys() + for pid in keys: + logging.debug("PID: {} , sock_stat: {}".format(pid, sock_pids[pid].closed)) + if not sock_pids[pid].closed: continue + + if pid in pids: + try: + p = psutil.Process(pid) + for cp in p.children(): + cp.kill() + p.kill() + logging.debug("killed: {}".format(pid)) + sock_pids.pop(pid) + except: + pass + else: + sock_pids.pop(pid) + + +def sock_recv(cmdstring, ws): + global sock_pids + try: + p = subprocess.Popen(cmdstring + " 2>&1", close_fds=True, shell=True, bufsize=4096, stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + sock_pids[p.pid] = ws + kill_closed() + while p.poll() is None: + ws.send(p.stdout.readline().decode()) + ws.send(p.stdout.read().decode()) + except: + kill_closed() + + +@app.route('/close_sock_shell', methods=method_all) +def close_sock_shell(): + ''' + @name 关闭指定命令 + @author hwliang<2021-07-19> + @param cmdstring 完整命令行 + @return dict + 示例: + $.post('/close_sock_shell',{cmdstring:'ping www.bt.cn -c 100'}) + ''' + comReturn = comm.local() + if comReturn: return comReturn + args = get_input() + cmdstring = args.cmdstring.strip() + skey = public.md5(cmdstring) + pid = cache.get(skey) + if not pid: + return json.dumps(public.return_data(False, [], error_msg='指定sock已终止!')), json_header + os.kill(pid, 9) + cache.delete(skey) + return json.dumps(public.return_data(True, '操作成功!')), json_header + +def check_csrf_websocket(ws,args): + ''' + @name 检查websocket是否被csrf攻击 + @author hwliang<2021-07-24> + @param ws websocket对像 + @return void + ''' + if g.is_aes: return True + is_success = True + if not 'x-http-token' in args: + is_success = False + + if is_success: + if session['request_token_head'] != args['x-http-token']: + is_success = False + + # if is_success: + # cookie_token = request.cookies.get('request_token') + # if cookie_token != session['request_token']: + # is_success = False + + if not is_success: + ws.send('token error') + return False + + return True + +@sockets.route('/webssh') +def webssh(ws): + # 宝塔终端连接 + comReturn = comm.local() + if comReturn: + ws.send(str(comReturn)) + return + if not ws: return 'False' + get = ws.receive() + if not get: return + get = json.loads(get) + if not check_csrf_websocket(ws,get): + return + + import ssh_terminal + sp = ssh_terminal.ssh_host_admin() + if 'host' in get: + ssh_info = {} + ssh_info['host'] = get['host'].strip() + if 'port' in get: + ssh_info['port'] = int(get['port']) + if 'username' in get: + ssh_info['username'] = get['username'].strip() + if 'password' in get: + ssh_info['password'] = get['password'].strip() + if 'pkey' in get: + ssh_info['pkey'] = get['pkey'].strip() + + if get['host'] in ['127.0.0.1', 'localhost'] and 'port' not in ssh_info: + ssh_info = sp.get_ssh_info('127.0.0.1') + if not ssh_info: ssh_info = sp.get_ssh_info('localhost') + if not ssh_info: ssh_info = {"host": "127.0.0.1"} + ssh_info['port'] = public.get_ssh_port() + else: + ssh_info = sp.get_ssh_info('127.0.0.1') + if not ssh_info: ssh_info = sp.get_ssh_info('localhost') + if not ssh_info: ssh_info = {"host": "127.0.0.1"} + ssh_info['port'] = public.get_ssh_port() + + if not ssh_info['host'] in ['127.0.0.1', 'localhost']: + if not 'username' in ssh_info: + ssh_info = sp.get_ssh_info(ssh_info['host']) + if not ssh_info: + ws.send('The specified host information is not found, please add it again!') + return + p = ssh_terminal.ssh_terminal() + p.run(ws, ssh_info) + del (p) + if not ws.closed: + ws.close() + return 'False' + + +# --------------------- websocket END -------------------------- # diff --git a/BTPanel/static/css/site.css b/BTPanel/static/css/site.css index 91ba44c0..5a147f30 100644 --- a/BTPanel/static/css/site.css +++ b/BTPanel/static/css/site.css @@ -1815,7 +1815,19 @@ html .menu .menu_exit:hover { .bt-w-con { margin-left: 170px; - position: relative + position: relative; + padding: 7px 15px; +} +.bt-w-con .bt-w-item{ + height: 100%; + display:none; +} +.bt-w-con .bt-w-item.active{ + display:block; +} +.taskcon{ + height: 500px; + overflow: auto; } .mes_channel .bt-w-con { margin-left: 110px; @@ -3115,7 +3127,6 @@ html .menu .menu_exit:hover { vertical-align: middle; padding: 5px 10px; height: 40px; - font-size: 12.5px; box-sizing: border-box; } .table>tbody{ @@ -9934,6 +9945,16 @@ select[name="network-io"]{ margin-left: 5px; vertical-align: middle; } + +.command_output_pre{ + white-space: pre-line; + background: rgb(51, 51, 51); + color: rgb(236, 236, 236); + box-sizing: border-box; + margin: 0; + border: none; + border-radius: 1px; +} /*批量创建站点end*/ .custom_layer .layui-layer-content .tab-body .tab-con{ @@ -10288,3 +10309,63 @@ background:url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iODIiIGhlaWdodD0iODIiIHh margin-right: 10px; } /* 企业版支付end */ +.commonly_software{ + height: 28px; + line-height: 28px; + margin-bottom: 15px; + color:#666; +} +.commonly_software .commonly_software_title{ + display: inline-block; + padding-left: 5px; + padding-right: 15px; +} + +.commonly_software .commonly_software_list{ + display: inline-block; + +} +.commonly_software .commonly_software_list .item{ + display: inline-block; + margin-right: 10px; + padding: 0 10px; + cursor: pointer; + border-radius: 3px; + transition: all 500ms; + position: relative; +} +.commonly_software .commonly_software_list .item:hover{ + color: #20A53A; + background-color: #f5f5f5; +} +.commonly_software .commonly_software_list .item img{ + max-width: 22px; + margin-right: 5px; + image-rendering: -webkit-optimize-contrast; + vertical-align: middle; + margin-top: -2.5px; +} + +.commonly_software .commonly_software_list .item span{ + display: inline-block; + font-size: 12px; + color:#666; +} +.pro_introduce_content .item{ + position: relative; +} +.pro_introduce_content .item .success_icon{ + position: absolute; + display: block; + left: 0; + top: 50%; + margin-top: -8px; + width: 6px; + height: 12px; + border: solid #20a532; + border-width: 0 1.5px 1.5px 0; + transform: rotate(45deg); +} +.pro_introduce_content .item span:nth-child(2){ + padding-left: 14px; +} \ No newline at end of file diff --git a/BTPanel/static/img/soft_ico/ico-total.png b/BTPanel/static/img/soft_ico/ico-total.png index 59d454ad..97c8a6ae 100644 Binary files a/BTPanel/static/img/soft_ico/ico-total.png and b/BTPanel/static/img/soft_ico/ico-total.png differ diff --git a/BTPanel/static/js/crontab.js b/BTPanel/static/js/crontab.js index dbb53945..4324b967 100644 --- a/BTPanel/static/js/crontab.js +++ b/BTPanel/static/js/crontab.js @@ -883,177 +883,173 @@ $(".dropdown ul li a").click(function(){ }) + //备份 function toBackup(type){ - var sMsg = ""; - switch(type){ - case 'sites': - sMsg = lan.crontab.backup_site; - sType = "sites"; - break; - case 'databases': - sMsg = lan.crontab.backup_database; - sType = "databases"; - break; - case 'logs': - sMsg = lan.crontab.backup_log; - sType = "sites"; - break; - case 'path': - sMsg = lan.crontab.dir_bak; - sType = "sites"; - break; - } - var data='type='+sType - $.post('/crontab?action=GetDataList',data,function(rdata){ - $(".planname input[name='name']").attr('readonly','true').css({"background-color":"#f6f6f6","color":"#666"}); - if(type != 'path'){ - var sOpt = "",sOptBody = ''; - if(rdata.data.length == 0){ - $(".planname input[name='name']").val(''); - layer.msg(lan.public.list_empty,{icon:2}) - return - } - for(var i=0;i'+rdata.data[i].name+'['+rdata.data[i].ps+']'; - } - sOptBody ='' - }else{ - $(".planname input[name='name']").val(sMsg+'[/www/wwwroot/]'); - sOptBody = '
' - setCookie('default_dir_path','/www/wwwroot/'); - setCookie('path_dir_change','/www/wwwroot/'); - setInterval(function(){ - if(getCookie('path_dir_change') != getCookie('default_dir_path')){ - var path_dir_change = getCookie('path_dir_change') - $(".planname input").val(lan.crontab.dir_bak+'['+getCookie('path_dir_change')+']'); - setCookie('default_dir_path',path_dir_change); - } - },500); - } - var orderOpt = '' - for (var i=0;i'+rdata.orderOpt[i].name+'' - } - - - - var sBody = sOptBody + '
'+lan.crontab.backup_to+'
\ - \ -
'+lan.crontab.save_new+'
\ - \ - '+lan.crontab.copies+'\ -
'; - if (type == 'sites' || type == 'path' || type == 'databases') { - $.post('/config?action=get_settings',data,function(rdata){ - var messageChannelDom = '', messageChannelBtnText = '', channelInitVal = '' - if(rdata.user_mail.user_name && rdata.dingding.dingding) { - messageChannelBtnText = 'All' - channelInitVal= 'user_name,dingding' - messageChannelDom = '
  • All
  • 钉钉
  • Email
  • ' - } else if(!rdata.user_mail.user_name && !rdata.dingding.dingding){ - messageChannelBtnText = 'No Data' - channelInitVal= '' - messageChannelDom += '
  • No Data
  • ' - } else if(rdata.dingding.dingding) { - messageChannelBtnText = '钉钉' - channelInitVal= 'dingding' - messageChannelDom += '
  • 钉钉
  • ' - } else if(rdata.user_mail.user_name) { - messageChannelBtnText = 'Email' - channelInitVal= 'mail' - messageChannelDom += '
  • Email
  • ' - } - sBody += '

    \ -

    Backup reminder
    \ - \ + var sMsg = ""; + switch(type){ + case 'sites': + sMsg = lan.crontab.backup_site; + sType = "sites"; + break; + case 'databases': + sMsg = lan.crontab.backup_database; + sType = "databases"; + break; + case 'logs': + sMsg = lan.crontab.backup_log; + sType = "sites"; + break; + case 'path': + sMsg = lan.crontab.dir_bak; + sType = "sites"; + break; + } + var data='type='+sType + $.post('/crontab?action=GetDataList',data,function(rdata){ + $(".planname input[name='name']").attr('readonly','true').css({"background-color":"#f6f6f6","color":"#666"}); + if(type != 'path'){ + var sOpt = "",sOptBody = ''; + if(rdata.data.length == 0){ + layer.msg(lan.public.list_empty,{icon:2}) + return + } + for(var i=0;i'+rdata.data[i].name+'['+rdata.data[i].ps+']'; + } + sOptBody ='' + }else{ + $(".planname input[name='name']").val(sMsg+'[/www/wwwroot/]'); + sOptBody = '
    ' + setCookie('default_dir_path','/www/wwwroot/'); + setCookie('path_dir_change','/www/wwwroot/'); + setInterval(function(){ + if(getCookie('path_dir_change') != getCookie('default_dir_path')){ + var path_dir_change = getCookie('path_dir_change') + $(".planname input").val(lan.crontab.dir_bak+'['+getCookie('path_dir_change')+']'); + setCookie('default_dir_path',path_dir_change); + } + },500); + } + var orderOpt = '' + for (var i=0;i'+rdata.orderOpt[i].name+'' + } + var save_num = 3; + if(type === 'logs'){ + $('#cycle b').attr('val','day').text(lan.crontab.daily); + $('.planweek').hide(); + $('[name="hour"]').val(0); + $('[name="minute"]').val(1); + // $('#implement').parent().after('
    提示
    根据网络安全法第二十一条规定,网络日志应留存不少于六个月。
    ') + save_num = 180; + }else{ + $('#logs_tips').remove(); + } + var sBody = sOptBody + '
    '+lan.crontab.backup_to+'
    \ + \ +
    '+lan.crontab.save_new+'
    \ + \ +
    '; + if (type == 'sites' || type == 'path' || type == 'databases') { + $.post('/config?action=get_settings',data,function(rdata){ + var messageChannelDom = '', messageChannelBtnText = '', channelInitVal = '' + if(rdata.user_mail.user_name && rdata.dingding.dingding) { + messageChannelBtnText = 'ALL' + channelInitVal= 'user_name,dingding' + messageChannelDom = '
  • ALL
  • 钉钉
  • 邮箱
  • ' + } else if(!rdata.user_mail.user_name && !rdata.dingding.dingding){ + messageChannelBtnText = 'No Data' + channelInitVal= '' + messageChannelDom += '
  • No Data
  • ' + } else if(rdata.dingding.dingding) { + messageChannelBtnText = '钉钉' + channelInitVal= 'dingding' + messageChannelDom += '
  • 钉钉
  • ' + } else if(rdata.user_mail.user_name) { + messageChannelBtnText = 'Email' + channelInitVal= 'mail' + messageChannelDom += '
  • Email
  • ' + } + sBody += '

    \ +

    Backup reminder
    \ + \ - \ - \ - \ - Set notifications\ - Keep local backup\ -

    '; - if(type == 'sites' || type == "path") { - sBody += '

    \ -

    '+lan.crontab.exclusion_rule+'
    \ - \ -

    '; - } - $("#implement").html(sBody); - getselectname(); - }) - }else{ - $("#implement").html('
    '); - sBody += '

    \ -

    '+lan.crontab.exclusion_rule+'
    \ - \ -

    '; - $("#implement").html(sBody); - } - $("#implement").on('click','.dropdown ul li a',function(ev){ - var val = $(this).attr('value'); - console.log(val) - $("#sName").attr({'value':val}).text($(this).text()) - $(".planname input[name='name']").val(sMsg+'['+val+']'); - }); - if(type == "path"){ - $('.planname input').attr('readonly',false).removeAttr('style'); - } - $("#exclude").focus(function(){ - var _this = $(this), tips = _this.attr('placeholder'), - tipss = ''+lan.crontab.exclusion_rule_tips+'
    data/config.php
    static/upload
    *.log
    '; - _this.attr('placeholder', ''); - var loadT = layer.tips(tipss, _this, { - tips: [1, '#20a53a'], - time: 0, - area: _this[0].clientWidth + 'px' - }); - $(this).one('blur', function () { - $(this).attr('placeholder', tips); - layer.close(loadT); - }); - }); - }); - + \ + \ + \ + Set notifications\ + \ +

    '; + if(type == 'sites' || type == "path") { + sBody += '

    \ +

    '+lan.crontab.exclusion_rule+'
    \ + \ +

    '; + } + $("#implement").html(sBody); + getselectnoticename(); + }) + } else { + $("#implement").html('
    '); + sBody += '

    \ +

    '+lan.crontab.exclusion_rule+'
    \ + \ +

    '; + $("#implement").html(sBody); + getselectname(); + } + $("#implement").on('click','.dropdown ul li a',function(ev){ + var sName = $("#sName").attr("val"); + if(!sName) return; + $(".planname input[name='name']").val(sMsg+'['+sName+']'); + }); + if(type == "path"){ + $('.planname input').attr('readonly',false).removeAttr('style'); + } + }); } //下拉菜单名称 diff --git a/BTPanel/static/js/files.js b/BTPanel/static/js/files.js index ffeeca64..4333559f 100644 --- a/BTPanel/static/js/files.js +++ b/BTPanel/static/js/files.js @@ -298,12 +298,14 @@ var bt_file = { if(that.uploading){ layer.confirm('Do you want to cancel the upload of files? It need to delete the uploaded files manually. Continue?',{title:'Cancel file upload',icon:0},function(indexs){ $('.upload_file_body').addClass('active').html('Please drag the file here') + $('.file_upload_info').css('display','none').siblings().css('display','block') that.filesList.length = 0 }); return false; }else{ $('.upload_file_body').addClass('active').html('Please drag the file here') that.filesList.length = 0 + $('.file_upload_info').css('display','none').siblings().css('display','block') return false; } }, @@ -609,7 +611,6 @@ var bt_file = { that.loadT.close(); } }) - $('.file_search_config').addClass('hide') e.stopPropagation(); }) $('.search_path_views').on('click','.file_search_config label',function(e){ @@ -4416,13 +4417,13 @@ var bt_file = { }); return (paths+path).replace('//','/'); }, - + /** * @descripttion 取扩展名 * @return: 返回扩展名 */ get_ext_name:function(fileName){ - var extArr = fileName.split("."); + var extArr = fileName.split("."); var exts = ["folder", "folder-unempty", "sql", "c", "cpp", "cs", "flv", "css", "js", "htm", "html", "java", "log", "mht", "php", "url", "xml", "ai", "bmp", "cdr", "gif", "ico", "jpeg", "jpg", "JPG", "png", "psd", "webp", "ape", "avi", "mkv", "mov", "mp3", "mp4", "mpeg", "mpg", "rm", "rmvb", "swf", "wav", "webm", "wma", "wmv", "rtf", "docx", "fdf", "potm", "pptx", "txt", "xlsb", "xlsx", "7z", "cab", "iso", "rar", "zip", "gz", "bt", "file", "apk", "bookfolder", "folder-empty", "fromchromefolder", "documentfolder", "fromphonefolder", "mix", "musicfolder", "picturefolder", "videofolder", "sefolder", "access", "mdb", "accdb", "fla", "doc", "docm", "dotx", "dotm", "dot", "pdf", "ppt", "pptm", "pot", "xls", "csv", "xlsm"]; var extLastName = extArr[extArr.length - 1]; for(var i=0; i-1,init:function(){0==$("#mask_layer").length&&(window.UploadFiles=function(){bt_file.file_drop.dialog_view()},$("body").append($('")),this.event_relation(document.querySelector("#container"),document,document.querySelector("#mask_layer")))},event_relation:function(e,t,i){var a=this;Object.keys(arguments);for(var l in arguments)"object"==typeof arguments[l]&&void 0!==arguments[l].nodeType&&(arguments[l]={el:arguments[l],callback:null});t.el.addEventListener("dragleave",null!=t.callback?t.callback:function(e){0==e.x&&0==e.y&&$("#mask_layer").hide(),e.preventDefault()},!1),e.el.addEventListener("dragenter",null!=e.callback?e.callback:function(e){if("string"==e.dataTransfer.items[0].kind)return!1;$("#mask_layer").show(),a.isLayuiDrop=!1,e.preventDefault()},!1),i.el.addEventListener("dragover",function(e){e.preventDefault()},!1),i.el.addEventListener("drop",null!=e.callback?i.callback:a.ev_drop,!1)},ev_drop:function(e){function t(e){e.getFilesAndDirectories().then(function(t){return n(t,e.path)})}if("string"==e.dataTransfer.items[0].kind)return!1;if(!bt_file.file_drop.is_webkit)return $("#mask_layer").hide(),!1;if(e.preventDefault(),bt_file.file_drop.uploading)return layer.msg("Uploading files, please wait..."),!1;var i,a=e.dataTransfer.items,l=0;if(loadT=layer.msg("Getting upload files details, please wait...",{icon:16,time:0,shade:.3}),bt_file.file_drop.isUpload=!0,a&&a.length&&null!=a[0].webkitGetAsEntry&&"file"!=a[0].kind)return!1;null==bt_file.file_drop.filesList&&(bt_file.file_drop.filesList=[]);for(var s=bt_file.file_drop.filesList.length-1;s>=0;s--)bt_file.file_drop.filesList[s].is_upload&&bt_file.file_drop.filesList.splice(-s,1);$("#mask_layer").hide();var n=function(e,a){if(!bt_file.file_drop.isUpload)return!1;for(var s=0;sbt_file.file_drop.isUploadNumber)return bt_file.file_drop.isUpload=!1,layer.msg(" "+bt_file.file_drop.isUploadNumber+" items cannot upload, please compress first!。",{icon:2,area:"405px"}),bt_file.file_drop.filesList=[],clearTimeout(i),!1;bt_file.file_drop.filesList.push({file:e[s],path:bt.get_file_path(a+"/"+e[s].name).replace("//","/"),name:e[s].name.replace("//","/"),icon:bt_file.get_ext_name(e[s].name),size:bt_file.file_drop.to_size(e[s].size),upload:0,is_upload:!1}),bt_file.file_drop.uploadAllSize+=e[s].size,clearTimeout(i),i=setTimeout(function(){layer.close(loadT),bt_file.file_drop.dialog_view()},100),l++}};"getFilesAndDirectories"in e.dataTransfer&&e.dataTransfer.getFilesAndDirectories().then(function(e){return n(e,"/")})},dialog_view:function(e){var t=this,i="";if(this.f_path=bt_file.file_path,!$(".file_dir_uploads").length>0){null==t.filesList&&(t.filesList=[]);for(var a=0;a
    '+(l.path+"/"+l.name).replace("//","/")+''+l.size+''+t.is_upload_status(l.upload)+'
    '}var s=t.filesList.length>11;layer.open({type:1,closeBtn:1,maxmin:!0,area:["550px","505px"],btn:["Upload","Cancel","Clear"],title:"Upload files to【"+bt.get_cookie("Path")+"】--- Support breakpoint renewal",skin:"file_dir_uploads",content:'
    '+(""!=i?'
    • File nameFile sizeFile status
      '+i+"
    ":"Please drag the file here"+(t.is_webkit?"":'The current browser does not support drag upload. Commend to use Chrome browser or WebKit kernel for browsing')+"")+"
    ",success:function(layers){layers.find('.layui-layer-btn2').css('margin','0 300px 0 0');$("#mask_layer").hide(),$(".file_dir_uploads .layui-layer-max").hide(),$(".upload_btn_groud .upload_file_btn").click(function(){$(".upload_btn_groud .dropdown-menu [data-type=file]").click()}),$(".upload_btn_groud .dropdown-menu a").click(function(){var e=$(this).attr("data-type");$('").change(function(e){for(var i=e.target.files,a=0;aPlease drag the file here')});t.filesList.length=0;return !1;}else{$('.upload_file_body').addClass('active').html('Please drag the file here');t.filesList.length=0;return !1;}},end:function(){t.clear_drop_stauts(!0)},min:function(){$(".file_dir_uploads .layui-layer-max").show(),$("#layui-layer-shade"+$(".file_dir_uploads").attr("times")).fadeOut()},restore:function(){$(".file_dir_uploads .layui-layer-max").hide(),$("#layui-layer-shade"+$(".file_dir_uploads").attr("times")).fadeIn()}})}else{if(null==e&&!t.isLayuiDrop)return!1;if(t.isLayuiDrop&&(e=t.filesList),$(".upload_file_body").html('
    • File nameFile sizeFile status
      ').removeClass("active"),Array.isArray(e)){for(a=0;a
      '+(l.path+"/"+l.name).replace("//","/")+''+l.size+''+t.is_upload_status(l.upload)+'
      '}$(".dropUpLoadFile").append(i)}else $(".dropUpLoadFile").append('
    • '+(e.path+"/"+e.name).replace("//","/")+''+e.size+''+t.is_upload_status(e.upload)+'
    • ')}},is_upload_status:function(e,t){switch(void 0===t&&(t=""),e){case-1:return'Fail'+(""!=t?","+t:"")+"";case 0:return'Waiting to upload';case 1:return'Uploaded';case 2:return'Uploading '+t+"";case 3:return'Stoped'}},set_upload_view:function(e,t){var i=$(".dropUpLoadFile li:eq("+e+")"),a=this,l=$(".file_upload_info");0==$(".file_upload_info .uploadProgress").length&&$(".file_upload_info").html('Total process ,Uploading ,Fail Speed Getting,Expect time Getting'),l.show().prev().hide().parent().css("paddingRight",0),a.errorLength>0&&l.find(".uploadError").text("("+a.errorLength+"份)").parent().show(),l.find(".uploadNumber").html("("+a.uploadLength+"/"+a.filesList.length+")"),l.find(".uploadProgress").html((a.uploadedSize/a.uploadAllSize*100).toFixed(2)+"%"),1===t.upload||-1===t.upload?(a.filesList[e].is_upload=!0,a.uploadLength+=1,i.find(".fileLoading").css({width:"100%",opacity:".5",background:-1==t.upload?"#ffadad":"#20a53a21"}),i.find(".filesize").text(t.size),i.find(".fileStatus").html(a.is_upload_status(t.upload,1===t.upload?"(Time:"+a.diff_time(a.startTime,a.endTime)+")":t.errorMsg)),i.find(".fileLoading").fadeOut(500,function(){$(this).remove();var e=$(".dropUpLoadFile");if(0==e.length)return!1;e[0].scrollHeight>e.height()&&e.scrollTop(e.scrollTop()+40)})):(i.find(".fileLoading").css("width",t.percent),i.find(".filesize").text(t.upload_size+"/"+t.size),i.find(".fileStatus").html(a.is_upload_status(t.upload,"("+t.percent+")")))},clear_drop_stauts:function(e){var t=new Date,i=this;if(!e)try{var a=bt_file.file_drop.to_size(bt_file.file_drop.uploadedSize/((t.getTime()-bt_file.file_drop.initTimer.getTime())/1e3));$(".file_upload_info").html(""+this.uploadLength+" uploaded,"+(this.errorLength>0?this.errorLength+"failures, ":"")+"time"+this.diff_time(this.initTimer,t)+",speed "+a+"/s").append($('').click(function(){$(".file_upload_info").hide().prev().show()}))}catch(e){}$(".layui-layer-btn0").removeAttr("style data-upload").text(lan.upload.upload),$.extend(bt_file.file_drop,{startTime:0,endTime:0,uploadLength:0,splitSize:2097152,filesList:[],errorLength:0,isUpload:!1,isUploadNumber:800,uploadAllSize:0,uploadedSize:0,topUploadedSize:0,uploadExpectTime:0,initTimer:0,speedInterval:null,timerSpeed:0,uploading:!1}),clearInterval(i.speedInterval)},upload_file:function(e,t){if(null==e&&0==this.uploadSuspend.length&&(e=0,t=0),this.filesList.length===t)return clearInterval(this.speedInterval),this.clear_drop_stauts(),bt_file.reader_file_list({path:bt_file.file_path,is_operating:!1}),!1;var i=this;i.splitEndTime=(new Date).getTime(),i.get_timer_speed(),i.splitStartTime=(new Date).getTime();var a=this.filesList[t],l="";if(null==a)return!1;l=Math.min(a.file.size,e+this.splitSize),i.fileSize=l-e,form=new FormData,0==e&&(i.startTime=new Date,a=$.extend(a,{percent:"0%",upload:2,upload_size:"0B"})),form.append("f_path",this.f_path+a.path),form.append("f_name",a.name),form.append("f_size",a.file.size),form.append("f_start",e),form.append("blob",a.file.slice(e,l)),i.set_upload_view(t,a),$.ajax({url:"/files?action=upload",type:"POST",data:form,async:!0,processData:!1,contentType:!1,success:function(s){"number"==typeof s?(i.set_upload_view(t,$.extend(a,{percent:(s/a.file.size*100).toFixed(2)+"%",upload:2,upload_size:i.to_size(s)})),i.uploadedSize+=l!=s?s:parseInt(l-e),i.upload_file(s,t)):s.status?(i.endTime=new Date,i.uploadedSize+=parseInt(l-e),i.set_upload_view(t,$.extend(a,{upload:1,upload_size:a.size})),i.upload_file(0,t+=1)):(i.set_upload_view(t,$.extend(a,{upload:-1,errorMsg:s.msg})),i.errorLength++)},error:function(a){if(void 0===i.filesList[t].req_error&&(i.filesList[t].req_error=1),i.filesList[t].req_error>2)return i.set_upload_view(t,$.extend(i.filesList[t],{upload:-1,errorMsg:"error"==a.statusText?lan.public.network_err:a.statusText})),i.errorLength++,i.upload_file(e,t+=1),!1;i.filesList[t].req_error+=1,i.upload_file(e,t)}})},get_timer_speed:function(e){var t=(new Date).getTime();if(t-this.speedLastTime>1e3){var i=this;null==e&&(e=200);var a=(i.splitEndTime-i.splitStartTime)/1e3;if(i.timerSpeed=(i.fileSize/a).toFixed(2),i.updateedSizeLast=i.uploadedSize,i.timerSpeed<2)return;$(".file_upload_info .uploadSpeed").text(i.to_size(isNaN(i.timerSpeed)?0:i.timerSpeed)+"/s");var l=i.time(parseInt((i.uploadAllSize-i.uploadedSize)/i.timerSpeed*1e3));isNaN(i.timerSpeed)||$(".file_upload_info .uploadEstimate").text(-1==l.indexOf("NaN")?l:"0 "+lan.bt.s),this.speedLastTime=t}},time:function(e){var t=Math.floor(e/36e5),i=Math.floor(e/6e4),a=parseInt(e%6e4/1e3),l=a+"sec";return i>0&&(l=i+"min"+a+"sec"),t>0&&(l=t+"hour"+Math.floor((e-36e5*t)/6e4)+"min"),l},diff_time:function(e,t){var i=t.getTime()-e.getTime(),a=Math.floor(i/6e4),l=i%6e4,s=l/1e3,n=s.toFixed(a>0?0:2)+lan.bt.s;return a>0&&(n=a+"min"+s.toFixed(0)+lan.bt.s),n},to_size:function(e){for(var t=[" B"," KB"," MB"," GB"," TB"," PB"],i=1024,a=0;a1)return e.file_groud_event({open:"soft_link"}),!1;var i=$(this).data("type"),a=$(".create_file_or_dir .nav_down_list");if(a.css({display:function(){return setTimeout(function(){a.removeAttr("style")},100),"none"}}),e.is_editor)return!1;e.is_editor=!0,$(".file_list_content").prepend('
      '+("icon"==bt.get_cookie("rank")?'":'')+"
      "),$(("icon"==bt.get_cookie("rank")?"textarea":"input")+"[name=createArea]").on("input",function(){"icon"==bt.get_cookie("rank")&&(this.style.height="auto",this.style.height=this.scrollHeight+"px")}).keyup(function(e){13==e.keyCode&&$(this).blur()}).blur(function(t){var a=$(this).val().replace(/[\r\n]/g,"");if(e.match_unqualified_string(a))return layer.msg('Name cannot contain /\\:*?"<>| symbol',{icon:2});""==a&&(a="newBlankDir"==i?"New directory":"New blank file"),setTimeout(function(){e.create_file_req({type:"newBlankDir"==i?"folder":"file",path:e.file_path+"/"+a},function(t){t.status&&e.reader_file_list({path:e.file_path}),layer.msg(t.msg,{icon:t.status?1:2})}),$(".createModel").remove(),e.is_editor=!1},300),t.preventDefault()}).focus(),t.stopPropagation(),t.preventDefault()}),$(".file_nav_view .favorites_file_path ul").on("click","li",function(t){var i=$(this).data("path"),a=$(this).data("type"),l=$(".favorites_file_path .nav_down_list");if("dir"==a)e.reader_file_list({path:i,is_operating:!0});else{if(null!=$(this).data("null"))return!1;var s=$(this).attr("title").split("."),n=s[s.length-1],o=e.determine_file_type(n);switch(o){case"text":openEditorView(0,i);break;case"video":e.open_video_play(i);break;case"images":e.open_images_preview({filename:$(this).attr("title"),path:i});break;default:e.reader_file_list({path:e.retrun_prev_path(i),is_operating:!0})}}l.css({display:function(){return setTimeout(function(){l.removeAttr("style")},100),"none"}}),t.stopPropagation(),t.preventDefault()}),$(".terminal_view").on("click",function(){web_shell()}),$(".share_file_list").on("click",function(){e.open_share_view()}),$(".mount_disk_list").on("click",".nav_btn",function(){var t=$(this).data("menu");e.reader_file_list({path:t,is_operating:!0})}),$(".mount_disk_list").on("click",".nav_down_list li",function(){var t=$(this).data("disk"),i=$(".mount_disk_list.thezoom .nav_down_list");i.css({display:function(){return setTimeout(function(){i.removeAttr("style")},100),"none"}}),e.reader_file_list({path:t,is_operating:!0})}),$(".file_nav_view").on("click",".manage_backup",function(t){e.manage_backup(),t.stopPropagation(),t.preventDefault()}),$(".file_nav_view").on("click",".recycle_bin",function(t){e.recycle_bin_view(),t.stopPropagation(),t.preventDefault()}),$(".file_nav_view .multi").on("click",".nav_btn_group",function(t){var i=$(this).data("type");void 0!==i&&e.batch_file_manage(i),t.stopPropagation(),t.preventDefault()}),$(".file_nav_view .multi").on("click",".nav_btn_group li",function(t){var i=$(this).data("type");e.batch_file_manage(i),t.stopPropagation(),t.preventDefault()}),$(".file_nav_view").on("click",".file_all_paste",function(){e.paste_file_or_dir()}),$(".file_list_header").on("click",".file_name,.file_size,.file_mtime,.file_accept,.file_user",function(t){var i=$(this).attr("data-tid"),a=$(this).find(".icon_sort").hasClass("active"),l=$(this).hasClass("active");return!$(this).find(".icon_sort").hasClass("active")&&$(this).hasClass("active")?$(this).find(".icon_sort").addClass("active"):$(this).find(".icon_sort").removeClass("active"),$(this).addClass("active").siblings().removeClass("active").find(".icon_sort").removeClass("active").empty(),$(this).find(".icon_sort").html(''),l||(a=!0),bt.set_cookie("files_sort",i),bt.set_cookie("name_reverse",a?"True":"False"),e.reader_file_list({reverse:a?"True":"False",sort:i}),!1}),$(".file_list_header .file_th").each(function(e,t){var i=bt.get_cookie("files_sort"),a=bt.get_cookie("name_reverse");$(this).attr("data-tid")===i&&($(this).addClass("active").siblings().removeClass("active").find(".icon_sort").removeClass("active").empty(),$(this).find(".icon_sort").html(''),"False"===a&&$(this).find(".icon_sort").addClass("active"))}),$(".file_list_header .file_check").on("click",function(t){var i=parseInt($(this).data("checkbox"));switch(i){case 0:$(this).addClass("active").removeClass("active_2").data("checkbox",1),$(".file_list_content .file_tr").addClass("active").removeClass("active_2"),$(".nav_group.multi").removeClass("hide"),$(".file_menu_tips").addClass("hide"),e.file_table_arry=e.file_list.slice();break;case 2:$(this).addClass("active").removeClass("active_2").data("checkbox",1),$(".file_list_content .file_tr").addClass("active"),$(".nav_group.multi").removeClass("hide"),$(".file_menu_tips").addClass("hide"),e.file_table_arry=e.file_list.slice();break;case 1:$(this).removeClass("active active_2").data("checkbox",0),$(".file_list_content .file_tr").removeClass("active"),$(".nav_group.multi").addClass("hide"),$(".file_menu_tips").removeClass("hide"),e.file_table_arry=[]}e.calculate_table_active()}),$(".file_list_content").on("click",".file_checkbox",function(t){var i=$(this).parents(".file_tr"),a=i.data("index"),l=i.data("filename");i.hasClass("active")?(i.removeClass("active"),e.remove_check_file(e.file_table_arry,"filename",l)):(i.addClass("active"),i.attr("data-filename",e.file_list[a].filename),e.file_table_arry.push(e.file_list[a])),e.calculate_table_active(),t.stopPropagation()}),$(".file_list_content").scroll(function(e){$(this).scrollTop()==$(this)[0].scrollHeight-$(this)[0].clientHeight?($(this).prev().css("opacity",1),$(this).next().css("opacity",0)):$(this).scrollTop()>0?$(this).prev().css("opacity",1):0==$(this).scrollTop()&&($(this).prev().css("opacity",0),$(this).next().css("opacity",1))}),$(".file_table_view .file_list_content").on("click",".file_tr",function(t){if($(t.target).hasClass("foo_menu_title")||$(t.target).parents().hasClass("foo_menu_title"))return!0;$(this).addClass("active").siblings().removeClass("active"),e.file_table_arry=[e.file_list[$(this).data("index")]],e.calculate_table_active(),t.stopPropagation(),t.preventDefault()}),$(".file_table_view .file_list_content").on("click",".file_name .iconfont",function(t){var i=$(this).parents(".file_tr"),a=i.data("index"),l=e.file_list[a];l.index=a,$(this).hasClass("icon-share1")&&e.info_file_share(l),$(this).hasClass("icon-favorites")&&e.cancel_file_favorites(l),t.stopPropagation()}),$(".file_table_view .file_list_content").on("dblclick",".file_tr",function(t){var i=$(this).data("index"),a=e.file_list[i];if($(t.target).hasClass("file_check")||$(t.target).parents(".foo_menu").length>0||$(t.target).hasClass("set_file_ps")||e.is_editor)return!1;if("dir"==a.type){if("Recycle_bin"==a.filename)return e.recycle_bin_view();e.reader_file_list({path:e.file_path+"/"+a.filename,is_operating:!0})}else switch(a.open_type){case"text":openEditorView(0,a.path);break;case"video":e.open_video_play(a);break;case"images":e.open_images_preview(a);break;case"compress":e.unpack_file_to_path(a)}t.stopPropagation(),t.preventDefault()}),$(".file_table_view .file_list_content").on("click",".file_title i,.file_ico_type .file_icon",function(t){var i=$(this).parents(".file_tr"),a=i.data("index"),l=e.file_list[a];if("dir"==l.type){if("Recycle_bin"==l.filename)return e.recycle_bin_view();e.reader_file_list({path:e.file_path+"/"+l.filename,is_operating:!0})}else layer.msg("compress"==l.open_type?"Double click to unzip the file":"Double click to edit the file");t.stopPropagation(),t.preventDefault()}),$(".file_list_content").on("contextmenu",function(e){return"createArea"==$(e.target).attr("name")||"rename_file_input"==$(e.target).attr("name")}),$(".selection_right_menu").on("contextmenu",function(e){return!1}),$(".file_list_content").on("mousedown",".file_tr",function(t){if(1===t.which&&($(t.target).hasClass("foo_menu_title")||$(t.target).parents().hasClass("foo_menu_title")))e.render_file_groud_menu(t,this),$(t.target).parent().addClass("foo_menu_click"),$(this).siblings().find(".foo_menu").removeClass("foo_menu_click"),$(this).addClass("active").siblings().removeClass("active");else{if(3!==t.which||e.is_editor)return!0;e.file_table_arry.length>1?e.render_files_multi_menu(t):(e.render_file_groud_menu(t,this),$(".content_right_menu").removeAttr("style"),$(this).addClass("active").siblings().removeClass("active"))}t.stopPropagation(),t.preventDefault()}),$(".filePage").on("change",".showRow",function(){var t=$(this).val();bt.set_cookie("showRow",t),e.reader_file_list({showRow:t,p:1,is_operating:!1})}),$(".filePage").on("click","div:nth-child(2) a",function(t){var i=$(this).attr("href").match(/p=([0-9]+)$/)[1];e.reader_file_list({path:e.path,p:i}),t.stopPropagation(),t.preventDefault()}),$(".file_list_content").on("click",".folder_size",function(t){var i=e.file_list[$(this).parents(".file_tr").data("index")],a=this;e.get_file_size({path:i.path},function(e){$(a).text(bt.format_size(e.size))}),t.stopPropagation(),t.preventDefault()}),$(".filePage").on("click","#file_all_size",function(t){if("/"===e.file_path)return layer.tips('The current directory is document root (/),calculate size will occupymassive server IO,continue?',this,{tips:[1,"red"],time:5e3}),!1;e.get_dir_size({path:e.file_path})}),$(".file_list_content").on("mousedown",function(t){ -if($(t.target).hasClass("file_checkbox")||$(t.target).hasClass("file_check")||$(t.target).hasClass("icon-share1")||$(t.target).hasClass("icon-favorites")||"i"==t.target.localName||$(t.target).parents(".app_menu_group").length>0||$(t.target).hasClass("createModel")||$(t.target).hasClass("editr_tr")||"createArea"==$(t.target).attr("name")||"rename_file_input"==$(t.target).attr("name")||$(t.target).hasClass("set_file_ps")||e.is_editor)return!0;if(3==t.which&&!e.is_editor)return $(".selection_right_menu").removeAttr("style"),e.render_file_all_menu(t,this),!0;$(".file_list_content").bind("mousewheel",function(){return!1});var i=$(this),a=0,l=i.offset().top,s=i.offset().left,n={top:t.clientY-$(this).offset().top,left:t.clientX-$(this).offset().left};$(document).unbind("mousemove").mousemove(function(t){var o={top:t.clientY-l>0&&t.clientY-l1?i.height():0,left:t.clientX-s>0&&t.clientX-s1?i.width():0},r={top:o.top>n.top?n.top:o.top,left:o.left>n.left?n.left:o.left};"list"==bt.get_cookie("rank")&&(r.top=r.top+40);var c=Math.min(Math.abs(o.left-n.left),s+i.width()-r.left),d=Math.min(Math.abs(o.top-n.top),l+i.height()-r.top);if(t.clientY-l<0){var p=Math.abs(t.clientY-l);i.scrollTop(i.scrollTop()-p),0!=i.scrollTop()&&(a+=p),d+=a}if(t.clientY-(l+i.height())>1){var _=t.clientY-(l+i.height());i.scrollTop(i.scrollTop()+_),i[0].scrollHeight-i[0].scrollTop!==i[0].clientHeight&&(a+=_),d+=a,r.top=r.top-a}if(n.top==o.top||n.left==o.left)return!0;e.enter_files_box().show().css({left:r.left+"px",top:r.top+"px",width:c+"px",height:d+"px"});var f=e.enter_files_box().offset().top,h=e.enter_files_box().offset().left,u=e.enter_files_box().offset().left+e.enter_files_box().width(),m=e.enter_files_box().offset().top+e.enter_files_box().height();$(i).find(".file_tr").each(function(e,t){var i=$(t).offset().top,a=$(t).offset().left,l=$(t).offset().top+$(t).height(),s=$(t).offset().left+$(t).width();"icon"==bt.get_cookie("rank")?s>=h&&a<=u&&l>=f&&i<=m?$(t).addClass("active"):$(t).removeClass("active"):s>=h&&l>=f&&i<=m?$(t).addClass("active"):$(t).removeClass("active")})}),$(document).on("mouseup",function(){var t=[],a=e.enter_files_box().offset().top,l=e.enter_files_box().offset().left,s=e.enter_files_box().offset().left+e.enter_files_box().width(),n=e.enter_files_box().offset().top+e.enter_files_box().height();$(i).find(".file_tr").each(function(e,i){var o=$(i).offset().top,r=$(i).offset().left,c=$(i).offset().top+$(i).height(),d=$(i).offset().left+$(i).width();"icon"==bt.get_cookie("rank")?d>=l&&r<=s&&c>=a&&o<=n&&t.push($(i).data("index")):d>=l&&c>=a&&o<=n&&t.push($(i).data("index"))}),e.render_file_selected(t),e.enter_files_box().remove(),$(".file_list_content").unbind("mousewheel")}),t.stopPropagation(),t.preventDefault()}),$(".file_list_content").on("blur",".set_file_ps",function(t){var i=$(this).parents(".file_tr").data("index"),a=e.file_list[i],l=$(this).val(),s=$(this).data("value"),n=this;if(l==s)return!1;bt_tools.send("files/set_file_ps",{filename:a.path,ps_type:0,ps_body:l},function(e){$(n).data("value",l)},{tips:"Set ps",tips:!0})}),$(".file_list_content").on("keyup",".set_file_ps",function(e){13==e.keyCode&&$(this).blur(),e.stopPropagation()}),$(".file_list_header").on("mousedown",".file_width_resize",function(e){return!1}),$(".cut_view_model").on("click",function(){var e=$(this).data("type");$(".file_table_view").addClass("icon"==e?"icon_view":"list_view").removeClass("icon"!=e?"icon_view":"list_view").scrollLeft(0),bt.set_cookie("rank",e),$(this).addClass("active").siblings().removeClass("active")}),$(".file_list_content").on("click",".set_operation_group a",function(t){var i=$(this).parents(".file_tr").data(),a=$(this).data("type"),l=e.file_list[i.index];if("more"==a)return!0;l.open=a,l.index=i.index,l.type_tips="file"==l.type?"File":"Directory",e.file_groud_event(l)})},enter_files_box:function(){return 0==$("#web_mouseDrag").length&&$("
      ",{id:"web_mouseDrag",style:["position:absolute; top:0; left:0;","border:1px solid #072246; background-color: #cce8ff;","filter:Alpha(Opacity=15); opacity:0.15;","overflow:hidden;display:none;z-index:9;"].join("")}).appendTo(".file_table_view"),$("#web_mouseDrag")},clear_table_active:function(){this.file_table_arry=[],$(".file_list_header .file_check").removeClass("active active_2"),$(".file_list_content .file_tr").removeClass("active app_menu_operation"),$(".file_list_content .file_tr .file_ps .foo_menu").removeClass("foo_menu_click"),$(".app_menu_group").remove()},calculate_table_active:function(){var e=this,t=$(".file_list_header .file_check");0==this.file_table_arry.length?t.removeClass("active active_2").data("checkbox",0):this.file_table_arry.length==this.file_list.length?t.addClass("active").removeClass("active_2").data("checkbox",1):t.addClass("active_2").removeClass("active").data("checkbox",2),this.file_table_arry.length>0?($(document).unbind("keydown").on("keydown",function(t){var i=t.keyCode,a=t.target.localName.toLowerCase();window.navigator.userAgent.indexOf("Mac");if("input"==a||"textarea"==a)return!0;t.ctrlKey&&67==i&&(1==e.file_table_arry.length?(e.file_groud_event($.extend(e.file_table_arry[0],{open:"copy"})),$(".file_all_paste").removeClass("hide")):e.file_table_arry.length>1&&e.batch_file_manage("copy")),t.ctrlKey&&88==i&&(1==e.file_table_arry.length?(e.file_groud_event($.extend(e.file_table_arry[0],{open:"shear"})),$(".file_all_paste").removeClass("hide")):e.file_table_arry.length>1&&e.batch_file_manage("shear"))}),this.file_table_arry.length>1?($(".nav_group.multi").removeClass("hide"),$(".file_menu_tips").addClass("hide")):($(".nav_group.multi").addClass("hide"),$(".file_menu_tips").removeClass("hide"))):($(".nav_group.multi").addClass("hide"),$(".file_menu_tips.multi").removeClass("hide"),$(document).unbind("keydown")),$(".selection_right_menu,.file_path_input .file_dir_item .nav_down_list").removeAttr("style"),e.set_menu_line_view_resize()},set_dir_view_resize:function(){var e=$(".file_path_input"),t=$(".file_path_input .file_dir_view"),i=t.attr("data-width"),a=null;if(i?parseInt(i):(i=t.width(),t.attr("data-width",i)),t.width()-i<90){var l=0;$($(".file_path_input .file_dir_view .file_dir_item").toArray().reverse()).each(function(){var t=0;$(this).attr("data-width")?t=parseInt($(this).attr("data-width")):($(this).attr("data-width",$(this).width()),t=$(this).width()),l+=t,e.width()-l<=90?$(this).addClass("hide"):$(this).removeClass("hide")})}a=t.children(".file_dir_item.hide").clone(!0);0==t.children(".file_dir_item.hide").length?e.removeClass("active").find(".file_dir_omit").addClass("hide"):(a.each(function(){0==$(this).find(".glyphicon-hdd").length&&$(this).find(".file_dir").before('')}),e.addClass("active").find(".file_dir_omit").removeClass("hide"),e.find(".file_dir_omit .nav_down_list").empty().append(a),e.find(".file_dir_omit .nav_down_list .file_dir_item").removeClass("hide"))},set_menu_line_view_resize:function(){var e=$(".file_nav_view").width(),t=0,i=0,a=$(".mount_disk_list"),l=$(".nav_group.multi");a.attr("data-width")||a.attr("data-width",a.innerWidth()),l.attr("data-width")||0==l.innerWidth()||-1==l.innerWidth()||l.attr("data-width",l.innerWidth()),t=parseInt(a.attr("data-width")),parseInt(l.attr("data-width")),$(".file_nav_view>.nav_group").not(".mount_disk_list").each(function(){i+=$(this).innerWidth()}),i+=$(".menu-header-foot").innerWidth(),e-i.nav_btn_group").each(function(e){e>=$(".batch_group_list>.nav_btn_group").length-(indexs+2)?$(this).hide():$(this).show()}),$(".batch_group_list>.nav_btn_group:last-child").removeClass("hide").show()):($(".batch_group_list>.nav_btn_group").css("display","inline-block"),$(".batch_group_list>.nav_btn_group:last-child").addClass("hide"))},set_file_forward:function(){var e=this,t=$(".forward_path span");1==e.file_operating.length?t.addClass("active"):e.file_pointer==e.file_operating.length-1?(t.eq(0).removeClass("active"),t.eq(1).addClass("active")):0==e.file_pointer?(t.eq(0).addClass("active"),t.eq(1).removeClass("active")):t.removeClass("active")},set_file_view:function(){var e=$(".file_list_content"),t=this.area[1]-$(".file_table_view")[0].offsetTop-170;$(".file_bodys").height(this.area[1]-100),50*this.file_list.length>t?(e.attr("data-height",e.data("height")||e.height()).css({overflow:"hidden","overflow-y":"auto",height:t+"px"}),$(".file_shadow_bottom").css("opacity",1)):(e.css({overflow:"hidden","overflow-y":"auto",height:t+"px"}),$(".file_shadow_top,.file_shadow_bottom").css("opacity",0))},open_share_view:function(){var e=this;layer.open({type:1,shift:5,closeBtn:2,area:["850px","580px"],title:"Share list",content:'
      Share nameShare addressExpiration dateOpt
      ',success:function(){e.render_share_list(),$(".download_url_list").on("click",".info_down",function(){var t=$(this).attr("data-index");e.file_share_view(e.file_share_list[t],"list")}),$(".download_table .download_url_page").on("click","a",function(t){var i=$(this).attr("href").match(/p=([0-9]+)$/)[1];e.render_share_list({p:i}),t.stopPropagation(),t.preventDefault()})}})},render_share_list:function(e){var t=this,i="";void 0===e&&(e={p:1}),bt_tools.send("files/get_download_url_list",e,function(a){t.file_share_list=a.data,a.data.length>0?$.each(a.data,function(e,t){i+=''+t.ps+''+t.filename+""+bt.format_data(t.expire)+'Details | Close'}):i='No share data',$(".download_url_list").html(i),$(".download_url_page").html(a.page),$(".download_table").on("click",".del_down",function(){var i=$(this).attr("data-id"),a=$(this).attr("data-ps");t.remove_download_url({id:i,fileName:a},function(i){i.status&&t.render_share_list(e),layer.msg(i.msg,{icon:i.status?1:2})})})},"Share list")},remove_check_file:function(e,t,i){for(var a=e.length;a--;)e[a][t]==i&&e.splice(a,1)},open_download_view:function(){var e=this;e.reader_form_line({url:"DownloadFile",beforeSend:function(e){return{url:e.url,path:e.path,filename:e.filename}},overall:{width:"310px"},data:[{label:"URL address:",name:"url",placeholder:"URL address",value:"http://",eventType:["input","focus"],input:function(){var e=$(this).val(),t=e.split("/");$('[name="filename"]').val(t[t.length-1])}},{label:"Download to:",name:"path",placeholder:"Download to",value:e.file_path},{label:"File name:",name:"filename",placeholder:"Save file name",value:"",eventType:"enter",enter:function(){$(".download_file_view .layui-layer-btn0").click()}}]},function(t,i){var a=bt.open({type:1,title:"Download file",area:"500px",shadeClose:!1,skin:"download_file_view",content:i[0].outerHTML,btn:["Comfirm","Close"],success:function(){t.setEvent()},yes:function(i,l){var s=t.getVal();if(!bt.check_url(s.url))return layer.msg("Please enter valid URL address..",{icon:2}),!1;t.submitForm(function(t){e.render_present_task_list(),layer.msg(t.msg,{icon:t.status?1:2}),a.close()})}})})},set_style_width:function(e,t){var i=bt.get_cookie("formHeader")||$("#file_list_info").html(),a="",l=new RegExp("\\.file_"+e+"\\s?\\{width\\s?\\:\\s?(\\w+)\\s\\!important;\\}","g"),s={name:150,type:80,size:80,mtime:150,accept:80,user:80,ps:150};a=i.replace(l,function(i,a,l,n){return".file_"+e+"{width:"+(t<80?s[e]+"px":t+"px")+" !important;}"}),$("#file_list_info").html(a)},set_file_table_width:function(){var e=$(".file_table_view")[0].offsetWidth,t=0,i=0,a=0,l="",s=0,n=45,o="",r={};$.each(this.file_header,function(e,a){"auto"==a?(t++,r[e]=0):(i+=a,l+="."+e+"{width:"+("file_operation"!=e?a:a-16)+"px !important;}")}),this.is_mobile&&$(".file_operation.file_th").attr("style","margin-right:-10px !important;"),this.file_list.length*n>$(".file_list_content").height()?(r.file_tr=e-(this.is_mobile?0:this.scroll_width),e=e,o+=".file_td.file_operation{width:"+(this.file_header.file_operation-(this.is_mobile?0:this.scroll_width)-10)+"px !important;}",o+=".file_th.file_operation{padding-right:"+(10+(this.is_mobile?0:this.scroll_width))+"px !important}"):(e=e,r.file_tr=e,this.is_mobile&&(o+=".file_td.file_operation{width:"+(this.file_header.file_operation-20)+"px !important;}")),r.file_list_header=e,a=e-i,s=a/t,$.each(r,function(e,t){l+="."+e+"{width:"+(0==t?s:t)+"px !important;}"}),$("#file_list_info").html(l+o)},render_path_list:function(e){var t=this,i='
      ',a="",l=this.file_path.split("/").splice(1),s=this.file_path.split("/")[0];"Windows"===bt.os?(0==l.length&&(l=[]),l.unshift('Local disk ('+s+")")):("/"==this.file_path&&(l=[]),l.unshift("Root dir"));for(var n=0;n '+l[n]+' ';$(".path_input").val("").attr("data-path",this.file_path);var o=$(".file_path_input .file_dir_view");o.html(i),o.attr("data-width",o.width()),t.set_dir_view_resize.delay(t,100)},render_path_down_list:function(e,t,i){var a=this,l="",s=$(e).parent().next().find(".file_dir").attr("title");this.get_dir_list({path:t},function(i){$.each(a.data_reconstruction(i.DIR),function(e,i){var a=("/"!=t?t:"")+"/"+i.filename;l+='
    • '+i.filename+"
    • "}),$(e).html(l)})},reader_file_list:function(e,t){var i=this,a="",l="",s=bt.get_cookie("rank"),n=bt.get_cookie("record_paste_type");"null"!=n&&null!=n?$(".file_nav_view .file_all_paste").removeClass("hide"):$(".file_nav_view .file_all_paste").addClass("hide"),$(".file_table_view").removeClass(".list_view,.icon_view").addClass("list"==s?"list_view":"icon_view"),$(".cut_view_model:nth-child("+("list"==s?"2":"1")+")").addClass("active").siblings().removeClass("active"),this.file_images_list=[],this.get_dir_list(e,function(s){if(!1===s.status&&s.msg.indexOf("The specified directory does not exist!")>-1)return i.reader_file_list({path:"/www"});i.file_path=i.path_check(s.PATH),i.file_list=$.merge(i.data_reconstruction(s.DIR,"DIR"),i.data_reconstruction(s.FILES)),i.is_recycle=s.FILE_RECYCLE,i.file_store_list=s.STORE,bt.set_cookie("Path",i.path_check(s.PATH)),i.reader_file_list_content(i.file_list,function(n){$(".path_input").attr("data-path",i.file_path),$(".file_nav_view .multi").addClass("hide"),$(".selection_right_menu").removeAttr("style"),$.each(["100","200","500","1000","2000"],function(e,t){a+='"});var o=$(s.PAGE);o.append('per pageitem(s)"),$(".filePage").html('
      Total '+n.is_dir_num+" directory, "+(i.file_list.length-n.is_dir_num)+'file(s), size:Click to calculate
      '+o[0].outerHTML),e.is_operating&&i.file_operating[i.file_pointer]!=s.PATH&&(l=i.file_operating[i.file_pointer+1],void 0!==l&&l!=s.PATH&&i.file_operating.splice(i.file_pointer+1),i.file_operating.push(s.PATH),i.file_pointer=i.file_operating.length-1),i.render_path_list(),i.set_file_forward(),i.render_favorites_list(),i.set_file_view(),i.set_file_table_width(),t&&t(s)})})},data_reconstruction:function(e,t,i){var a=this,l=[],s=[["/etc","PS: System files directory"],["/home","PS: Home directory"],["/tmp","PS: Common temporary files directory"],["/root","PS: Main directory of system admin"],["/usr","PS: System application directory"],["/boot","PS: System run directory"],["/lib","PS: System source file directory"],["/mnt","PS: Store temporary mapped file system"],["/www","PS: Aapanel program directory"],["/bin","PS: Store binary executable file directory"],["/dev","PS: Storage device file directory"],["/www/wwwlogs","PS: Default site logs directory"],["/www/server","PS: Aapanel soft installed directory"],["/www/wwwlogs","PS: Site logs directory"],["/www/Recycle_bin",lan.files.recycle_bin_dir],["/www/server/panel","PS: Aapanel main program directory, do not move"],["/www/server/panel/plugin","PS: Aapanel plugin directory"],["/www/server/panel/BTPanel","PS: Aapanel directory"],["/www/server/panel/BTPanel/static","PS: Aapanel static directory"],["/www/server/panel/BTPanel/templates","PS: Aapanel templates directory"],[bt.get_cookie("backup_path"),"PS: Default backup directory"],[bt.get_cookie("sites_path"),"PS: Default site directory"]];return e.length<1?[]:($.each(e,function(e,i){var n=i.split(";"),o="",r=n[0].split("."),c=r[r.length-1];switch(n[0]){case".user.ini":o=lan.files.php_profile;break;case".htaccess":o=lan.files.apache_profile;break;case"swap":o=lan.files.swap_file}-1!=n[0].indexOf("Recycle_bin")&&(o=lan.files.swap_file),-1!=n[0].indexOf(".upload.tmp")&&(o=lan.files.recycle_bin_dir);for(var d=0;d0?($.each(this.file_store_list,function(t,i){e+='
    • '+i.name+"
    • "}),e+='
    • Management
    • '):e='
    • (Empty)
    • ',$(".favorites_file_path .nav_down_list").html(e)},set_favorites_manage:function(){var e=this;layer.open({type:1,title:"Manage Favorites",area:["850px","580px"],closeBtn:2,shift:5,shadeClose:!1,content:"
      PathOpt
      ",success:function(t){e.render_favorites_type_list(),setTimeout(function(){$(t).css("top",($(window).height()-$(t).height())/2)},50)},cancel:function(){e.reader_file_list({path:e.file_path})}})},render_favorites_type_list:function(){var e="";this.$http("get_files_store",function(t){t.length>0?$.each(t,function(t,i){e+=''+i.path+'Del"}):e='No favorites',$(".favorites_body").html(e),jQuery.prototype.fixedThead?$(".stroe_tab_list .divtable").fixedThead({resize:!1}):$(".stroe_tab_list .divtable").css({overflow:"auto"})})},load_favorites_index_list:function(){var e=this;this.$http("get_files_store",function(t){e.file_store_list=t,e.render_favorites_list()})},del_favorites:function(e){var t=this;layer.confirm("Comfirm delete path【"+e+"】?",{title:"Delete favorites",closeBtn:2,icon:3},function(i){t.$http("del_files_store",{path:e},function(e){e.status&&t.render_favorites_type_list(),layer.msg(e.msg,{icon:e.status?1:2})})})},reader_file_list_content:function(e,t){var i="",a=this,l=0,s=0;$.each(e,function(e,t){t.filename;var n=bt.get_random(10),o=(a.file_path+"/"+t.filename).replace("//","/"),r=a.determine_file_type(t.ext,"compress"),c=function(){var e="open";switch(a.determine_file_type(t.ext)){case"images":e="Preview";break;case"video":e="Play";break;default:e="compress"==a.determine_file_type(t.ext)?"":"Edit"}return"dir"==t.type&&(e="Open"),e}();a.file_list[e].only_id=n,i+='
      "+t.filename+t.soft_link+""+(t.caret?'':"")+(0!=t.down_id?'':"")+'
      '+("dir"==t.type?"directory":a.ext_type_tips(t.ext))+'
      '+t.user+" / "+t.root_level+'
      '+("dir"==t.type?'Calculate':bt.format_size(t.size))+'
      '+bt.format_data(t.mtime)+'
      '+(t.is_os_ps?t.ps:'')+'
      '+c+' | Copy | Cut | Rename | PMSN | '+(r?"Unzip":"Zip")+' | Del | More
      ',"dir"==t.type&&l++,t.path=o,t.open_type=a.determine_file_type(t.ext),"images"==t.open_type&&(t.images_id=s,a.file_images_list.push(t.path),s++)}),$(".file_list_content").html(i),t&&t({is_dir_num:l}),a.clear_table_active()},render_file_disk_list:function(){var e=this,t="",i="";e.get_disk_list(function(a){$.each(a,function(e,a){t+='",i+='
    • '+("/"==a.path?"Root dir":a.path)+" ("+a.size[2]+")
    • "}),$(".mount_disk_list").html('
      '+lan.files.mounted_disk+'
      '+t+"
      "),e.set_menu_line_view_resize()})},render_file_groud_menu:function(e,t){var i=this,a=$(t).data("index"),l="Open",s=i.file_list[a],n=["zip","rar","gz","war","tgz","bz2"],o={open:l,split_0:!0,download:"Download",share:"Share file",cancel_share:"Cancel share",favorites:"Favorites file",cancel_favorites:"Cancel favorites",split_1:!0,authority:"Permission",split_2:!0,copy:"Copy",shear:"Cut",rename:"Rename",del:"Delete",split_3:!0,compress:"Compress",unzip:"Unzip",open_find_dir:"Open file location",split_4:!0,property:"Properties"};switch(i.determine_file_type(s.ext)){case"images":l="Preview";break;case"video":l="Play";break;default:l="Edit"}o.open="dir"==s.type?"Open":l,"dir"===s.type&&delete o.download,"compress"==s.open_type&&delete o.open,0!=s.down_id?delete o.share:(delete o.cancel_share,o.share="dir"==s.type?"Share dir":"Share file"),!1!==s.caret?delete o.favorites:(delete o.cancel_favorites,o.favorites="dir"==s.type?"Favorites dir":"Favorites file"),"php"==s.ext&&(o.dir_kill="文件查杀"),"php"!=s.ext&&"dir"!=s.type&&delete o.dir_kill;var r=0;$.each(n,function(e,t){t==s.ext&&r++}),0==r&&delete o.unzip,s.is_search?o.open_find_dir="dir"==s.type?"Open dir":"Open file location":delete o.open_find_dir,i.file_selection_operating=o,i.reader_menu_list({el:$(".selection_right_menu"),ev:e,data:s,list:o})},render_file_all_menu:function(e,t){var i=this,a={refresh:"Refresh",split_0:!0,upload:"Upload",create:["New file/folder",{create_dir:"New folder",create_files:"New file",soft_link:"Softlink"}],web_shell:"Terminal",split_1:!0,paste:"Paste"},l=bt.get_cookie("record_paste_type");"null"!=l&&null!=l||(delete a.split_1,delete a.paste),i.reader_menu_list({el:$(".selection_right_menu"),ev:e,data:{},list:a})},render_files_multi_menu:function(e){var t=this,i=[["copy","Copy"],["shear","cut"],["authority","Permission"],["compress","Compress"],["del","Delete"]],a=$(".selection_right_menu").find("ul"),l=a.height(),s=a.width(),n=e.clientX-(this.area[0]-e.clientX'):a.append($('
    • '+i[1]+"
    • ").append(s).on("click",{type:i[0],data:t.file_table_arry},function(e){$(".selection_right_menu").removeAttr("style"),t.batch_file_manage(e.data.type),e.stopPropagation(),e.preventDefault()}))}),$(".selection_right_menu").css({left:n,top:e.clientY-(this.area[1]-e.clientY'):(Array.isArray(l)&&(s=$('
        '),n=s.find(".set_group"),$.each(l[1],function(i,a){n.append($('
      • '+a+"
      • ").on("click",{type:i,data:e.data},function(i){t.file_groud_event($.extend(i.data.data,{open:i.data.type,index:parseInt($(e.ev.currentTarget).data("index")),element:e.ev.currentTarget,type_tips:"dir"==e.data.type?"folder":"file"})),e.el.removeAttr("style"),i.stopPropagation(),i.preventDefault()}))})),i.append($('
      • '+(Array.isArray(l)?l[0]:l)+"
      • ").append(s).on("click",{type:a,data:e.data},function(i){t.file_groud_event($.extend(i.data.data,{open:i.data.type,index:parseInt($(e.ev.currentTarget).data("index")),element:e.ev.currentTarget,type_tips:"dir"==e.data.type?"folder":"file"})),"compress"!=a&&"create"!=a&&e.el.removeAttr("style"),i.stopPropagation(),i.preventDefault()})))}),a=i.innerHeight(),n=e.ev.clientY-(this.area[1]-e.ev.clientY'+lan.files.recycle_bin_warning+"",function(){t.$http("SetBatchData",e,function(e){e.status&&t.reader_file_list({path:t.file_path}),layer.msg(e.msg,{icon:e.status?1:2})})})},batch_file_paste:function(){var e=this,t=bt.get_cookie("record_paste_type");this.check_exists_files_req({dfile:this.file_path},function(i){if(i.length>0){for(var a="",l=0;l'+i[l].filename+""+ToSize(i[l].size)+""+getLocalTime(i[l].mtime)+"";var s='
        '+a+"
        File nameSizeLast edit time
        ";SafeMessage("The following files will be overwritten",s,function(){e.$http("BatchPaste",{type:t,path:e.file_path},function(t){t.status&&(bt.set_cookie("record_paste_type",null),e.reader_file_list({path:e.file_path})),layer.msg(t.msg,{icon:t.status?1:2})})})}else e.$http("BatchPaste",{type:t,path:e.file_path},function(t){t.status&&(bt.set_cookie("record_paste_type",null),e.reader_file_list({path:e.file_path})),layer.msg(t.msg,{icon:t.status?1:2})})})},recycle_bin_view:function(){var e=this;layer.open({type:1,shift:5,closeBtn:2,area:["80%","606px"],title:lan.files.recycle_bin_title,content:'
        '+lan.files.recycle_bin_on+'
        '+lan.files.recycle_bin_on_db+'
        '+lan.files.recycle_bin_ps+'

        '+lan.files.recycle_bin_type1+'

        '+lan.files.recycle_bin_type2+'

        '+lan.files.recycle_bin_type3+'

        '+lan.files.recycle_bin_type4+'

        '+lan.files.recycle_bin_type5+'

        '+lan.files.recycle_bin_type6+'

        '+lan.files.recycle_bin_th1+" "+lan.files.recycle_bin_th2+" "+lan.files.recycle_bin_th3+' '+lan.files.recycle_bin_th4+' '+lan.files.recycle_bin_th5+'
        ',success:function(){-1!=window.location.href.indexOf("database")?($(".re-con-menu p:last-child").addClass("on").siblings().removeClass("on"),e.render_recycle_list(6)):e.render_recycle_list(1),$(".re-con-menu").on("click","p",function(){var t=$(this).data("type");$(this).addClass("on").siblings().removeClass("on"),e.render_recycle_list(t)})}})},render_recycle_list:function(e){var t=this;this.$http("Get_Recycle_bin",function(i){function a(e){var t=e.split("."),i=t.length-1;return t=t[i],t}function l(e){for(var t=["jpg","jpeg","png","bmp","gif","tiff","ico"],i=0;i20&&(o=o.substring(0,20)+"..."),r.length>20&&(r=r.substring(0,20)+"..."),s+=' '+o+' '+r+" "+ToSize(i.dirs[n].size)+" "+getLocalTime(i.dirs[n].time)+' "+lan.files.recycle_bin_re+' | "+lan.files.recycle_bin_del+" "}for(n=0;n20&&(o=o.substring(0,20)+"..."),r.length>20&&(r=r.substring(0,20)+"..."),s+=' '+o+' '+r+" "+ToSize(i.files[n].size)+" "+getLocalTime(i.files[n].time)+' "+lan.files.recycle_bin_re+' | "+lan.files.recycle_bin_del+" "}else{var o=i.files[n].name.replace(/'/,"\\'"),r=i.files[n].dname;o.length>20&&(o=o.substring(0,20)+"..."),r.length>20&&(r=r.substring(0,20)+"..."),s+=' '+o.replace("BTDB_","")+' mysql://'+r.replace("BTDB_","")+" - "+getLocalTime(i.files[n].time)+' "+lan.files.recycle_bin_re+' | "+lan.files.recycle_bin_del+" "}return void $("#RecycleBody").html(s);case 2:for(n=0;n20&&(o=o.substring(0,20)+"..."),r.length>20&&(r=r.substring(0,20)+"..."),s+=' '+o+' '+r+" "+ToSize(i.dirs[n].size)+" "+getLocalTime(i.dirs[n].time)+' "+lan.files.recycle_bin_re+' | "+lan.files.recycle_bin_del+" "}return void $("#RecycleBody").html(s);case 3:for(n=0;n20&&(o=o.substring(0,20)+"..."),r.length>20&&(r=r.substring(0,20)+"..."),s+=' '+o+' '+r+" "+ToSize(i.files[n].size)+" "+getLocalTime(i.files[n].time)+' "+lan.files.recycle_bin_re+' | "+lan.files.recycle_bin_del+" "}return void $("#RecycleBody").html(s);case 4:for(n=0;n20&&(o=o.substring(0,20)+"..."),r.length>20&&(r=r.substring(0,20)+"..."),s+=' '+o+' '+r+" "+ToSize(i.files[n].size)+" "+getLocalTime(i.files[n].time)+' "+lan.files.recycle_bin_re+' | "+lan.files.recycle_bin_del+" "}return void $("#RecycleBody").html(s);case 5:for(n=0;n20&&(o=o.substring(0,20)+"..."),r.length>20&&(r=r.substring(0,20)+"..."),s+=' '+o+' '+r+" "+ToSize(i.files[n].size)+" "+getLocalTime(i.files[n].time)+' "+lan.files.recycle_bin_re+' | "+lan.files.recycle_bin_del+" "}return void $("#RecycleBody").html(s);case 6:for(n=0;n20&&(o=o.substring(0,20)+"..."),r.length>20&&(r=r.substring(0,20)+"..."),s+=' '+o.replace("BTDB_","")+' mysql://'+r.replace("BTDB_","")+" - "+getLocalTime(i.files[n].time)+' "+lan.files.recycle_bin_re+' | "+lan.files.recycle_bin_del+" "}return void $("#RecycleBody").html(s)}$("#RecycleBody").html(s)})},recycle_bin_view:function(){var e=this;layer.open({title:lan.files.recycle_bin_title,type:1,skin:"recycle_view",area:["80%","672px"],closeBtn:2,content:'
        '+lan.files.recycle_bin_on+'
        '+lan.files.recycle_bin_on_db+'
        '+lan.files.recycle_bin_ps+'

        '+lan.files.recycle_bin_type1+'

        '+lan.files.recycle_bin_type2+'

        '+lan.files.recycle_bin_type3+'

        '+lan.files.recycle_bin_type4+'

        '+lan.files.recycle_bin_type5+'

        '+lan.files.recycle_bin_type6+'

        ',success:function(){-1!=window.location.href.indexOf("database")?($(".re-con-menu p:last-child").addClass("on").siblings().removeClass("on"),$(".re-con-menu p:eq(5)").click()):$(".re-con-menu p:eq(0)").click();var t=e.render_recycle_list();$(".re-con-menu").on("click","p",function(){$(this).data("type");$(this).addClass("on").siblings().removeClass("on"),t.$refresh_table_list(!0)})}})},render_recycle_list:function(){var e=this;$("#recycle_table").empty();var t=bt_tools.table({el:"#recycle_table",url:"/files?action=Get_Recycle_bin",height:480,dataFilter:function(t){var i=[];switch($(".re-con-menu p.on").index()){case 0:for(let e=0;e-1?(l.dname=l.dname.replace("BTDB_",""),l.name=l.name.replace("BTDB_",""),i.push($.extend(l,{type:"files"}))):"images"==n?i.push($.extend(l,{type:n})):i.push($.extend(l,{type:"files"}))}break;case 1:for(let e=0;e-1&&(a.dname=a.dname.replace("BTDB_",""),a.name=a.name.replace("BTDB_",""),i.push($.extend(a,{type:"files"})))}}return $("#Set_Recycle_bin").attr("checked",t.status),$("#Set_Recycle_bin_db").attr("checked",t.status_db),{data:i}},column:[{type:"checkbox",class:"",width:18},{fid:"name",title:lan.files.recycle_bin_th1,width:155,template:function(e){return'
        '+e.name+"
        "}},{fid:"dname",title:lan.files.recycle_bin_th2,template:function(e){return''+e.dname+""}},{fid:"size",title:lan.files.recycle_bin_th3,width:85,template:function(e){return''+bt.format_size(e.size)+""}},{fid:"time",title:lan.files.recycle_bin_th4,width:180,template:function(e,t){return''+bt.format_data(e.time)+""}},{type:"group",align:"right",width:250,title:lan.files.recycle_bin_th5,group:[{title:lan.files.recycle_bin_re,event:function(e,t,i,a,l){bt_file.ReRecycleBin(e.rname,function(){l.$delete_table_row(t)})}},{title:lan.files.recycle_bin_del,event:function(e,t,i,a,l){bt_file.DelRecycleBin(e.rname,function(){l.$delete_table_row(t)})}}]}],tootls:[{type:"batch",positon:["left","bottom"],placeholder:"Please Choose",buttonValue:"Execute",disabledSelectValue:"Please select the port that needs batch operation!",selectList:[{title:"Restore",url:"/files?action=Re_Recycle_bin",load:!0,param:function(e){return{path:e.rname}},callback:function(e){bt.confirm({title:"Restore files",msg:"Batch restore selected files, do you want to continue?",icon:0},function(i){layer.close(i),e.start_batch({},function(e){for(var i="",a=0;a"+l.name+'
        '+(l.request.status?"Successful recovery":"Recovery failed")+"
        "}t.$batch_success_table({title:"Restore files",th:"File name",html:i}),t.$refresh_table_list(!0)})})}},{title:"Delete files permanently",url:"/files?action=Del_Recycle_bin",load:!0,param:function(e){return{path:e.rname}},callback:function(e){bt.confirm({title:"Delete selected files",msg:"Delete the selected file. The file will be completely deleted and cannot be recovered. Do you want to continue?",icon:0},function(i){layer.close(i),e.start_batch({},function(e){for(var i="",a=0;a"+l.name+'
        '+(l.request.status?"Successfully deleted":"Failed to delete")+"
        "}t.$batch_success_table({title:"Delete multiple files",th:"File name",html:i}),t.$refresh_table_list(!0)})})}}]}]});return bt_tools.$fixed_table_thead("#recycle_table .divtable"),t},Set_Recycle_bin:function(e){var t=layer.msg(lan.public.the,{icon:16,time:0,shade:[.3,"#000"]}),i=this,a={};1==e&&(a={db:e}),$.post("/files?action=Recycle_bin",a,function(a){layer.close(t),a.status&&null==e&&(i.is_recycle=$("#Set_Recycle_bin").prop("checked")),layer.msg(a.msg,{icon:a.status?1:5})})},ReRecycleBin:function(e,t){layer.confirm(lan.files.recycle_bin_re_msg,{title:lan.files.recycle_bin_re_title,closeBtn:2,icon:3},function(){var i=layer.msg(lan.files.recycle_bin_re_the,{icon:16,time:0,shade:[.3,"#000"]});$.post("/files?action=Re_Recycle_bin","path="+encodeURIComponent(e),function(e){layer.close(i),layer.msg(e.msg,{icon:e.status?1:5}),$(t).parents("tr").remove()})})},DelRecycleBin:function(e,t){layer.confirm(lan.files.recycle_bin_del_msg,{title:lan.files.recycle_bin_del_title,closeBtn:2,icon:3},function(){var i=layer.msg(lan.files.recycle_bin_del_the,{icon:16,time:0,shade:[.3,"#000"]});$.post("/files?action=Del_Recycle_bin","path="+encodeURIComponent(e),function(e){layer.close(i),layer.msg(e.msg,{icon:e.status?1:5}),$(t).parents("tr").remove()})})},CloseRecycleBin:function(){var e=this;layer.confirm(lan.files.recycle_bin_close_msg,{title:lan.files.recycle_bin_close,closeBtn:2,icon:3},function(){var t=layer.msg("
        "+lan.files.recycle_bin_close_the+"
        ",{icon:16,time:0,shade:[.3,"#000"]});setTimeout(function(){getSpeed(".myspeed")},1e3),$.post("/files?action=Close_Recycle_bin","",function(i){layer.close(t),layer.msg(i.msg,{icon:i.status?1:5}),e.render_recycle_list()})})},open_property_view:function(e){var t=this;t.$http("get_file_attribute",{filename:e.path},function(i){layer.open({type:1,closeBtn:2,title:"[ "+e.filename+" ] - "+(e.is_dir?"Folder":"File")+" properties",area:["580px","500px"],shadeClose:!1,content:'
        General Detail History
        Type:
        '+(i.is_dir||i.is_link?i.st_type:t.ext_type_tips(i.st_type))+'
        Location:
        '+i.path+'
        Size:
        '+bt.format_size(i.st_size)+" ("+t.font_thousandth(i.st_size)+' byte)
        Permissions:
        '+i.mode+'
        Group:
        '+i.group+'
        User:
        '+i.user+'
        Visit time:
        '+bt.format_data(i.st_atime)+'
        Modified time:
        '+bt.format_data(i.st_mtime)+'
        Properties
        Value
        Modified time
        Size
        MD5
        OPT
        ',success:function(a,l){$(".bt-property-setting .tab-nav span").click(function(){var e=$(this).index();$(this).addClass("on").siblings().removeClass("on"),$(".property-box:eq("+e+")").addClass("active").siblings().removeClass("active")}),$(".history_box_view").on("click",".open_history_file",function(){var t=$(this).attr("data-time");openEditorView(0,e.path),setTimeout(function(){aceEditor.openHistoryEditorView({filename:e.path,history:t},function(){layer.close(l),$(".ace_conter_tips").show(),$(".ace_conter_tips .tips").html("Read-only file, the file is "+_item.path+", historic version [ "+bt.format_data(new Number(t))+' ]Click to restore')})},500)}),$(".history_box_view").on("click",".recovery_file_historys",function(){aceEditor.event_ecovery_file(this)});var s={filename:["Name",e.filename],type:["Type",i.is_dir||i.is_link?i.st_type:t.ext_type_tips(i.st_type)],path:"Location",st_size:["Size",bt.format_size(i.st_size)+" ("+t.font_thousandth(i.st_size)+" byte)"],st_atime:["Visit time",bt.format_data(i.st_atime)],st_mtime:["Modified time",bt.format_data(i.st_mtime)],st_ctime:["Metadata modification time",bt.format_data(i.st_ctime)],md5:"MD5",sha1:"sha1",user:"User",group:"Group",mode:"Permissions",st_uid:"UID",st_gid:"GID",st_nlink:"Num of inode links",st_ino:"inode node num",st_mode:"inode protection mode",st_dev:"inode resident device"},n="",o="";for(var r in s)if(Object.hasOwnProperty.call(s,r)){var c=s[r],d=$.isArray(c)?c[1]:i[r];n+='
        '+($.isArray(c)?c[0]:c)+'
        '+d+"
        "}for(let t=0;t
        '+bt.format_data(a.st_mtime)+'
        '+bt.format_size(a.st_size)+"
        "+a.md5+'
        view  |  restore
        '}""===o&&(o+='
        No historical version
        '),$(".details_list").html(n),$(".history_list ").html(o),t.fixed_table_thead(".details_box_view"),t.fixed_table_thead(".history_box_view ")}})})},fixed_table_thead:function(e){$(e).scroll(function(){var e=this.scrollTop;this.querySelector("thead").style.transform="translateY("+e+"px)"})},font_thousandth:function(e){var t=String(e).split(".");return t[0]=t[0].replace(new RegExp("(\\d)(?=(\\d{3})+$)","ig"),"$1,"),t.join(".")},open_images_preview:function(e){function t(e){ -var t=Math.abs(l.rotate/90),i=t%2==0?l.preview_width:l.preview_height,a=t%2==0?l.preview_height:l.preview_width,s=$("#preview_images"),n={};l.init_width=l.natural_width,l.init_height=l.natural_height,l.init_width>i&&(l.init_width=i,l.init_height=parseFloat((i/l.natural_width*l.init_height).toFixed(2))),l.init_height>a&&(l.init_width=parseFloat((a/l.natural_height*l.init_width).toFixed(2)),l.init_height=a),l.current_width=parseFloat(l.init_width*l.scale),l.current_height=parseFloat(l.init_height*l.scale),l.current_left=parseFloat(((l.preview_width-l.current_width)/2).toFixed(2)),l.current_top=parseFloat(((l.preview_height-l.current_height)/2).toFixed(2)),n={width:l.current_width,height:l.current_height,top:l.current_top,left:l.current_left,display:"inline",transform:"rotate("+l.rotate+"deg)",opacity:1,transition:"all 100ms"},!1===e&&delete n.transition,s.css(n)}var i=this,a=$('
        '+e.filename+'
        '),l={natural_width:0,natural_height:0,init_width:0,init_height:0,preview_width:0,preview_height:0,current_width:0,current_height:0,current_left:0,current_top:0,rotate:0,scale:1,images_mouse:!1};if($(".preview_images_mask").length>0)return $("#preview_images").attr("src","/download?filename="+e.path),!1;$("body").css("overflow","hidden").append(a),l.preview_width=a[0].clientWidth,l.preview_height=a[0].clientHeight,$(".preview_body img").load(function(){var i=$(this)[0];$(this).attr("data-index")||$(this).attr("data-index",e.images_id),l.natural_width=i.naturalWidth,l.natural_height=i.naturalHeight,t(!1)}),$(".preview_images_mask .preview_head").on("mousedown",function(e){e=e||window.event;var t=$(this).parent();if($("body").addClass("select"),$(this).onselectstart=$(this).ondrag=function(){return!1},!$(e.target).hasClass("preview_close")){var i=e.clientX-t.offset().left,a=e.clientY-t.offset().top;$(document).on("mousemove",function(e){e=e||window.event;var l=e.clientX-i,s=e.clientY-a;l<0?l=0:l>window.innerWidth-t.width()&&(l=window.innerWidth-t.width()),s<0?s=0:s>window.innerHeight-t.height()&&(s=window.innerHeight-t.height()),t.css({left:l,top:s,margin:0})}).on("mouseup",function(){$(this).unbind("mousemove mouseup")})}}),$(".preview_images_mask #preview_images").on("mousedown",function(e){e=e||window.event,$(this).onselectstart=$(this).ondrag=function(){return!1};var t=$(this),i=$(".preview_images_mask").offset(),a=e.clientX-i.left,s=e.clientY-i.top;$(".preview_images_mask").on("mousemove",function(e){e=e||window.event;var n,o,r=e.clientX-i.left-a,c=e.clientY-i.top-s,d=Math.abs(l.rotate/90),p=d%2==0?l.preview_width:l.preview_height,_=d%2==0?l.preview_height:l.preview_width;if(l.current_width>p){var f=p-l.current_width;n=l.current_left+r,n>0?n=0:n_){var h=_-l.current_height;o=l.current_top+c,o>0?o=0:o_&&l.current_top<=0&&l.current_height-_<=l.current_top&&(l.current_top-=c),t.css({left:l.current_left,top:l.current_top})}).on("mouseup",function(){$(this).unbind("mousemove mouseup")}).on("dragstart",function(){e.preventDefault()})}).on("dragstart",function(){return!1}),$(".preview_close").click(function(e){$(".preview_images_mask").remove()}),$(".preview_toolbar a").click(function(){var e=$(this).index();$("#preview_images");switch(e){case 0:case 1:l.rotate=e?l.rotate+90:l.rotate-90,t();break;case 2:case 3:if(3==l.scale&&2==e||.2==l.scale&&3==e)return layer.msg(l.scale>=1?"The image is the maximum size":"The image is the minimum size"),!1;l.scale=(2==e?Math.round(10*(l.scale+.4)):Math.round(10*(l.scale-.4)))/10,t();break;case 4:var i=l.rotate%360;i>=180?l.rotate+=360-i:l.rotate-=i,l.scale=1,t()}}),$(".preview_full,.preview_small").click(function(){$(this).hasClass("preview_full")?($(this).addClass("hidden").prev().removeClass("hidden"),l.preview_width=i.area[0],l.preview_height=i.area[1],a.css({width:i.area[0],height:i.area[1],top:0,left:0,margin:0}).data("type","full"),t()):($(this).addClass("hidden").next().removeClass("hidden"),$(".preview_images_mask").removeAttr("style"),l.preview_width=750,l.preview_height=650,t())}),$(".preview_cut_view a").click(function(){var e="",t=$("#preview_images"),a=parseInt(t.attr("data-index"));$(this).index()?(a=a==i.file_images_list.length-1?0:a+1,e=i.file_images_list[a]):(a=0===a?i.file_images_list.length-1:a-1,e=i.file_images_list[a]),t.attr("data-index",a).attr("src","/download?filename="+e),$(".preview_title").html(i.get_path_filename(e))})},open_video_play:function(e){var t=e.path,i="/download?filename="+e.path,a=e.path.split("/"),l=a.slice(0,a.length-1).join("/");layer.open({type:1,closeBtn:2,title:'Playing ['+a[a.length-1]+"]",area:["890px","402px"],shadeClose:!1,skin:"movie_pay",content:'
        ',success:function(){$.post("/files?action=get_videos",{path:l},function(e){for(var i='',a=0,s=0;s"}i+="
        File nameSize
        '+e[s].name+''+ToSize(e[s].size)+"
        ",$(".video-list").html(i).scrollTop(34*a)})}})},play_file:function(e,t){if($("#btvideo video").attr("data-filename")==t)return!1;var i="/download?filename="+t+"&play=true",a='';$("#btvideo").html(a);var l=t.split("/");$(".btvideo-title").html(l[l.length-1]),$(".video-avt").removeClass("video-avt"),$(e).parents("tr").addClass("video-avt")},copy_file_or_dir:function(e){bt.set_cookie("record_paste",e.path),bt.set_cookie("record_paste_type","copy"),$(".file_all_paste").removeClass("hide"),layer.msg("Copy successfully. Please click [Paste] or Ctrl + V to paste")},cut_file_or_dir:function(e){bt.set_cookie("record_paste",e.path),bt.set_cookie("record_paste_type","cut"),$(".file_all_paste").removeClass("hide"),layer.msg("Cut successfully. Please click [Paste] or Ctrl + V to paste")},paste_file_or_dir:function(){var e=this,t=bt.get_cookie("record_paste_type"),i=bt.get_cookie("record_paste"),a="";if("null"!=i&&null!=i&&(a=i.split("/").pop()),e.file_path.indexOf(i)>-1)return layer.msg("Can not paste ["+a+"] here, Because the item cannot be pasted into itself.",{icon:0}),!1;if("null"!=t&&null!=t)switch(t){case"cut":case"copy":this.check_exists_files_req({dfile:this.file_path,filename:a},function(t){if(t.length>0){for(var l="",s=0;s'+t[s].filename+""+ToSize(t[s].size)+""+getLocalTime(t[s].mtime)+"";var n='
        '+l+"
        File nameSizeLast edit time
        ";SafeMessage("This files will be overwritten",n,function(){e.config_paste_to(i,a)})}else e.config_paste_to(i,a)});break;case"1":case"2":e.batch_file_paste()}},config_paste_to:function(e,t){var i=this,a=bt.get_cookie("record_paste_type");this.$http("copy"==a?"CopyFile":"MvFile",{sfile:e,dfile:this.file_path+"/"+t},function(e){e.status&&(bt.set_cookie("record_paste",null),bt.set_cookie("record_paste_type",null),i.reader_file_list({path:i.file_path})),layer.msg(e.msg,{icon:e.status?1:2})})},rename_file_or_dir:function(e){var t=this;t.is_editor=!0,$(".file_list_content .file_tr:nth-child("+(e.index+1)+")").addClass("editr_tr").find(".file_title").empty().append($("icon"==bt.get_cookie("rank")?'":'')),"icon"==bt.get_cookie("rank")&&$("textarea[name=rename_file_input]").css({height:$("textarea[name=rename_file_input]")[0].scrollHeight}),$(("icon"==bt.get_cookie("rank")?"textarea":"input")+"[name=rename_file_input]").on("input",function(){if("icon"==bt.get_cookie("rank")&&(this.style.height="auto",this.style.height=this.scrollHeight+"px"),"file"==e.type){var t=$(this).val().split("."),i=t[t.length-1];$(this).parent().prev().find(".file_icon").removeAttr("class").addClass("file_icon file_"+i)}}).keyup(function(e){13==e.keyCode&&$(this).blur(),e.stopPropagation(),e.preventDefault()}).blur(function(){var i=$(this).val().replace(/[\r\n]/g,""),a={sfile:e.path,dfile:t.path_resolve(t.file_path,i)};return e.filename==i||""==i?($(".file_list_content .file_tr:nth-child("+(e.index+1)+")").removeClass("editr_tr").find(".file_title").empty().append($(""+e.filename+"")),t.is_editor=!1,!1):t.match_unqualified_string(i)?layer.msg('The name cannot have /\\:*?"<>| symbol',{icon:2}):(t.rename_file_req(a,function(e){t.reader_file_list({path:t.file_path},function(){layer.msg(e.msg,{icon:e.status?1:2})})}),void(t.is_editor=!1))}).focus()},set_file_share:function(e){var t=this;this.loadY=bt.open({type:1,shift:5,closeBtn:2,area:"450px",title:"Set share "+e.type_tips+"-["+e.filename+"]",btn:["Create","Cancel"],content:'
        Share name
        Expiration date
        Extraction code
        ',yes:function(i,a){var l=$("[name=ps]").val(),s=$("[name=expire]:checked").val(),n=$("[name=password]").val();if(""===l)return layer.msg("No sharing name!",{icon:2}),!1;t.create_download_url({filename:e.path,ps:l,password:n,expire:s},function(i){if(!i.status)return layer.msg(i.msg,{icon:i.status?1:2}),!1;var a=i.msg;t.file_list[e.index]=$.extend(t.file_list[e.index],{down_id:a.id,down_info:a}),t.loadY.close(),t.info_file_share(e),t.reader_file_list_content(t.file_list)})},success:function(e,t){$("#random_paw").click(function(){$(this).prev().val(bt.get_random(6))})}})},info_file_share:function(e){var t=this;if(void 0===e.down_info)return this.get_download_url_find({id:e.down_id},function(i){t.file_list[e.index]=$.extend(t.file_list[e.index],{down_info:i}),t.file_share_view(t.file_list[e.index],"fonticon")}),!1;this.file_share_view(e,"fonticon")},file_share_view:function(e,t){var i=e;"fonticon"==t&&(i=e.down_info);var a=this,l=location.origin+"/down/"+i.token;this.loadY=bt.open({type:1,shift:5,closeBtn:2,area:"550px",title:"Share details-["+i.filename+"]",content:'
        Share name
        Expiration date
        '+(i.expire>new Date("2099-01-01 00:00:00").getTime()/1e3?'Permanent':bt.format_data(i.expire))+'
        ',success:function(s,n){var o=new ClipboardJS(".copy_url"),r=new ClipboardJS(".copy_paw");o.on("success",function(e){layer.msg("Copy link succeeded!",{icon:1}),e.clearSelection()}),r.on("success",function(e){layer.msg("Copy link and extraction code succeeded!",{icon:1}),e.clearSelection()}),$(".layer_close").click(function(){layer.close(n)}),$(".QR_code").click(function(){layer.closeAll("tips"),layer.tips('
        ',".QR_code",{area:["150px","150px"],tips:[1,"#ececec"],time:0,shade:[.05,"#000"],shadeClose:!0,success:function(){jQuery("#QR_code").qrcode({render:"canvas",text:l,height:130,width:130})}})}),$(".close_down").click(function(){a.remove_download_url({id:i.id,fileName:i.filename},function(i){a.loadY.close(),"fonticon"==t&&(a.file_list[e.index].down_id=0,a.reader_file_list_content(a.file_list)),"list"==t&&a.render_share_list(),layer.msg(i.msg,{icon:i.status?1:2})})})}})},del_file_or_dir:function(e){var t=this;t.is_recycle?bt.confirm({title:"Delete "+e.type_tips+"[ "+e.filename+" ]",msg:"Comfirm delete "+e.type_tips+"[ "+e.path+" ],it will move to recycle bin after delete, continue?"},function(){t.del_file_req(e,function(e){t.reader_file_list({path:t.file_path}),layer.msg(e.msg,{icon:e.status?1:2})})}):bt.show_confirm("Delete "+e.type_tips+"[ "+e.filename+" ]",'Recycle bin is not currently open, delete '+("dir"==e.type?"directory":"file")+" cannot be restored after, continue?
        ",function(){t.del_file_req(e,function(e){t.reader_file_list({path:t.file_path}),layer.msg(e.msg,{icon:e.status?1:2})})})},cancel_file_favorites:function(e){var t=this,i=e.index;this.loadY=bt.confirm({title:e.filename+lan.files.unfavorite1,msg:lan.files.unfavorite1+" ["+e.path+"] "+lan.files.continue},function(){t.$http("del_files_store",{path:e.path},function(e){e.status&&(t.file_list[i].caret=!1,t.reader_file_list_content(t.file_list),t.load_favorites_index_list()),layer.msg(e.msg,{icon:e.status?1:2})})})},set_soft_link:function(e){var t=this;bt_tools.open({title:"Create Softlink",area:"520px",content:{class:"pd20",formLabelWidth:"110px",form:[{label:"Source file",group:{type:"text",name:"sfile",width:"280px",placeholder:"Please select the folder and file to be linked",icon:{type:"glyphicon-folder-open",event:function(e){},select:"all"},value:"",input:function(e){}}},{label:"Softlink name",group:{type:"text",name:"name",width:"280px",placeholder:"Please enter the name of the softlink",value:""}}]},init:function(){var e=null,t=setInterval(function(){if($('input[name="sfile"]').length<1&&clearInterval(t),e!=$('input[name="sfile"]').val()){e=$('input[name="sfile"]').val();var i=e.split("/");i.length>1&&$('[name="name"]').val(i[i.length-1])}},100)},yes:function(e,i,a){e=$.extend(e,{dfile:t.file_path+"/"+e.name}),delete e.name,bt_tools.send("files/CreateLink",e,function(e){e.status&&(layer.close(i),bt.msg(e),t.reader_file_list())},{tips:"Create Softlink"})}})},set_file_authority:function(e,t){var i=this;i.get_file_authority({path:e.path},function(a){var l='
        ';i.loadY=layer.open({type:1,closeBtn:2,title:lan.files.set_auth+"["+e.filename+"]",area:"465px",shadeClose:!1,content:'
        Set permission
        Backups list
        '+l+"
        "+lan.files.file_own+'

        '+lan.files.file_read+'

        '+lan.files.file_write+'

        '+lan.files.file_exec+"

        "+lan.files.file_group+'

        '+lan.files.file_read+'

        '+lan.files.file_write+'

        '+lan.files.file_exec+"

        "+lan.files.file_public+'

        '+lan.files.file_read+'

        '+lan.files.file_write+'

        '+lan.files.file_exec+'

        '+lan.files.file_menu_auth+", "+lan.files.file_own+'
        ",success:function(a,l){i.edit_access_authority(),$("#access").keyup(function(){i.edit_access_authority()}),$("input[type=checkbox]").change(function(){for(var e=["owner","group","public"],t="",i=0;i

        Please enter the current backup name

        Remarks
        ',yes:function(l,s){$(".layer_close").click(function(){layer.close(s)}),a.$http("back_path_permissions",{back_sub_dir:i,path:e,remark:$("input.form-control").val()},function(i){if(layer.close(l),!i.status)return layer.msg(i.msg,{time:1900,icon:2}),!1;if(0==t){var s=a.backup_list();$(".buplist").html(s)}else if(3==t){var n=$("#access").val(),o=$("#chown").val(),r=$("#accept_all").prop("checked")?"True":"False",c="filename="+encodeURIComponent(e)+"&user="+o+"&access="+n+"&all="+r;Oksend(c),layer.closeAll()}layer.msg(i.msg,{time:1900,icon:1})})},btn2:function(){layer.close(l)},cancel:function(){layer.close(l)}})},backup_list:function(){var e="",t=this;t.$http("get_all_back",function(t){for(var i=0;i '+o+' "+t[i][3]+' '+t[i][1]+' Del '}$(".allback .buplist").html(e)})},manage_backup:function(){var e=this,t=layer.open({type:1,closeBtn:2,title:"Manage Backups",area:["630px","500px"],shadeClose:!1,content:'
        Backup time Backup path Name Delect
        ',cancel:function(){layer.close(t)},success:function(){e.backup_list(),$("#btn-backup").click(function(t){var i=$("#server_path").val();e.backup_files_permission(i,0)}),$(".allback").on("click",".del_back",function(){var t=$(this).parents("tr").attr("data-id");e.del_backup(t)})}})},del_backup:function(e){var t=this;layer.confirm("The backup cannot be restored after deletion.
        Continue to delete?",{title:"Confirm delete?",btn:["Yes","No"],closeBtn:2},function(i,a){t.$http("del_path_premissions",{id:e},function(i){var a=$(".layui-layer-title:eq(0)").text();"Manage Backups"!==a?(a=$(".backup_list").attr("data-path"),t.backup_files_list(a)):$(".allback tbody tr[data-id="+e+"]").remove(),layer.msg(i.msg,{icon:i.status?1:2})})})},backup_files_list:function(e){var t=this;t.$http("get_path_premissions",{path:e},function(i){var a="",l="";if(0==i.length)a='No data';else for(var s=0;s '+i[s][4]+" "+i[s][2]+" "+i[s][1]+" "+c+' Restore | Del '} -l='
        Fix all permissions to [ Folder: 755, File: 644 ]
        '+a+"
        Name permission Owner Backup Time Opt
        ",$(".chmodset").hide(),$(".backup_lists").html(l),$(".fixper").click(function(){layer.confirm("Note: Under the file or folder all permissions will be fixed to [ Folder: 755, File: 644 ]",{title:"Fix Permissions?",btn:["Confirm","Cancel"],closeBtn:2},function(i,a){t.$http("fix_permissions",{path:e},function(e){layer.closeAll(),t.reader_file_list({path:t.file_path,is_operating:!1}),layer.msg(e.msg,{icon:e.status?1:2})})})}),$(".restore_backup").click(function(){t.restore_file_permission($(this).attr("data-time"),e)}),$(".backup_list").on("click",".del_back",function(){var e=$(this).attr("data-id");t.del_backup(e)})})},restore_file_permission:function(e,t){var i=this,a=$("#accept_all").prop("checked")?1:0,l=layer.open({type:1,closeBtn:2,title:"Confirm restore",area:"330px",shadeClose:!1,btn:["Yes","No"],content:'
        Restore would overwrite the current settings, continue?
        ',yes:function(l,s){i.$http("restore_path_permissions",{restore_sub_dir:a,date:e,path:t},function(e){layer.closeAll(),layer.msg(e.msg,{icon:1,time:1900})})},btn2:function(){layer.close(l)},cancel:function(){layer.close(l)}})},get_present_task_view:function(){this.file_present_task=layer.open({type:1,title:"Real-time task queue",area:"500px",closeBtn:2,skin:"present_task_list",shadeClose:!1,shade:!1,offset:"auto",content:'
        '})},render_present_task_list:function(){var e=this;this.get_task_req({status:-3},function(t){if(0==t.length)return layer.close(e.file_present_task),e.file_present_task=null,void e.reader_file_list({path:e.file_path,is_operating:!1});var i="",a=!1;$.each(t,function(t,l){-1==l.status?(e.file_present_task||e.get_present_task_view(),"1"==l.type?i+='
        • '+lan.layout.download+l.shell+''+l.log.pre+'%'+lan.public.cancel+'
          '+l.log.used+"/"+ToSize(l.log.total)+''+(0==l.log.speed?lan.layout.connect:l.log.speed)+'/s'+lan.files.expected_to_be+": "+l.log.time+"
        ":i+='
        '+l.name+": "+l.shell+''+lan.public.cancel+'
        '+l.log+"
        "):(a||(i+='
        '+lan.layout.wait_task+'
          ',a=!0),i+='
        • '+l.name+": "+l.shell+'X
        • ')}),e.file_present_task&&(a&&(i+="
        "),$(".message-list").html(i)),setTimeout(function(){e.render_present_task_list()},1e3)})},remove_present_task:function(e){var t=this;layer.confirm("Do you want to cancel the upload of files? It need to delete the uploaded files manually. Continue?",{title:"Cancel file upload",icon:0},function(i){bt.send("remove_task","task/remove_task",{id:e},function(e){layer.msg(e.msg,{icon:1}),layer.close(t.file_present_task),t.file_present_task=null}),layer.close(i)})},edit_access_authority:function(){for(var e=$("#access").val(),t=["owner","group","public"],i=0;it.length))switch(l>7&&$("#access").val(e.substr(0,e.length-1)),l){case"1":$("#"+t[a]+"_x").prop("checked",!0);break;case"2":$("#"+t[a]+"_w").prop("checked",!0);break;case"3":$("#"+t[a]+"_x").prop("checked",!0),$("#"+t[a]+"_w").prop("checked",!0);break;case"4":$("#"+t[a]+"_r").prop("checked",!0);break;case"5":$("#"+t[a]+"_r").prop("checked",!0),$("#"+t[a]+"_x").prop("checked",!0);break;case"6":$("#"+t[a]+"_r").prop("checked",!0),$("#"+t[a]+"_w").prop("checked",!0);break;case"7":$("#"+t[a]+"_r").prop("checked",!0),$("#"+t[a]+"_w").prop("checked",!0),$("#"+t[a]+"_x").prop("checked",!0)}}},get_file_authority:function(e,t){this.$http("GetFileAccess",{filename:e.path},function(e){t&&t(e)})},set_dir_kill:function(e){var t=this;"php"==e.ext?t.$http("file_webshell_check",{filename:e.path},function(e){layer.msg(e.msg,{icon:e.status?1:2})}):layer.confirm("目录查杀将包含子目录中的php文件,是否操作?",{title:"目录查杀["+e.filename+"]",closeBtn:2,icon:3},function(i){t.$http("dir_webshell_check",{path:e.path},function(e){layer.msg(e.msg,{icon:e.status?1:2})})})},path_resolve:function(e,t){var i="";return Array.isArray(t)||(t=[t]),e.replace(/([\/|\/]*)$/,function(e){return e,"www"}),$.each(t,function(e,t){i+="/"+t}),(e+i).replace("//","/")},get_ext_name:function(e){for(var t=e.split("."),i=["folder","folder-unempty","sql","c","cpp","cs","flv","css","js","htm","html","java","log","mht","php","url","xml","ai","bmp","cdr","gif","ico","jpeg","jpg","JPG","png","psd","webp","ape","avi","mkv","mov","mp3","mp4","mpeg","mpg","rm","rmvb","swf","wav","webm","wma","wmv","rtf","docx","fdf","potm","pptx","txt","xlsb","xlsx","7z","cab","iso","rar","zip","gz","bt","file","apk","bookfolder","folder-empty","fromchromefolder","documentfolder","fromphonefolder","mix","musicfolder","picturefolder","videofolder","sefolder","access","mdb","accdb","fla","doc","docm","dotx","dotm","dot","pdf","ppt","pptm","pot","xls","csv","xlsm"],a=t[t.length-1],l=0;l')},yes:function(){var e=a.getVal();if(""==e.dfile)return layer.msg("Please select a valid address",{icon:2});a.submitForm(function(e,t){setTimeout(function(){i.reader_file_list({path:t.path})},1e3),null!=e&&null!=e||layer.msg(lan.files.zip_ok,{icon:1}),e.status&&i.render_present_task_list(),layer.close(s)})}})})},unpack_file_to_path:function(e){var t=this,i="zip",a="";a=e.path.substring(0,e.path.lastIndexOf("/")),this.reader_form_line({url:"UnZip",overall:{width:"310px"},data:[{label:"File name",name:"z_name",placeholder:"Compress file name",value:e.path},{label:"Compress path",name:"z_path",placeholder:"Compress path",value:a},{label:"Encoding",name:"z_code",type:"select",value:"UTF-8",list:[["UTF-8","UTF-8"],["gb18030","GBK"]]}],beforeSend:function(e){return{sfile:e.z_name,dfile:e.z_path,type:i,coding:e.z_code,password:e.z_password}}},function(a,l){var s=layer.open({type:1,title:"Decompress file",area:"520px",shadeClose:!1,closeBtn:2,skin:"unpack_file_view",btn:["Comfirm","Cancel"],content:l[0].outerHTML,success:function(){"gz"==e.ext&&(i="tar"),"zip"==i&&$(".unpack_file_view .line:nth-child(2)").append('
        Password
        ')},yes:function(){var e=a.getVal();return""==e.z_name?layer.msg("Please enter the file name path",{icon:2}):""==e.z_path?layer.msg("Please enter the decompression address",{icon:2}):void a.submitForm(function(e,i){layer.close(s),setTimeout(function(){t.reader_file_list({path:i.path})},1e3),e.status&&t.render_present_task_list(),layer.msg(e.msg,{icon:e.status?1:2})})}})})},match_unqualified_string:function(e){var t=RegExp(/[(\ )(\*)(\|)(\\)(\:)(\")(\/)(\<)(\>)(\?)(\)]+/);return t.test(e)},reader_form_line:function(e,t){var i=this,a=bt.get_random(10),l=$('
        '),s=e,n=[];i=this;Array.isArray(e)||(s=e.data),$.each(s,function(t,i){var a=i.labelWidth||e.overall.labelWidth||null,s=bt.get_random(10),o=i.labelWidth||e.overall.width||null,r=$('
        "+(i.label||"")+'
        '),c=$(function(){switch(i.type){case"select":return"";case"text":default:return"'}}());(i.eventType||i.event)&&(Array.isArray(i.eventType)||(i.eventType=[i.eventType]),$.each(i.eventType,function(t,a){if(n.push({el:s,type:a||"click",event:i[a]||null}),e.el){var l=$('[data-event="'+i.el+'"]');if(i[a])"enter"==a?l.on("keyup",function(e){13==e.keyCode&&i.event(e)}):l.on(i||"click",i.event);else if("focus"==a){var o=l.val();""!=o&&l.val("").focus().val(o)}else l[a]()}})),r.find(".info-r").append(c),l.append(r)}),e.el&&$(e.el).empty().append(l),t&&t({getVal:function(){return $("#"+a).serializeObject()},setEvent:function(){$.each(n,function(e,t){var i=$('[data-event="'+t.el+'"]');if(null===t.event)if("focus"==t.type){var a=i.val();""!=a&&i.val("").focus().val(a)}else i[t.type]();else"enter"==t.type?i.on("keyup",function(e){13==e.keyCode&&t.event(e)}):i.on(t.type,t.event)})},submitForm:function(t){var a=this.getVal();e.beforeSend&&(a=e.beforeSend(a)),i.loadT=bt.load("submitting the form, please wait..."),bt.send(e.url,"files/"+e.url,a,function(e){i.loadT.close(),t&&t(e,a)})}},l)},$http:function(e,t,i){var a=this,l="";"string"==typeof e?("object"!=typeof t&&(i=t,t={}),Array.isArray(a.method_list[e])||(a.method_list[e]=["files",a.method_list[e]]),a.$http({method:e,tips:!!a.method_list[e][1]&&a.method_list[e][1],module:a.method_list[e][0],data:t,msg:!0},i)):(void 0!==e.tips&&e.tips&&(l=bt.load(e.tips)),bt.send(e.method,(e.module||"files")+"/"+e.method,e.data||{},function(e){if(""!=l&&l.close(),"string"==typeof e&&(e=JSON.parse(e)),!1===e.status&&e.msg)return bt.msg(e),!1;t&&t(e)}))}};bt_file.init(),Function.prototype.delay=function(e,t,i){return Array.isArray(t)||(i=t,t=[]),void 0===i&&(i=0),setTimeout(this.apply(e,t),i),this},jQuery.prototype.serializeObject=function(){var e,t,i,a,l;for(e=this.serializeArray(),t={},i=t.hasOwnProperty,a=0;a-1,init:function(){0==$("#mask_layer").length&&(window.UploadFiles=function(){bt_file.file_drop.dialog_view()},$("body").append($('")),this.event_relation(document.querySelector("#container"),document,document.querySelector("#mask_layer")))},event_relation:function(enter,leave,drop){var that=this,obj=Object.keys(arguments);for(var item in arguments)"object"==typeof arguments[item]&&void 0!==arguments[item].nodeType&&(arguments[item]={el:arguments[item],callback:null});leave.el.addEventListener("dragleave",null!=leave.callback?leave.callback:function(e){0==e.x&&0==e.y&&$("#mask_layer").hide(),e.preventDefault()},!1),enter.el.addEventListener("dragenter",null!=enter.callback?enter.callback:function(e){if("string"==e.dataTransfer.items[0].kind)return!1;$("#mask_layer").show(),that.isLayuiDrop=!1,e.preventDefault()},!1),drop.el.addEventListener("dragover",(function(e){e.preventDefault()}),!1),drop.el.addEventListener("drop",null!=enter.callback?drop.callback:that.ev_drop,!1)},ev_drop:function(e){if("string"==e.dataTransfer.items[0].kind)return!1;if(!bt_file.file_drop.is_webkit)return $("#mask_layer").hide(),!1;if(e.preventDefault(),bt_file.file_drop.uploading)return layer.msg("Uploading files, please wait..."),!1;var items=e.dataTransfer.items,time,num=0;if(loadT=layer.msg("Getting upload files details, please wait...",{icon:16,time:0,shade:.3}),bt_file.file_drop.isUpload=!0,items&&items.length&&null!=items[0].webkitGetAsEntry&&"file"!=items[0].kind)return!1;null==bt_file.file_drop.filesList&&(bt_file.file_drop.filesList=[]);for(var i=bt_file.file_drop.filesList.length-1;i>=0;i--)bt_file.file_drop.filesList[i].is_upload&&bt_file.file_drop.filesList.splice(-i,1);function update_sync(s){s.getFilesAndDirectories().then((function(subFilesAndDirs){return iterateFilesAndDirs(subFilesAndDirs,s.path)}))}$("#mask_layer").hide();var iterateFilesAndDirs=function(filesAndDirs,path){if(!bt_file.file_drop.isUpload)return!1;for(var i=0;ibt_file.file_drop.isUploadNumber)return bt_file.file_drop.isUpload=!1,layer.msg(" "+bt_file.file_drop.isUploadNumber+" items cannot upload, please compress first!。",{icon:2,area:"405px"}),bt_file.file_drop.filesList=[],clearTimeout(time),!1;bt_file.file_drop.filesList.push({file:filesAndDirs[i],path:bt.get_file_path(path+"/"+filesAndDirs[i].name).replace("//","/"),name:filesAndDirs[i].name.replace("//","/"),icon:bt_file.get_ext_name(filesAndDirs[i].name),size:bt_file.file_drop.to_size(filesAndDirs[i].size),upload:0,is_upload:!1}),bt_file.file_drop.uploadAllSize+=filesAndDirs[i].size,clearTimeout(time),time=setTimeout((function(){layer.close(loadT),bt_file.file_drop.dialog_view()}),100),num++}};"getFilesAndDirectories"in e.dataTransfer&&e.dataTransfer.getFilesAndDirectories().then((function(filesAndDirs){return iterateFilesAndDirs(filesAndDirs,"/")}))},dialog_view:function(config){var that=this,html="";if(this.f_path=bt_file.file_path,!$(".file_dir_uploads").length>0){null==that.filesList&&(that.filesList=[]);for(var i=0;i'+(item.path+"/"+item.name).replace("//","/")+''+item.size+''+that.is_upload_status(item.upload)+'
        '}var is_show=that.filesList.length>11;layer.open({type:1,closeBtn:1,maxmin:!0,area:["550px","505px"],btn:["Upload","Cancel","Clear"],title:"Upload files to【"+bt.get_cookie("Path")+"】--- Support breakpoint renewal",skin:"file_dir_uploads",content:'
        '+(""!=html?'
        • File nameFile sizeFile status
          '+html+"
        ":"Please drag the file here"+(that.is_webkit?"":'The current browser does not support drag upload. Commend to use Chrome browser or WebKit kernel for browsing')+"")+"
        ",success:function(layers){$("#mask_layer").hide(),layers.find(".layui-layer-btn2").css("margin","0 300px 0 0"),$(".file_dir_uploads .layui-layer-max").hide(),$(".upload_btn_groud .upload_file_btn").click((function(){$(".upload_btn_groud .dropdown-menu [data-type=file]").click()})),$(".upload_btn_groud .dropdown-menu a").click((function(){var type=$(this).attr("data-type");$('").change((function(e){for(var files=e.target.files,arry=[],i=0;iPlease drag the file here"),$('.file_upload_info').css('display','none').siblings().css('display','block'),that.filesList.length=0})),!1):($(".upload_file_body").addClass("active").html("Please drag the file here"),$('.file_upload_info').css('display','none').siblings().css('display','block'),that.filesList.length=0,!1)},end:function(){that.clear_drop_stauts(!0)},min:function(){$(".file_dir_uploads .layui-layer-max").show(),$("#layui-layer-shade"+$(".file_dir_uploads").attr("times")).fadeOut()},restore:function(){$(".file_dir_uploads .layui-layer-max").hide(),$("#layui-layer-shade"+$(".file_dir_uploads").attr("times")).fadeIn()}})}else{if(null==config&&!that.isLayuiDrop)return!1;if(that.isLayuiDrop&&(config=that.filesList),$(".upload_file_body").html('
        • File nameFile sizeFile status
          ').removeClass("active"),Array.isArray(config)){for(var i=0;i'+(item.path+"/"+item.name).replace("//","/")+''+item.size+''+that.is_upload_status(item.upload)+'
          '}$(".dropUpLoadFile").append(html)}else $(".dropUpLoadFile").append('
        • '+(config.path+"/"+config.name).replace("//","/")+''+config.size+''+that.is_upload_status(config.upload)+'
        • ')}},is_upload_status:function(status,val){switch(void 0===val&&(val=""),status){case-1:return'Fail'+(""!=val?","+val:"")+"";case 0:return'Waiting to upload';case 1:return'Uploaded';case 2:return'Uploading '+val+"";case 3:return'Stoped'}},set_upload_view:function(index,config){var item=$(".dropUpLoadFile li:eq("+index+")"),that=this,file_info=$(".file_upload_info");0==$(".file_upload_info .uploadProgress").length&&$(".file_upload_info").html('Total process ,Uploading ,Fail Speed Getting,Expect time Getting'),file_info.show().prev().hide().parent().css("paddingRight",0),this.errorLength>0&&file_info.find(".uploadError").text("("+this.errorLength+"份)").parent().show(),file_info.find(".uploadNumber").html("("+this.uploadLength+"/"+this.filesList.length+")"),file_info.find(".uploadProgress").html((this.uploadedSize/this.uploadAllSize*100).toFixed(2)+"%"),1===config.upload||-1===config.upload?(this.filesList[index].is_upload=!0,this.uploadLength+=1,item.find(".fileLoading").css({width:"100%",opacity:".5",background:-1==config.upload?"#ffadad":"#20a53a21"}),item.find(".filesize").text(config.size),item.find(".fileStatus").html(this.is_upload_status(config.upload,1===config.upload?"(Time:"+this.diff_time(this.startTime,this.endTime)+")":config.errorMsg)),item.find(".fileLoading").fadeOut(500,(function(){$(this).remove();var uploadHeight=$(".dropUpLoadFile");if(0==uploadHeight.length)return!1;uploadHeight[0].scrollHeight>uploadHeight.height()&&uploadHeight.scrollTop(uploadHeight.scrollTop()+40)}))):(item.find(".fileLoading").css("width",config.percent),item.find(".filesize").text(config.upload_size+"/"+config.size),item.find(".fileStatus").html(this.is_upload_status(config.upload,"("+config.percent+")")))},clear_drop_stauts:function(status){var time=new Date,that=this;if(!status)try{var s_peed=bt_file.file_drop.to_size(bt_file.file_drop.uploadedSize/((time.getTime()-bt_file.file_drop.initTimer.getTime())/1e3));$(".file_upload_info").html(""+this.uploadLength+" uploaded,"+(this.errorLength>0?this.errorLength+"failures, ":"")+"time"+this.diff_time(this.initTimer,time)+",speed "+s_peed+"/s").append($('').click((function(){$(".file_upload_info").hide().prev().show()})))}catch(e){}$(".layui-layer-btn0").removeAttr("style data-upload").text(lan.upload.upload),$.extend(bt_file.file_drop,{startTime:0,endTime:0,uploadLength:0,splitSize:2097152,filesList:[],errorLength:0,isUpload:!1,isUploadNumber:800,uploadAllSize:0,uploadedSize:0,topUploadedSize:0,uploadExpectTime:0,initTimer:0,speedInterval:null,timerSpeed:0,uploading:!1}),clearInterval(this.speedInterval)},upload_file:function(fileStart,index){if(null==fileStart&&0==this.uploadSuspend.length&&(fileStart=0,index=0),this.filesList.length===index)return clearInterval(this.speedInterval),this.clear_drop_stauts(),bt_file.reader_file_list({path:bt_file.file_path,is_operating:!1}),!1;var that=this;that.splitEndTime=(new Date).getTime(),that.get_timer_speed(),that.splitStartTime=(new Date).getTime();var item=this.filesList[index],fileEnd="";if(null==item)return!1;fileEnd=Math.min(item.file.size,fileStart+this.splitSize),that.fileSize=fileEnd-fileStart,form=new FormData,0==fileStart&&(that.startTime=new Date,item=$.extend(item,{percent:"0%",upload:2,upload_size:"0B"})),form.append("f_path",this.f_path+item.path),form.append("f_name",item.name),form.append("f_size",item.file.size),form.append("f_start",fileStart),form.append("blob",item.file.slice(fileStart,fileEnd)),that.set_upload_view(index,item),$.ajax({url:"/files?action=upload",type:"POST",data:form,async:!0,processData:!1,contentType:!1,success:function(data){"number"==typeof data?(that.set_upload_view(index,$.extend(item,{percent:(data/item.file.size*100).toFixed(2)+"%",upload:2,upload_size:that.to_size(data)})),that.uploadedSize+=fileEnd!=data?data:parseInt(fileEnd-fileStart),that.upload_file(data,index)):data.status?(that.endTime=new Date,that.uploadedSize+=parseInt(fileEnd-fileStart),that.set_upload_view(index,$.extend(item,{upload:1,upload_size:item.size})),that.upload_file(0,index+=1)):(that.set_upload_view(index,$.extend(item,{upload:-1,errorMsg:data.msg})),that.errorLength++)},error:function(e){if(void 0===that.filesList[index].req_error&&(that.filesList[index].req_error=1),that.filesList[index].req_error>2)return that.set_upload_view(index,$.extend(that.filesList[index],{upload:-1,errorMsg:"error"==e.statusText?lan.public.network_err:e.statusText})),that.errorLength++,that.upload_file(fileStart,index+=1),!1;that.filesList[index].req_error+=1,that.upload_file(fileStart,index)}})},get_timer_speed:function(speed){var done_time=(new Date).getTime();if(done_time-this.speedLastTime>1e3){var that=this,num=0;null==speed&&(speed=200);var s_time=(this.splitEndTime-this.splitStartTime)/1e3;if(this.timerSpeed=(this.fileSize/s_time).toFixed(2),this.updateedSizeLast=this.uploadedSize,this.timerSpeed<2)return;$(".file_upload_info .uploadSpeed").text(this.to_size(isNaN(this.timerSpeed)?0:this.timerSpeed)+"/s");var estimateTime=this.time(parseInt((this.uploadAllSize-this.uploadedSize)/this.timerSpeed*1e3));isNaN(this.timerSpeed)||$(".file_upload_info .uploadEstimate").text(-1==estimateTime.indexOf("NaN")?estimateTime:"0 "+lan.bt.s),this.speedLastTime=done_time}},time:function(date){var hours=Math.floor(date/36e5),minutes=Math.floor(date/6e4),seconds=parseInt(date%6e4/1e3),result=seconds+"sec";return minutes>0&&(result=minutes+"min"+seconds+"sec"),hours>0&&(result=hours+"hour"+Math.floor((date-36e5*hours)/6e4)+"min"),result},diff_time:function(start_date,end_date){var diff=end_date.getTime()-start_date.getTime(),minutes=Math.floor(diff/6e4),leave3,seconds=diff%6e4/1e3,result=seconds.toFixed(minutes>0?0:2)+lan.bt.s;return minutes>0&&(result=minutes+"min"+seconds.toFixed(0)+lan.bt.s),result},to_size:function(a){for(var d=[" B"," KB"," MB"," GB"," TB"," PB"],e=1024,b=0;b1)return that.file_groud_event({open:"soft_link"}),!1;var type=$(this).data("type"),nav_down_list=$(".create_file_or_dir .nav_down_list");if(nav_down_list.css({display:function(){return setTimeout((function(){nav_down_list.removeAttr("style")}),100),"none"}}),that.is_editor)return!1;that.is_editor=!0,$(".file_list_content").prepend('
          '+("icon"==bt.get_cookie("rank")?'":'')+"
          "),$(("icon"==bt.get_cookie("rank")?"textarea":"input")+"[name=createArea]").on("input",(function(){"icon"==bt.get_cookie("rank")&&(this.style.height="auto",this.style.height=this.scrollHeight+"px")})).keyup((function(e){13==e.keyCode&&$(this).blur()})).blur((function(e){var _val=$(this).val().replace(/[\r\n]/g,"");if(that.match_unqualified_string(_val))return layer.msg('Name cannot contain /\\:*?"<>| symbol',{icon:2});""==_val&&(_val="newBlankDir"==type?"New directory":"New blank file"),setTimeout((function(){that.create_file_req({type:"newBlankDir"==type?"folder":"file",path:that.file_path+"/"+_val},(function(res){res.status&&that.reader_file_list({path:that.file_path}),layer.msg(res.msg,{icon:res.status?1:2})})),$(".createModel").remove(),that.is_editor=!1}),300),e.preventDefault()})).focus(),e.stopPropagation(),e.preventDefault()})),$(".file_nav_view .favorites_file_path ul").on("click","li",(function(e){var _href=$(this).data("path"),_type=$(this).data("type"),nav_down_list=$(".favorites_file_path .nav_down_list");if("dir"==_type)that.reader_file_list({path:_href,is_operating:!0});else{if(null!=$(this).data("null"))return!1;var _file=$(this).attr("title").split("."),_fileT=_file[_file.length-1],_fileE;switch(that.determine_file_type(_fileT)){case"text":openEditorView(0,_href);break;case"video":that.open_video_play(_href);break;case"images":that.open_images_preview({filename:$(this).attr("title"),path:_href});break;default:that.reader_file_list({path:that.retrun_prev_path(_href),is_operating:!0})}}nav_down_list.css({display:function(){return setTimeout((function(){nav_down_list.removeAttr("style")}),100),"none"}}),e.stopPropagation(),e.preventDefault()})),$(".terminal_view").on("click",(function(){web_shell()})),$(".share_file_list").on("click",(function(){that.open_share_view()})),$(".mount_disk_list").on("click",".nav_btn",(function(){var path=$(this).data("menu");that.reader_file_list({path:path,is_operating:!0})})),$(".mount_disk_list").on("click",".nav_down_list li",(function(){var path=$(this).data("disk"),disk_list=$(".mount_disk_list.thezoom .nav_down_list");disk_list.css({display:function(){return setTimeout((function(){disk_list.removeAttr("style")}),100),"none"}}),that.reader_file_list({path:path,is_operating:!0})})),$(".file_nav_view").on("click",".manage_backup",(function(ev){that.manage_backup(),ev.stopPropagation(),ev.preventDefault()})),$(".file_nav_view").on("click",".recycle_bin",(function(ev){that.recycle_bin_view(),ev.stopPropagation(),ev.preventDefault()})),$(".file_nav_view .multi").on("click",".nav_btn_group",(function(ev){var batch_type=$(this).data("type");void 0!==batch_type&&that.batch_file_manage(batch_type),ev.stopPropagation(),ev.preventDefault()})),$(".file_nav_view .multi").on("click",".nav_btn_group li",(function(ev){var batch_type=$(this).data("type");that.batch_file_manage(batch_type),ev.stopPropagation(),ev.preventDefault()})),$(".file_nav_view").on("click",".file_all_paste",(function(){that.paste_file_or_dir()})),$(".file_list_header").on("click",".file_name,.file_size,.file_mtime,.file_accept,.file_user",(function(e){var _tid=$(this).attr("data-tid"),_reverse=$(this).find(".icon_sort").hasClass("active"),_active=$(this).hasClass("active");return!$(this).find(".icon_sort").hasClass("active")&&$(this).hasClass("active")?$(this).find(".icon_sort").addClass("active"):$(this).find(".icon_sort").removeClass("active"),$(this).addClass("active").siblings().removeClass("active").find(".icon_sort").removeClass("active").empty(),$(this).find(".icon_sort").html(''),_active||(_reverse=!0),bt.set_cookie("files_sort",_tid),bt.set_cookie("name_reverse",_reverse?"True":"False"),that.reader_file_list({reverse:_reverse?"True":"False",sort:_tid}),!1})),$(".file_list_header .file_th").each((function(index,item){var files_sort=bt.get_cookie("files_sort"),name_reverse=bt.get_cookie("name_reverse");$(this).attr("data-tid")===files_sort&&($(this).addClass("active").siblings().removeClass("active").find(".icon_sort").removeClass("active").empty(),$(this).find(".icon_sort").html(''),"False"===name_reverse&&$(this).find(".icon_sort").addClass("active"))})),$(".file_list_header .file_check").on("click",(function(e){var checkbox;switch(parseInt($(this).data("checkbox"))){case 0:$(this).addClass("active").removeClass("active_2").data("checkbox",1),$(".file_list_content .file_tr").addClass("active").removeClass("active_2"),$(".nav_group.multi").removeClass("hide"),$(".file_menu_tips").addClass("hide"),that.file_table_arry=that.file_list.slice();break;case 2:$(this).addClass("active").removeClass("active_2").data("checkbox",1),$(".file_list_content .file_tr").addClass("active"),$(".nav_group.multi").removeClass("hide"),$(".file_menu_tips").addClass("hide"),that.file_table_arry=that.file_list.slice();break;case 1:$(this).removeClass("active active_2").data("checkbox",0),$(".file_list_content .file_tr").removeClass("active"),$(".nav_group.multi").addClass("hide"),$(".file_menu_tips").removeClass("hide"),that.file_table_arry=[]}that.calculate_table_active()})),$(".file_list_content").on("click",".file_checkbox",(function(e){var _tr=$(this).parents(".file_tr"),index=_tr.data("index"),filename=_tr.data("filename");_tr.hasClass("active")?(_tr.removeClass("active"),that.remove_check_file(that.file_table_arry,"filename",filename)):(_tr.addClass("active"),_tr.attr("data-filename",that.file_list[index].filename),that.file_table_arry.push(that.file_list[index])),that.calculate_table_active(),e.stopPropagation()})),$(".file_list_content").scroll((function(e){$(this).scrollTop()==$(this)[0].scrollHeight-$(this)[0].clientHeight?($(this).prev().css("opacity",1),$(this).next().css("opacity",0)):$(this).scrollTop()>0?$(this).prev().css("opacity",1):0==$(this).scrollTop()&&($(this).prev().css("opacity",0),$(this).next().css("opacity",1))})),$(".file_table_view .file_list_content").on("click",".file_tr",(function(e){if($(e.target).hasClass("foo_menu_title")||$(e.target).parents().hasClass("foo_menu_title"))return!0;$(this).addClass("active").siblings().removeClass("active"),that.file_table_arry=[that.file_list[$(this).data("index")]],that.calculate_table_active(),e.stopPropagation(),e.preventDefault()})),$(".file_table_view .file_list_content").on("click",".file_name .iconfont",(function(e){var file_tr,index=$(this).parents(".file_tr").data("index"),data=that.file_list[index];data.index=index,$(this).hasClass("icon-share1")&&that.info_file_share(data),$(this).hasClass("icon-favorites")&&that.cancel_file_favorites(data),e.stopPropagation()})),$(".file_table_view .file_list_content").on("dblclick",".file_tr",(function(e){var index=$(this).data("index"),data=that.file_list[index];if($(e.target).hasClass("file_check")||$(e.target).parents(".foo_menu").length>0||$(e.target).hasClass("set_file_ps")||that.is_editor)return!1;if("dir"==data.type){if("Recycle_bin"==data.filename)return that.recycle_bin_view();that.reader_file_list({path:that.file_path+"/"+data.filename,is_operating:!0})}else switch(data.open_type){case"text":openEditorView(0,data.path);break;case"video":that.open_video_play(data);break;case"images":that.open_images_preview(data);break;case"compress":that.unpack_file_to_path(data)}e.stopPropagation(),e.preventDefault()})),$(".file_table_view .file_list_content").on("click",".file_title i,.file_ico_type .file_icon",(function(e){var file_tr,index=$(this).parents(".file_tr").data("index"),data=that.file_list[index];if("dir"==data.type){if("Recycle_bin"==data.filename)return that.recycle_bin_view();that.reader_file_list({path:that.file_path+"/"+data.filename,is_operating:!0})}else layer.msg("compress"==data.open_type?"Double click to unzip the file":"Double click to edit the file");e.stopPropagation(),e.preventDefault()})),$(".file_list_content").on("contextmenu",(function(ev){return"createArea"==$(ev.target).attr("name")||"rename_file_input"==$(ev.target).attr("name")})),$(".selection_right_menu").on("contextmenu",(function(ev){return!1})),$(".file_list_content").on("mousedown",".file_tr",(function(ev){if(1===ev.which&&($(ev.target).hasClass("foo_menu_title")||$(ev.target).parents().hasClass("foo_menu_title")))that.render_file_groud_menu(ev,this),$(ev.target).parent().addClass("foo_menu_click"),$(this).siblings().find(".foo_menu").removeClass("foo_menu_click"),$(this).addClass("active").siblings().removeClass("active");else{if(3!==ev.which||that.is_editor)return!0;that.file_table_arry.length>1?that.render_files_multi_menu(ev):(that.render_file_groud_menu(ev,this),$(".content_right_menu").removeAttr("style"),$(this).addClass("active").siblings().removeClass("active"))}ev.stopPropagation(),ev.preventDefault()})),$(".filePage").on("change",".showRow",(function(){var val=$(this).val();bt.set_cookie("showRow",val),that.reader_file_list({showRow:val,p:1,is_operating:!1})})),$(".filePage").on("click","div:nth-child(2) a",(function(e){var num=$(this).attr("href").match(/p=([0-9]+)$/)[1];that.reader_file_list({path:that.path,p:num}),e.stopPropagation(),e.preventDefault()})),$(".file_list_content").on("click",".folder_size",(function(e){var data=that.file_list[$(this).parents(".file_tr").data("index")],_this=this;that.get_file_size({path:data.path},(function(res){$(_this).text(bt.format_size(res.size))})),e.stopPropagation(),e.preventDefault()})),$(".filePage").on("click","#file_all_size",(function(e){if("/"===that.file_path)return layer.tips('The current directory is document root (/),calculate size will occupymassive server IO,continue?',this,{tips:[1,"red"],time:5e3}),!1;that.get_dir_size({path:that.file_path})})),$(".file_list_content").on("mousedown",(function(ev){if($(ev.target).hasClass("file_checkbox")||$(ev.target).hasClass("file_check")||$(ev.target).hasClass("icon-share1")||$(ev.target).hasClass("icon-favorites")||"i"==ev.target.localName||$(ev.target).parents(".app_menu_group").length>0||$(ev.target).hasClass("createModel")||$(ev.target).hasClass("editr_tr")||"createArea"==$(ev.target).attr("name")||"rename_file_input"==$(ev.target).attr("name")||$(ev.target).hasClass("set_file_ps")||that.is_editor)return!0;if(3==ev.which&&!that.is_editor)return $(".selection_right_menu").removeAttr("style"),that.render_file_all_menu(ev,this),!0;$(".file_list_content").bind("mousewheel",(function(){return!1}));var container=$(this),scroll_h=0,con_t=container.offset().top,con_l=container.offset().left,startPos={top:ev.clientY-$(this).offset().top,left:ev.clientX-$(this).offset().left};$(document).unbind("mousemove").mousemove((function(ev){var endPos={top:ev.clientY-con_t>0&&ev.clientY-con_t1?container.height():0,left:ev.clientX-con_l>0&&ev.clientX-con_l1?container.width():0},fixedPoint={top:endPos.top>startPos.top?startPos.top:endPos.top,left:endPos.left>startPos.left?startPos.left:endPos.left};"list"==bt.get_cookie("rank")&&(fixedPoint.top=fixedPoint.top+40);var w=Math.min(Math.abs(endPos.left-startPos.left),con_l+container.width()-fixedPoint.left),h=Math.min(Math.abs(endPos.top-startPos.top),con_t+container.height()-fixedPoint.top);if(ev.clientY-con_t<0){var beyond_t=Math.abs(ev.clientY-con_t);container.scrollTop(container.scrollTop()-beyond_t),0!=container.scrollTop()&&(scroll_h+=beyond_t),h+=scroll_h}if(ev.clientY-(con_t+container.height())>1){var beyond_b=ev.clientY-(con_t+container.height());container.scrollTop(container.scrollTop()+beyond_b),container[0].scrollHeight-container[0].scrollTop!==container[0].clientHeight&&(scroll_h+=beyond_b),h+=scroll_h,fixedPoint.top=fixedPoint.top-scroll_h}if(startPos.top==endPos.top||startPos.left==endPos.left)return!0;that.enter_files_box().show().css({left:fixedPoint.left+"px",top:fixedPoint.top+"px",width:w+"px",height:h+"px"});var box_offset_top=that.enter_files_box().offset().top,box_offset_left=that.enter_files_box().offset().left,box_offset_w=that.enter_files_box().offset().left+that.enter_files_box().width(),box_offset_h=that.enter_files_box().offset().top+that.enter_files_box().height();$(container).find(".file_tr").each((function(i,item){var offset_top=$(item).offset().top,offset_left=$(item).offset().left,offset_h=$(item).offset().top+$(item).height(),offset_w=$(item).offset().left+$(item).width();"icon"==bt.get_cookie("rank")?offset_w>=box_offset_left&&offset_left<=box_offset_w&&offset_h>=box_offset_top&&offset_top<=box_offset_h?$(item).addClass("active"):$(item).removeClass("active"):offset_w>=box_offset_left&&offset_h>=box_offset_top&&offset_top<=box_offset_h?$(item).addClass("active"):$(item).removeClass("active")}))})),$(document).on("mouseup",(function(){var _move_array=[],box_offset_top=that.enter_files_box().offset().top,box_offset_left=that.enter_files_box().offset().left,box_offset_w=that.enter_files_box().offset().left+that.enter_files_box().width(),box_offset_h=that.enter_files_box().offset().top+that.enter_files_box().height();$(container).find(".file_tr").each((function(i,item){var offset_top=$(item).offset().top,offset_left=$(item).offset().left,offset_h=$(item).offset().top+$(item).height(),offset_w=$(item).offset().left+$(item).width();"icon"==bt.get_cookie("rank")?offset_w>=box_offset_left&&offset_left<=box_offset_w&&offset_h>=box_offset_top&&offset_top<=box_offset_h&&_move_array.push($(item).data("index")):offset_w>=box_offset_left&&offset_h>=box_offset_top&&offset_top<=box_offset_h&&_move_array.push($(item).data("index"))})),that.render_file_selected(_move_array),that.enter_files_box().remove(),$(".file_list_content").unbind("mousewheel")})),ev.stopPropagation(),ev.preventDefault()})),$(".file_list_content").on("blur",".set_file_ps",(function(ev){var tr_index=$(this).parents(".file_tr").data("index"),item=that.file_list[tr_index],nval=$(this).val(),oval=$(this).data("value"),_this=this;if(nval==oval)return!1;bt_tools.send("files/set_file_ps",{filename:item.path,ps_type:0,ps_body:nval},(function(rdata){$(_this).data("value",nval)}),{tips:"Set ps",tips:!0})})),$(".file_list_content").on("keyup",".set_file_ps",(function(ev){13==ev.keyCode&&$(this).blur(),ev.stopPropagation()})),$(".file_list_header").on("mousedown",".file_width_resize",(function(ev){return!1;var th,Minus_v,_header,maxlen})),$(".cut_view_model").on("click",(function(){var type=$(this).data("type");$(".file_table_view").addClass("icon"==type?"icon_view":"list_view").removeClass("icon"!=type?"icon_view":"list_view").scrollLeft(0),bt.set_cookie("rank",type),$(this).addClass("active").siblings().removeClass("active")})),$(".file_list_content").on("click",".set_operation_group a",(function(ev){var data=$(this).parents(".file_tr").data(),type=$(this).data("type"),item=that.file_list[data.index];if("more"==type)return!0;item.open=type,item.index=data.index,item.type_tips="file"==item.type?"File":"Directory",that.file_groud_event(item)}))},enter_files_box:function(){return 0==$("#web_mouseDrag").length&&$("
          ",{id:"web_mouseDrag",style:["position:absolute; top:0; left:0;","border:1px solid #072246; background-color: #cce8ff;","filter:Alpha(Opacity=15); opacity:0.15;","overflow:hidden;display:none;z-index:9;"].join("")}).appendTo(".file_table_view"),$("#web_mouseDrag")},clear_table_active:function(){this.file_table_arry=[],$(".file_list_header .file_check").removeClass("active active_2"),$(".file_list_content .file_tr").removeClass("active app_menu_operation"),$(".file_list_content .file_tr .file_ps .foo_menu").removeClass("foo_menu_click"),$(".app_menu_group").remove()},calculate_table_active:function(){var that=this,header_check=$(".file_list_header .file_check");0==this.file_table_arry.length?header_check.removeClass("active active_2").data("checkbox",0):this.file_table_arry.length==this.file_list.length?header_check.addClass("active").removeClass("active_2").data("checkbox",1):header_check.addClass("active_2").removeClass("active").data("checkbox",2),this.file_table_arry.length>0?($(document).unbind("keydown").on("keydown",(function(e){var keyCode=e.keyCode,tagName=e.target.localName.toLowerCase(),is_mac=window.navigator.userAgent.indexOf("Mac")>-1;if("input"==tagName||"textarea"==tagName)return!0;e.ctrlKey&&67==keyCode&&(1==that.file_table_arry.length?(that.file_groud_event($.extend(that.file_table_arry[0],{open:"copy"})),$(".file_all_paste").removeClass("hide")):that.file_table_arry.length>1&&that.batch_file_manage("copy")),e.ctrlKey&&88==keyCode&&(1==that.file_table_arry.length?(that.file_groud_event($.extend(that.file_table_arry[0],{open:"shear"})),$(".file_all_paste").removeClass("hide")):that.file_table_arry.length>1&&that.batch_file_manage("shear"))})),this.file_table_arry.length>1?($(".nav_group.multi").removeClass("hide"),$(".file_menu_tips").addClass("hide")):($(".nav_group.multi").addClass("hide"),$(".file_menu_tips").removeClass("hide"))):($(".nav_group.multi").addClass("hide"),$(".file_menu_tips.multi").removeClass("hide"),$(document).unbind("keydown")),$(".selection_right_menu,.file_path_input .file_dir_item .nav_down_list").removeAttr("style"),that.set_menu_line_view_resize()},set_dir_view_resize:function(){var file_path_input=$(".file_path_input"),file_dir_view=$(".file_path_input .file_dir_view"),_path_width=file_dir_view.attr("data-width"),file_item_hide=null;if(_path_width?parseInt(_path_width):(_path_width=file_dir_view.width(),file_dir_view.attr("data-width",_path_width)),file_dir_view.width()-_path_width<90){var width=0;$($(".file_path_input .file_dir_view .file_dir_item").toArray().reverse()).each((function(){var item_width=0;$(this).attr("data-width")?item_width=parseInt($(this).attr("data-width")):($(this).attr("data-width",$(this).width()),item_width=$(this).width()),width+=item_width,file_path_input.width()-width<=90?$(this).addClass("hide"):$(this).removeClass("hide")}))}var file_item_hide=file_dir_view.children(".file_dir_item.hide").clone(!0);0==file_dir_view.children(".file_dir_item.hide").length?file_path_input.removeClass("active").find(".file_dir_omit").addClass("hide"):(file_item_hide.each((function(){0==$(this).find(".glyphicon-hdd").length&&$(this).find(".file_dir").before('')})),file_path_input.addClass("active").find(".file_dir_omit").removeClass("hide"),file_path_input.find(".file_dir_omit .nav_down_list").empty().append(file_item_hide),file_path_input.find(".file_dir_omit .nav_down_list .file_dir_item").removeClass("hide"))},set_menu_line_view_resize:function(){var menu_width=$(".file_nav_view").width(),disk_list_width=0,batch_list_width=0,_width=0,disk_list=$(".mount_disk_list"),batch_list=$(".nav_group.multi");disk_list.attr("data-width")||disk_list.attr("data-width",disk_list.innerWidth()),batch_list.attr("data-width")||0==batch_list.innerWidth()||-1==batch_list.innerWidth()||batch_list.attr("data-width",batch_list.innerWidth()),disk_list_width=parseInt(disk_list.attr("data-width")),batch_list_width=parseInt(batch_list.attr("data-width")),$(".file_nav_view>.nav_group").not(".mount_disk_list").each((function(){_width+=$(this).innerWidth()})),menu_width-(_width+=$(".menu-header-foot").innerWidth()).nav_btn_group").each((function(index){index>=$(".batch_group_list>.nav_btn_group").length-(indexs+2)?$(this).hide():$(this).show()})),$(".batch_group_list>.nav_btn_group:last-child").removeClass("hide").show()):($(".batch_group_list>.nav_btn_group").css("display","inline-block"),$(".batch_group_list>.nav_btn_group:last-child").addClass("hide"))},set_file_forward:function(){var that=this,forward_path=$(".forward_path span");1==this.file_operating.length?forward_path.addClass("active"):this.file_pointer==this.file_operating.length-1?(forward_path.eq(0).removeClass("active"),forward_path.eq(1).addClass("active")):0==this.file_pointer?(forward_path.eq(0).addClass("active"),forward_path.eq(1).removeClass("active")):forward_path.removeClass("active")},set_file_view:function(){var file_list_content=$(".file_list_content"),height=this.area[1]-$(".file_table_view")[0].offsetTop-170;$(".file_bodys").height(this.area[1]-100),50*this.file_list.length>height?(file_list_content.attr("data-height",file_list_content.data("height")||file_list_content.height()).css({overflow:"hidden","overflow-y":"auto",height:height+"px"}),$(".file_shadow_bottom").css("opacity",1)):(file_list_content.css({overflow:"hidden","overflow-y":"auto",height:height+"px"}),$(".file_shadow_top,.file_shadow_bottom").css("opacity",0))},open_share_view:function(){var that=this;layer.open({type:1,shift:5,closeBtn:2,area:["850px","580px"],title:"Share list",content:'
          Share nameShare addressExpiration dateOpt
          ',success:function(){that.render_share_list(),$(".download_url_list").on("click",".info_down",(function(){var indexs=$(this).attr("data-index");that.file_share_view(that.file_share_list[indexs],"list")})),$(".download_table .download_url_page").on("click","a",(function(e){var _href=$(this).attr("href").match(/p=([0-9]+)$/)[1];that.render_share_list({p:_href}),e.stopPropagation(),e.preventDefault()}))}})},render_share_list:function(param){var that=this,_list="";void 0===param&&(param={p:1}),bt_tools.send("files/get_download_url_list",param,(function(res){that.file_share_list=res.data,res.data.length>0?$.each(res.data,(function(index,item){_list+=''+item.ps+''+item.filename+""+bt.format_data(item.expire)+'Details | Close'})):_list='No share data',$(".download_url_list").html(_list),$(".download_url_page").html(res.page),$(".download_table").on("click",".del_down",(function(){var id=$(this).attr("data-id"),_ps=$(this).attr("data-ps");that.remove_download_url({id:id,fileName:_ps},(function(res){res.status&&that.render_share_list(param),layer.msg(res.msg,{icon:res.status?1:2})}))}))}),"Share list")},remove_check_file:function(arry,key,value){for(var len=arry.length;len--;)arry[len][key]==value&&arry.splice(len,1)},open_download_view:function(){var that=this;that.reader_form_line({url:"DownloadFile",beforeSend:function(data){return{url:data.url,path:data.path,filename:data.filename}},overall:{width:"310px"},data:[{label:"URL address:",name:"url",placeholder:"URL address",value:"http://",eventType:["input","focus"],input:function(){var value,url_list=$(this).val().split("/");$('[name="filename"]').val(url_list[url_list.length-1])}},{label:"Download to:",name:"path",placeholder:"Download to",value:that.file_path},{label:"File name:",name:"filename",placeholder:"Save file name",value:"",eventType:"enter",enter:function(){$(".download_file_view .layui-layer-btn0").click()}}]},(function(form,html){var loadT=bt.open({type:1,title:"Download file",area:"500px",shadeClose:!1,skin:"download_file_view",content:html[0].outerHTML,btn:["Comfirm","Close"],success:function(){form.setEvent()},yes:function(indexo,layero){var ress=form.getVal();if(!bt.check_url(ress.url))return layer.msg("Please enter valid URL address..",{icon:2}),!1;form.submitForm((function(res){that.render_present_task_list(),layer.msg(res.msg,{icon:res.status?1:2}),loadT.close()}))}})}))},set_style_width:function(type,width){var _content=bt.get_cookie("formHeader")||$("#file_list_info").html(),_html="",_reg=new RegExp("\\.file_"+type+"\\s?\\{width\\s?\\:\\s?(\\w+)\\s\\!important;\\}","g"),_defined_config={name:150,type:80,size:80,mtime:150,accept:80,user:80,ps:150};_html=_content.replace(_reg,(function(match,$1,$2,$3){return".file_"+type+"{width:"+(width<80?_defined_config[type]+"px":width+"px")+" !important;}"})),$("#file_list_info").html(_html)},set_file_table_width:function(){var that=this,file_header_width=$(".file_table_view")[0].offsetWidth,auto_num=0,width=0,auto_all_width=0,css="",_width=0,tr_heigth=45,other="",config={};$.each(this.file_header,(function(key,item){"auto"==item?(auto_num++,config[key]=0):(width+=item,css+="."+key+"{width:"+("file_operation"!=key?item:item-16)+"px !important;}")})),this.is_mobile&&$(".file_operation.file_th").attr("style","margin-right:-10px !important;"),45*this.file_list.length>$(".file_list_content").height()?(config.file_tr=file_header_width-(this.is_mobile?0:this.scroll_width),file_header_width=file_header_width,other+=".file_td.file_operation{width:"+(this.file_header.file_operation-(this.is_mobile?0:this.scroll_width)-10)+"px !important;}",other+=".file_th.file_operation{padding-right:"+(10+(this.is_mobile?0:this.scroll_width))+"px !important}"):(file_header_width=file_header_width,config.file_tr=file_header_width,this.is_mobile&&(other+=".file_td.file_operation{width:"+(this.file_header.file_operation-20)+"px !important;}")),config.file_list_header=file_header_width,_width=(auto_all_width=file_header_width-width)/auto_num,$.each(config,(function(key,item){css+="."+key+"{width:"+(0==item?_width:item)+"px !important;}"})),$("#file_list_info").html(css+other)},render_path_list:function(callback){var that=this,html='
          ',path_before="",dir_list=this.file_path.split("/").splice(1),first_dir=this.file_path.split("/")[0];"Windows"===bt.os?(0==dir_list.length&&(dir_list=[]),dir_list.unshift('Local disk ('+first_dir+")")):("/"==this.file_path&&(dir_list=[]),dir_list.unshift("Root dir"));for(var i=0;i '+dir_list[i]+' ';$(".path_input").val("").attr("data-path",this.file_path);var file_dir_view=$(".file_path_input .file_dir_view");file_dir_view.html(html),file_dir_view.attr("data-width",file_dir_view.width()),this.set_dir_view_resize.delay(this,100)},render_path_down_list:function(el,path,callback){var that=this,_html="",next_path=$(el).parent().next().find(".file_dir").attr("title");this.get_dir_list({path:path},(function(res){$.each(that.data_reconstruction(res.DIR),(function(index,item){var _path=("/"!=path?path:"")+"/"+item.filename;_html+='
        • '+item.filename+"
        • "})),$(el).html(_html)}))},reader_file_list:function(data,callback){var that=this,select_page_num="",next_path="",model=bt.get_cookie("rank"),isPaste=bt.get_cookie("record_paste_type");"null"!=isPaste&&null!=isPaste?$(".file_nav_view .file_all_paste").removeClass("hide"):$(".file_nav_view .file_all_paste").addClass("hide"),$(".file_table_view").removeClass(".list_view,.icon_view").addClass("list"==model?"list_view":"icon_view"),$(".cut_view_model:nth-child("+("list"==model?"2":"1")+")").addClass("active").siblings().removeClass("active"),this.file_images_list=[],this.get_dir_list(data,(function(res){if(!1===res.status&&res.msg.indexOf("The specified directory does not exist!")>-1)return that.reader_file_list({path:"/www"});that.file_path=that.path_check(res.PATH),that.file_list=$.merge(that.data_reconstruction(res.DIR,"DIR"),that.data_reconstruction(res.FILES)),that.is_recycle=res.FILE_RECYCLE,that.file_store_list=res.STORE,bt.set_cookie("Path",that.path_check(res.PATH)),that.reader_file_list_content(that.file_list,(function(rdata){$(".path_input").attr("data-path",that.file_path),$(".file_nav_view .multi").addClass("hide"),$(".selection_right_menu").removeAttr("style"),$.each(["100","200","500","1000","2000"],(function(index,item){select_page_num+='"}));var page=$(res.PAGE);page.append('per pageitem(s)"),$(".filePage").html('
          Total '+rdata.is_dir_num+" directory, "+(that.file_list.length-rdata.is_dir_num)+'file(s), size:Click to calculate
          '+page[0].outerHTML),data.is_operating&&that.file_operating[that.file_pointer]!=res.PATH&&(void 0!==(next_path=that.file_operating[that.file_pointer+1])&&next_path!=res.PATH&&that.file_operating.splice(that.file_pointer+1),that.file_operating.push(res.PATH),that.file_pointer=that.file_operating.length-1),that.render_path_list(),that.set_file_forward(),that.render_favorites_list(),that.set_file_view(),that.set_file_table_width(),callback&&callback(res)}))}))},data_reconstruction:function(data,type,callback){var that=this,arry=[],info_ps=[["/etc","PS: System files directory"],["/home","PS: Home directory"],["/tmp","PS: Common temporary files directory"],["/root","PS: Main directory of system admin"],["/usr","PS: System application directory"],["/boot","PS: System run directory"],["/lib","PS: System source file directory"],["/mnt","PS: Store temporary mapped file system"],["/www","PS: Aapanel program directory"],["/bin","PS: Store binary executable file directory"],["/dev","PS: Storage device file directory"],["/www/wwwlogs","PS: Default site logs directory"],["/www/server","PS: Aapanel soft installed directory"],["/www/wwwlogs","PS: Site logs directory"],["/www/Recycle_bin",lan.files.recycle_bin_dir],["/www/server/panel","PS: Aapanel main program directory, do not move"],["/www/server/panel/plugin","PS: Aapanel plugin directory"],["/www/server/panel/BTPanel","PS: Aapanel directory"],["/www/server/panel/BTPanel/static","PS: Aapanel static directory"],["/www/server/panel/BTPanel/templates","PS: Aapanel templates directory"],[bt.get_cookie("backup_path"),"PS: Default backup directory"],[bt.get_cookie("sites_path"),"PS: Default site directory"]];return data.length<1?[]:($.each(data,(function(index,item){var itemD=item.split(";"),fileMsg="",fileN=itemD[0].split("."),extName=fileN[fileN.length-1];switch(itemD[0]){case".user.ini":fileMsg=lan.files.php_profile;break;case".htaccess":fileMsg=lan.files.apache_profile;break;case"swap":fileMsg=lan.files.swap_file}-1!=itemD[0].indexOf("Recycle_bin")&&(fileMsg=lan.files.swap_file),-1!=itemD[0].indexOf(".upload.tmp")&&(fileMsg=lan.files.recycle_bin_dir);for(var i=0;i0?($.each(this.file_store_list,(function(index,item){html+='
        • '+item.name+"
        • "})),html+='
        • Management
        • '):html='
        • (Empty)
        • ',$(".favorites_file_path .nav_down_list").html(html)},set_favorites_manage:function(){var that=this;layer.open({type:1,title:"Manage Favorites",area:["850px","580px"],closeBtn:2,shift:5,shadeClose:!1,content:"
          PathOpt
          ",success:function(layers){that.render_favorites_type_list(),setTimeout((function(){$(layers).css("top",($(window).height()-$(layers).height())/2)}),50)},cancel:function(){that.reader_file_list({path:that.file_path})}})},render_favorites_type_list:function(){var _detail="";this.$http("get_files_store",(function(rdata){rdata.length>0?$.each(rdata,(function(ind,item){_detail+=''+item.path+'Del"})):_detail='No favorites',$(".favorites_body").html(_detail),jQuery.prototype.fixedThead?$(".stroe_tab_list .divtable").fixedThead({resize:!1}):$(".stroe_tab_list .divtable").css({overflow:"auto"})}))},load_favorites_index_list:function(){var that=this;this.$http("get_files_store",(function(rdata){that.file_store_list=rdata,that.render_favorites_list()}))},del_favorites:function(path){var that=this;layer.confirm("Comfirm delete path【"+path+"】?",{title:"Delete favorites",closeBtn:2,icon:3},(function(index){that.$http("del_files_store",{path:path},(function(res){res.status&&that.render_favorites_type_list(),layer.msg(res.msg,{icon:res.status?1:2})}))}))},reader_file_list_content:function(data,callback){var _html="",that=this,is_dir_num=0,images_num=0;$.each(data,(function(index,item){var _title=item.filename,only_id=bt.get_random(10),path=(that.file_path+"/"+item.filename).replace("//","/"),is_compress=that.determine_file_type(item.ext,"compress"),is_editor_tips=function(){var _openTitle="open";switch(that.determine_file_type(item.ext)){case"images":_openTitle="Preview";break;case"video":_openTitle="Play";break;default:_openTitle="compress"==that.determine_file_type(item.ext)?"":"Edit"}return"dir"==item.type&&(_openTitle="Open"),_openTitle}(item);that.file_list[index].only_id=only_id,_html+='
          "+item.filename+item.soft_link+""+(item.caret?'':"")+(0!=item.down_id?'':"")+'
          '+("dir"==item.type?"directory":that.ext_type_tips(item.ext))+'
          '+item.user+" / "+item.root_level+'
          '+("dir"==item.type?'Calculate':bt.format_size(item.size))+'
          '+bt.format_data(item.mtime)+'
          '+(item.is_os_ps?item.ps:'')+'
          ',"dir"==item.type&&is_dir_num++,item.path=path,item.open_type=that.determine_file_type(item.ext),"images"==item.open_type&&(item.images_id=images_num,that.file_images_list.push(item.path),images_num++)})),$(".file_list_content").html(_html),callback&&callback({is_dir_num:is_dir_num}),that.clear_table_active()},render_file_disk_list:function(){var that=this,html="",_li="";that.get_disk_list((function(res){$.each(res,(function(index,item){html+='",_li+='
        • '+("/"==item.path?"Root dir":item.path)+" ("+item.size[2]+")
        • "})),$(".mount_disk_list").html('
          '+lan.files.mounted_disk+'
          '+html+"
          "),that.set_menu_line_view_resize()}))},render_file_groud_menu:function(ev,el){var that=this,index=$(el).data("index"),_openTitle="Open",data=this.file_list[index],compression=["zip","rar","gz","war","tgz","bz2"],offsetNum=0,config={open:_openTitle,split_0:!0,download:"Download",share:"Share file",cancel_share:"Cancel share",favorites:"Favorites file",cancel_favorites:"Cancel favorites",split_1:!0,authority:"Permission",split_2:!0,copy:"Copy",shear:"Cut",rename:"Rename",del:"Delete",split_3:!0,compress:"Compress",unzip:"Unzip",open_find_dir:"Open file location",split_4:!0,property:"Properties"};switch(this.determine_file_type(data.ext)){case"images":_openTitle="Preview";break;case"video":_openTitle="Play";break;default:_openTitle="Edit"}config.open="dir"==data.type?"Open":_openTitle,"dir"===data.type&&delete config.download,"compress"==data.open_type&&delete config.open,0!=data.down_id?delete config.share:(delete config.cancel_share,config.share="dir"==data.type?"Share dir":"Share file"),!1!==data.caret?delete config.favorites:(delete config.cancel_favorites,config.favorites="dir"==data.type?"Favorites dir":"Favorites file"),"php"==data.ext&&(config.dir_kill="文件查杀"),"php"!=data.ext&&"dir"!=data.type&&delete config.dir_kill;var num=0;$.each(compression,(function(index,item){item==data.ext&&num++})),0==num&&delete config.unzip,data.is_search?config.open_find_dir="dir"==data.type?"Open dir":"Open file location":delete config.open_find_dir,this.file_selection_operating=config,this.reader_menu_list({el:$(".selection_right_menu"),ev:ev,data:data,list:config})},render_file_all_menu:function(ev,el){var that=this,config={refresh:"Refresh",split_0:!0,upload:"Upload",create:["New file/folder",{create_dir:"New folder",create_files:"New file",soft_link:"Softlink"}],web_shell:"Terminal",split_1:!0,paste:"Paste"},offsetNum=0,isPaste=bt.get_cookie("record_paste_type");"null"!=isPaste&&null!=isPaste||(delete config.split_1,delete config.paste),this.reader_menu_list({el:$(".selection_right_menu"),ev:ev,data:{},list:config})},render_files_multi_menu:function(ev){var that=this,config_group=[["copy","Copy"],["shear","cut"],["authority","Permission"],["compress","Compress"],["del","Delete"]],el=$(".selection_right_menu").find("ul"),el_height=el.height(),el_width=el.width(),left=ev.clientX-(this.area[0]-ev.clientX'):el.append($('
        • '+mitem[1]+"
        • ").append(null).on("click",{type:mitem[0],data:that.file_table_arry},(function(ev){$(".selection_right_menu").removeAttr("style"),that.batch_file_manage(ev.data.type),ev.stopPropagation(),ev.preventDefault()})))})),$(".selection_right_menu").css({left:left,top:ev.clientY-(this.area[1]-ev.clientY'):(Array.isArray(item)&&($children=$('
            '),$children_list=$children.find(".set_group"),$.each(item[1],(function(keys,items){$children_list.append($('
          • '+items+"
          • ").on("click",{type:keys,data:config.data},(function(ev){that.file_groud_event($.extend(ev.data.data,{open:ev.data.type,index:parseInt($(config.ev.currentTarget).data("index")),element:config.ev.currentTarget,type_tips:"dir"==config.data.type?"folder":"file"})),config.el.removeAttr("style"),ev.stopPropagation(),ev.preventDefault()})))}))),el.append($('
          • '+(Array.isArray(item)?item[0]:item)+"
          • ").append($children).on("click",{type:key,data:config.data},(function(ev){that.file_groud_event($.extend(ev.data.data,{open:ev.data.type,index:parseInt($(config.ev.currentTarget).data("index")),element:config.ev.currentTarget,type_tips:"dir"==config.data.type?"folder":"file"})),"compress"!=key&&"create"!=key&&config.el.removeAttr("style"),ev.stopPropagation(),ev.preventDefault()}))))})),el_height=el.innerHeight(),top=config.ev.clientY-(this.area[1]-config.ev.clientY'+lan.files.recycle_bin_warning+"",(function(){that.$http("SetBatchData",obj,(function(res){res.status&&that.reader_file_list({path:that.file_path}),layer.msg(res.msg,{icon:res.status?1:2})}))}))},batch_file_paste:function(){var that=this,_pCookie=bt.get_cookie("record_paste_type");this.check_exists_files_req({dfile:this.file_path},(function(result){if(result.length>0){for(var tbody="",i=0;i'+result[i].filename+""+ToSize(result[i].size)+""+getLocalTime(result[i].mtime)+"";var mbody;SafeMessage("The following files will be overwritten",'
            '+tbody+"
            File nameSizeLast edit time
            ",(function(){that.$http("BatchPaste",{type:_pCookie,path:that.file_path},(function(rdata){rdata.status&&(bt.set_cookie("record_paste_type",null),that.reader_file_list({path:that.file_path})),layer.msg(rdata.msg,{icon:rdata.status?1:2})}))}))}else that.$http("BatchPaste",{type:_pCookie,path:that.file_path},(function(rdata){rdata.status&&(bt.set_cookie("record_paste_type",null),that.reader_file_list({path:that.file_path})),layer.msg(rdata.msg,{icon:rdata.status?1:2})}))}))},recycle_bin_view:function(){var that=this;layer.open({type:1,shift:5,closeBtn:2,area:["80%","606px"],title:lan.files.recycle_bin_title,content:'
            '+lan.files.recycle_bin_on+'
            '+lan.files.recycle_bin_on_db+'
            '+lan.files.recycle_bin_ps+'

            '+lan.files.recycle_bin_type1+'

            '+lan.files.recycle_bin_type2+'

            '+lan.files.recycle_bin_type3+'

            '+lan.files.recycle_bin_type4+'

            '+lan.files.recycle_bin_type5+'

            '+lan.files.recycle_bin_type6+'

            '+lan.files.recycle_bin_th1+" "+lan.files.recycle_bin_th2+" "+lan.files.recycle_bin_th3+' '+lan.files.recycle_bin_th4+' '+lan.files.recycle_bin_th5+'
            ',success:function(){-1!=window.location.href.indexOf("database")?($(".re-con-menu p:last-child").addClass("on").siblings().removeClass("on"),that.render_recycle_list(6)):that.render_recycle_list(1),$(".re-con-menu").on("click","p",(function(){var _type=$(this).data("type");$(this).addClass("on").siblings().removeClass("on"),that.render_recycle_list(_type)}))}})},render_recycle_list:function(num){var that=this;this.$http("Get_Recycle_bin",(function(rdata){var body="";switch($("#Set_Recycle_bin").attr("checked",rdata.status),$("#Set_Recycle_bin_db").attr("checked",rdata.status_db),num){case 1:for(var i=0;i20&&(shortwebname=shortwebname.substring(0,20)+"..."),shortpath.length>20&&(shortpath=shortpath.substring(0,20)+"..."),body+=' '+shortwebname+' '+shortpath+" "+ToSize(rdata.dirs[i].size)+" "+getLocalTime(rdata.dirs[i].time)+' "+lan.files.recycle_bin_re+' | "+lan.files.recycle_bin_del+" "}for(var i=0;i20&&(shortwebname=shortwebname.substring(0,20)+"..."),shortpath.length>20&&(shortpath=shortpath.substring(0,20)+"..."),body+=' '+shortwebname+' '+shortpath+" "+ToSize(rdata.files[i].size)+" "+getLocalTime(rdata.files[i].time)+' "+lan.files.recycle_bin_re+' | "+lan.files.recycle_bin_del+" "}else{var shortwebname=rdata.files[i].name.replace(/'/,"\\'"),shortpath=rdata.files[i].dname;shortwebname.length>20&&(shortwebname=shortwebname.substring(0,20)+"..."),shortpath.length>20&&(shortpath=shortpath.substring(0,20)+"..."),body+=' '+shortwebname.replace("BTDB_","")+' mysql://'+shortpath.replace("BTDB_","")+" - "+getLocalTime(rdata.files[i].time)+' "+lan.files.recycle_bin_re+' | "+lan.files.recycle_bin_del+" "}return void $("#RecycleBody").html(body);case 2:for(var i=0;i20&&(shortwebname=shortwebname.substring(0,20)+"..."),shortpath.length>20&&(shortpath=shortpath.substring(0,20)+"..."),body+=' '+shortwebname+' '+shortpath+" "+ToSize(rdata.dirs[i].size)+" "+getLocalTime(rdata.dirs[i].time)+' "+lan.files.recycle_bin_re+' | "+lan.files.recycle_bin_del+" "}return void $("#RecycleBody").html(body);case 3:for(var i=0;i20&&(shortwebname=shortwebname.substring(0,20)+"..."),shortpath.length>20&&(shortpath=shortpath.substring(0,20)+"..."),body+=' '+shortwebname+' '+shortpath+" "+ToSize(rdata.files[i].size)+" "+getLocalTime(rdata.files[i].time)+' "+lan.files.recycle_bin_re+' | "+lan.files.recycle_bin_del+" "}return void $("#RecycleBody").html(body);case 4:for(var i=0;i20&&(shortwebname=shortwebname.substring(0,20)+"..."),shortpath.length>20&&(shortpath=shortpath.substring(0,20)+"..."),body+=' '+shortwebname+' '+shortpath+" "+ToSize(rdata.files[i].size)+" "+getLocalTime(rdata.files[i].time)+' "+lan.files.recycle_bin_re+' | "+lan.files.recycle_bin_del+" "}return void $("#RecycleBody").html(body);case 5:for(var i=0;i20&&(shortwebname=shortwebname.substring(0,20)+"..."),shortpath.length>20&&(shortpath=shortpath.substring(0,20)+"..."),body+=' '+shortwebname+' '+shortpath+" "+ToSize(rdata.files[i].size)+" "+getLocalTime(rdata.files[i].time)+' "+lan.files.recycle_bin_re+' | "+lan.files.recycle_bin_del+" "}return void $("#RecycleBody").html(body);case 6:for(var i=0;i20&&(shortwebname=shortwebname.substring(0,20)+"..."),shortpath.length>20&&(shortpath=shortpath.substring(0,20)+"..."),body+=' '+shortwebname.replace("BTDB_","")+' mysql://'+shortpath.replace("BTDB_","")+" - "+getLocalTime(rdata.files[i].time)+' "+lan.files.recycle_bin_re+' | "+lan.files.recycle_bin_del+" "}return void $("#RecycleBody").html(body)}function getFileName(name){var text=name.split("."),n;return text=text[text.length-1]}function ReisImage(fileName){for(var exts=["jpg","jpeg","png","bmp","gif","tiff","ico"],i=0;i
            '+lan.files.recycle_bin_on+'
            '+lan.files.recycle_bin_on_db+'
            '+lan.files.recycle_bin_ps+'

            '+lan.files.recycle_bin_type1+'

            '+lan.files.recycle_bin_type2+'

            '+lan.files.recycle_bin_type3+'

            '+lan.files.recycle_bin_type4+'

            '+lan.files.recycle_bin_type5+'

            '+lan.files.recycle_bin_type6+'

            ',success:function(){-1!=window.location.href.indexOf("database")?($(".re-con-menu p:last-child").addClass("on").siblings().removeClass("on"),$(".re-con-menu p:eq(5)").click()):$(".re-con-menu p:eq(0)").click();var render_recycle=that.render_recycle_list();$(".re-con-menu").on("click","p",(function(){var _type=$(this).data("type");$(this).addClass("on").siblings().removeClass("on"),render_recycle.$refresh_table_list(!0)}))}})},render_recycle_list:function(){var that=this;$("#recycle_table").empty();var recycle_list=bt_tools.table({el:"#recycle_table",url:"/files?action=Get_Recycle_bin",height:480,dataFilter:function(res){var files=[];switch($(".re-con-menu p.on").index()){case 0:for(let i=0;i-1?(item.dname=item.dname.replace("BTDB_",""),item.name=item.name.replace("BTDB_",""),files.push($.extend(item,{type:"files"}))):"images"==ext?files.push($.extend(item,{type:ext})):files.push($.extend(item,{type:"files"}))}break;case 1:for(let i=0;i-1&&(item.dname=item.dname.replace("BTDB_",""),item.name=item.name.replace("BTDB_",""),console.log(),files.push($.extend(item,{type:"files"})))}}return $("#Set_Recycle_bin").attr("checked",res.status),$("#Set_Recycle_bin_db").attr("checked",res.status_db),{data:files}},column:[{type:"checkbox",class:"",width:18},{fid:"name",title:lan.files.recycle_bin_th1,width:155,template:function(row){return'
            '+row.name+"
            "}},{fid:"dname",title:lan.files.recycle_bin_th2,template:function(row){return''+row.dname+""}},{fid:"size",title:lan.files.recycle_bin_th3,width:85,template:function(row){return''+bt.format_size(row.size)+""}},{fid:"time",title:lan.files.recycle_bin_th4,width:180,template:function(row,index){return''+bt.format_data(row.time)+""}},{type:"group",align:"right",width:250,title:lan.files.recycle_bin_th5,group:[{title:lan.files.recycle_bin_re,event:function(row,index,ev,key,that){bt_file.ReRecycleBin(row.rname,(function(){that.$delete_table_row(index)}))}},{title:lan.files.recycle_bin_del,event:function(row,index,ev,key,that){bt_file.DelRecycleBin(row.rname,(function(){that.$delete_table_row(index)}))}}]}],tootls:[{type:"batch",positon:["left","bottom"],placeholder:"Please Choose",buttonValue:"Execute",disabledSelectValue:"Please select the port that needs batch operation!",selectList:[{title:"Restore",url:"/files?action=Re_Recycle_bin",load:!0,param:function(row){return{path:row.rname}},callback:function(that){bt.confirm({title:"Restore files",msg:"Batch restore selected files, do you want to continue?",icon:0},(function(index){layer.close(index),that.start_batch({},(function(list){for(var html="",i=0;i"+item.name+'
            '+(item.request.status?"Successful recovery":"Recovery failed")+"
            "}recycle_list.$batch_success_table({title:"Restore files",th:"File name",html:html}),recycle_list.$refresh_table_list(!0)}))}))}},{title:"Delete files permanently",url:"/files?action=Del_Recycle_bin",load:!0,param:function(row){return{path:row.rname}},callback:function(that){bt.confirm({title:"Delete selected files",msg:"Delete the selected file. The file will be completely deleted and cannot be recovered. Do you want to continue?",icon:0},(function(index){layer.close(index),that.start_batch({},(function(list){for(var html="",i=0;i"+item.name+'
            '+(item.request.status?"Successfully deleted":"Failed to delete")+"
            "}recycle_list.$batch_success_table({title:"Delete multiple files",th:"File name",html:html}),recycle_list.$refresh_table_list(!0)}))}))}}]}]});return bt_tools.$fixed_table_thead("#recycle_table .divtable"),recycle_list},Set_Recycle_bin:function(db){var loadT=layer.msg(lan.public.the,{icon:16,time:0,shade:[.3,"#000"]}),that=this,data={};1==db&&(data={db:db}),$.post("/files?action=Recycle_bin",data,(function(rdata){layer.close(loadT),rdata.status&&null==db&&(that.is_recycle=$("#Set_Recycle_bin").prop("checked")),layer.msg(rdata.msg,{icon:rdata.status?1:5})}))},ReRecycleBin:function(path,obj){layer.confirm(lan.files.recycle_bin_re_msg,{title:lan.files.recycle_bin_re_title,closeBtn:2,icon:3},(function(){var loadT=layer.msg(lan.files.recycle_bin_re_the,{icon:16,time:0,shade:[.3,"#000"]});$.post("/files?action=Re_Recycle_bin","path="+encodeURIComponent(path),(function(rdata){layer.close(loadT),layer.msg(rdata.msg,{icon:rdata.status?1:5}),$(obj).parents("tr").remove()}))}))},DelRecycleBin:function(path,obj){layer.confirm(lan.files.recycle_bin_del_msg,{title:lan.files.recycle_bin_del_title,closeBtn:2,icon:3},(function(){var loadT=layer.msg(lan.files.recycle_bin_del_the,{icon:16,time:0,shade:[.3,"#000"]});$.post("/files?action=Del_Recycle_bin","path="+encodeURIComponent(path),(function(rdata){layer.close(loadT),layer.msg(rdata.msg,{icon:rdata.status?1:5}),$(obj).parents("tr").remove()}))}))},CloseRecycleBin:function(){var _this=this;layer.confirm(lan.files.recycle_bin_close_msg,{title:lan.files.recycle_bin_close,closeBtn:2,icon:3},(function(){var loadT=layer.msg("
            "+lan.files.recycle_bin_close_the+"
            ",{icon:16,time:0,shade:[.3,"#000"]});setTimeout((function(){getSpeed(".myspeed")}),1e3),$.post("/files?action=Close_Recycle_bin","",(function(rdata){layer.close(loadT),layer.msg(rdata.msg,{icon:rdata.status?1:5}),_this.render_recycle_list()}))}))},open_property_view:function(data){console.log(data);var _this=this;_this.$http("get_file_attribute",{filename:data.path},(function(res){layer.open({type:1,closeBtn:2,title:"[ "+data.filename+" ] - "+(data.is_dir?"Folder":"File")+" properties",area:["580px","500px"],shadeClose:!1,content:'
            General Detail History
            Type:
            '+(res.is_dir||res.is_link?res.st_type:_this.ext_type_tips(res.st_type))+'
            Location:
            '+res.path+'
            Size:
            '+bt.format_size(res.st_size)+" ("+_this.font_thousandth(res.st_size)+' byte)
            Permissions:
            '+res.mode+'
            Group:
            '+res.group+'
            User:
            '+res.user+'
            Visit time:
            '+bt.format_data(res.st_atime)+'
            Modified time:
            '+bt.format_data(res.st_mtime)+'
            Properties
            Value
            Modified time
            Size
            MD5
            OPT
            ',success:function(layero,index){$(".bt-property-setting .tab-nav span").click((function(){var index=$(this).index();$(this).addClass("on").siblings().removeClass("on"),$(".property-box:eq("+index+")").addClass("active").siblings().removeClass("active")})),$(".history_box_view").on("click",".open_history_file",(function(){var _history=$(this).attr("data-time");openEditorView(0,data.path),setTimeout((function(){aceEditor.openHistoryEditorView({filename:data.path,history:_history},(function(){layer.close(index),$(".ace_conter_tips").show(),$(".ace_conter_tips .tips").html("Read-only file, the file is "+_item.path+", historic version [ "+bt.format_data(new Number(_history))+' ]Click to restore')}))}),500)})),$(".history_box_view").on("click",".recovery_file_historys",(function(){aceEditor.event_ecovery_file(this)}));var config={filename:["Name",data.filename],type:["Type",res.is_dir||res.is_link?res.st_type:_this.ext_type_tips(res.st_type)],path:"Location",st_size:["Size",bt.format_size(res.st_size)+" ("+_this.font_thousandth(res.st_size)+" byte)"],st_atime:["Visit time",bt.format_data(res.st_atime)],st_mtime:["Modified time",bt.format_data(res.st_mtime)],st_ctime:["Metadata modification time",bt.format_data(res.st_ctime)],md5:"MD5",sha1:"sha1",user:"User",group:"Group",mode:"Permissions",st_uid:"UID",st_gid:"GID",st_nlink:"Num of inode links",st_ino:"inode node num",st_mode:"inode protection mode",st_dev:"inode resident device"},html="",html2="";for(var key in config)if(Object.hasOwnProperty.call(config,key)){var element=config[key],value=$.isArray(element)?element[1]:res[key];html+='
            '+($.isArray(element)?element[0]:element)+'
            '+value+"
            "}for(let i=0;i
            '+bt.format_data(item.st_mtime)+'
            '+bt.format_size(item.st_size)+"
            "+item.md5+'
            view  |  restore
            '}""===html2&&(html2+='
            No historical version
            '),$(".details_list").html(html),$(".history_list ").html(html2),_this.fixed_table_thead(".details_box_view"),_this.fixed_table_thead(".history_box_view ")}})}))},fixed_table_thead:function(el){$(el).scroll((function(){var scrollTop=this.scrollTop;this.querySelector("thead").style.transform="translateY("+scrollTop+"px)"}))},font_thousandth:function(num){var source=String(num).split(".");return source[0]=source[0].replace(new RegExp("(\\d)(?=(\\d{3})+$)","ig"),"$1,"),source.join(".")},open_images_preview:function(data){var that=this,mask=$('
            '+data.filename+'
            '),images_config={natural_width:0,natural_height:0,init_width:0,init_height:0,preview_width:0,preview_height:0,current_width:0,current_height:0,current_left:0,current_top:0,rotate:0,scale:1,images_mouse:!1};if($(".preview_images_mask").length>0)return $("#preview_images").attr("src","/download?filename="+data.path),!1;function auto_images_size(transition){var rotate=Math.abs(images_config.rotate/90),preview_width=rotate%2==0?images_config.preview_width:images_config.preview_height,preview_height=rotate%2==0?images_config.preview_height:images_config.preview_width,preview_images=$("#preview_images"),css_config={};images_config.init_width=images_config.natural_width,images_config.init_height=images_config.natural_height,images_config.init_width>preview_width&&(images_config.init_width=preview_width,images_config.init_height=parseFloat((preview_width/images_config.natural_width*images_config.init_height).toFixed(2))),images_config.init_height>preview_height&&(images_config.init_width=parseFloat((preview_height/images_config.natural_height*images_config.init_width).toFixed(2)),images_config.init_height=preview_height),images_config.current_width=parseFloat(images_config.init_width*images_config.scale),images_config.current_height=parseFloat(images_config.init_height*images_config.scale),images_config.current_left=parseFloat(((images_config.preview_width-images_config.current_width)/2).toFixed(2)),images_config.current_top=parseFloat(((images_config.preview_height-images_config.current_height)/2).toFixed(2)),css_config={width:images_config.current_width,height:images_config.current_height,top:images_config.current_top,left:images_config.current_left,display:"inline",transform:"rotate("+images_config.rotate+"deg)",opacity:1,transition:"all 100ms"},!1===transition&&delete css_config.transition,preview_images.css(css_config)}$("body").css("overflow","hidden").append(mask),images_config.preview_width=mask[0].clientWidth,images_config.preview_height=mask[0].clientHeight,$(".preview_body img").load((function(){var img=$(this)[0];$(this).attr("data-index")||$(this).attr("data-index",data.images_id),images_config.natural_width=img.naturalWidth,images_config.natural_height=img.naturalHeight,auto_images_size(!1)})),$(".preview_images_mask .preview_head").on("mousedown",(function(e){e=e||window.event;var drag=$(this).parent();if($("body").addClass("select"),$(this).onselectstart=$(this).ondrag=function(){return!1},!$(e.target).hasClass("preview_close")){var diffX=e.clientX-drag.offset().left,diffY=e.clientY-drag.offset().top;$(document).on("mousemove",(function(e){var left=(e=e||window.event).clientX-diffX,top=e.clientY-diffY;left<0?left=0:left>window.innerWidth-drag.width()&&(left=window.innerWidth-drag.width()),top<0?top=0:top>window.innerHeight-drag.height()&&(top=window.innerHeight-drag.height()),drag.css({left:left,top:top,margin:0})})).on("mouseup",(function(){$(this).unbind("mousemove mouseup")}))}})),$(".preview_images_mask #preview_images").on("mousedown",(function(e){e=e||window.event,$(this).onselectstart=$(this).ondrag=function(){return!1};var images=$(this),preview=$(".preview_images_mask").offset(),diffX=e.clientX-preview.left,diffY=e.clientY-preview.top;$(".preview_images_mask").on("mousemove",(function(e){var offsetX=(e=e||window.event).clientX-preview.left-diffX,offsetY=e.clientY-preview.top-diffY,rotate=Math.abs(images_config.rotate/90),preview_width=rotate%2==0?images_config.preview_width:images_config.preview_height,preview_height=rotate%2==0?images_config.preview_height:images_config.preview_width,left,top;if(images_config.current_width>preview_width){var max_left=preview_width-images_config.current_width;(left=images_config.current_left+offsetX)>0?left=0:leftpreview_height){var max_top=preview_height-images_config.current_height;(top=images_config.current_top+offsetY)>0?top=0:toppreview_height&&images_config.current_top<=0&&images_config.current_height-preview_height<=images_config.current_top&&(images_config.current_top-=offsetY),images.css({left:images_config.current_left,top:images_config.current_top})})).on("mouseup",(function(){$(this).unbind("mousemove mouseup")})).on("dragstart",(function(){e.preventDefault()}))})).on("dragstart",(function(){return!1})),$(".preview_close").click((function(e){$(".preview_images_mask").remove()})),$(".preview_toolbar a").click((function(){var index=$(this).index(),images=$("#preview_images");switch(index){case 0:case 1:images_config.rotate=index?images_config.rotate+90:images_config.rotate-90,auto_images_size();break;case 2:case 3:if(3==images_config.scale&&2==index||.2==images_config.scale&&3==index)return layer.msg(images_config.scale>=1?"The image is the maximum size":"The image is the minimum size"),!1;images_config.scale=(2==index?Math.round(10*(images_config.scale+.4)):Math.round(10*(images_config.scale-.4)))/10,auto_images_size();break;case 4:var scale_offset=images_config.rotate%360;scale_offset>=180?images_config.rotate+=360-scale_offset:images_config.rotate-=scale_offset,images_config.scale=1,auto_images_size()}})),$(".preview_full,.preview_small").click((function(){$(this).hasClass("preview_full")?($(this).addClass("hidden").prev().removeClass("hidden"),images_config.preview_width=that.area[0],images_config.preview_height=that.area[1],mask.css({width:that.area[0],height:that.area[1],top:0,left:0,margin:0}).data("type","full"),auto_images_size()):($(this).addClass("hidden").next().removeClass("hidden"),$(".preview_images_mask").removeAttr("style"),images_config.preview_width=750,images_config.preview_height=650,auto_images_size())})),$(".preview_cut_view a").click((function(){var images_src="",preview_images=$("#preview_images"),images_id=parseInt(preview_images.attr("data-index"));$(this).index()?(images_id=images_id==that.file_images_list.length-1?0:images_id+1,images_src=that.file_images_list[images_id]):(images_id=0===images_id?that.file_images_list.length-1:images_id-1,images_src=that.file_images_list[images_id]),preview_images.attr("data-index",images_id).attr("src","/download?filename="+images_src),$(".preview_title").html(that.get_path_filename(images_src))}))},open_video_play:function(data){var old_filename=data.path,imgUrl="/download?filename="+data.path,p_tmp=data.path.split("/"),path=p_tmp.slice(0,p_tmp.length-1).join("/");layer.open({type:1,closeBtn:2,title:'Playing ['+p_tmp[p_tmp.length-1]+"]",area:["890px","402px"],shadeClose:!1,skin:"movie_pay",content:'
            ',success:function(){$.post("/files?action=get_videos",{path:path},(function(rdata){for(var video_list='',index=0,i=0;i"}video_list+="
            File nameSize
            '+rdata[i].name+''+ToSize(rdata[i].size)+"
            ",$(".video-list").html(video_list).scrollTop(34*index)}))}})},play_file:function(obj,filename){if($("#btvideo video").attr("data-filename")==filename)return!1;var imgUrl,v='';$("#btvideo").html(v);var p_tmp=filename.split("/");$(".btvideo-title").html(p_tmp[p_tmp.length-1]),$(".video-avt").removeClass("video-avt"),$(obj).parents("tr").addClass("video-avt")},copy_file_or_dir:function(data){bt.set_cookie("record_paste",data.path),bt.set_cookie("record_paste_type","copy"),$(".file_all_paste").removeClass("hide"),layer.msg("Copy successfully. Please click [Paste] or Ctrl + V to paste")},cut_file_or_dir:function(data){bt.set_cookie("record_paste",data.path),bt.set_cookie("record_paste_type","cut"),$(".file_all_paste").removeClass("hide"),layer.msg("Cut successfully. Please click [Paste] or Ctrl + V to paste")},paste_file_or_dir:function(){var that=this,_isPaste=bt.get_cookie("record_paste_type"),_paste=bt.get_cookie("record_paste"),_filename="";if("null"!=_paste&&null!=_paste&&(_filename=_paste.split("/").pop()),that.file_path.indexOf(_paste)>-1)return layer.msg("Can not paste ["+_filename+"] here, Because the item cannot be pasted into itself.",{icon:0}),!1;if("null"!=_isPaste&&null!=_isPaste)switch(_isPaste){case"cut":case"copy":this.check_exists_files_req({dfile:this.file_path,filename:_filename},(function(result){if(result.length>0){for(var tbody="",i=0;i'+result[i].filename+""+ToSize(result[i].size)+""+getLocalTime(result[i].mtime)+"";var mbody;SafeMessage("This files will be overwritten",'
            '+tbody+"
            File nameSizeLast edit time
            ",(function(){that.config_paste_to(_paste,_filename)}))}else that.config_paste_to(_paste,_filename)}));break;case"1":case"2":that.batch_file_paste()}},config_paste_to:function(path,_filename){var that=this,_type=bt.get_cookie("record_paste_type");this.$http("copy"==_type?"CopyFile":"MvFile",{sfile:path,dfile:this.file_path+"/"+_filename},(function(rdata){rdata.status&&(bt.set_cookie("record_paste",null),bt.set_cookie("record_paste_type",null),that.reader_file_list({path:that.file_path})),layer.msg(rdata.msg,{icon:rdata.status?1:2})}))},rename_file_or_dir:function(data){var that=this;that.is_editor=!0,$(".file_list_content .file_tr:nth-child("+(data.index+1)+")").addClass("editr_tr").find(".file_title").empty().append($("icon"==bt.get_cookie("rank")?'":'')),"icon"==bt.get_cookie("rank")&&$("textarea[name=rename_file_input]").css({height:$("textarea[name=rename_file_input]")[0].scrollHeight}),$(("icon"==bt.get_cookie("rank")?"textarea":"input")+"[name=rename_file_input]").on("input",(function(){if("icon"==bt.get_cookie("rank")&&(this.style.height="auto",this.style.height=this.scrollHeight+"px"),"file"==data.type){var ext_arry=$(this).val().split("."),ext=ext_arry[ext_arry.length-1];$(this).parent().prev().find(".file_icon").removeAttr("class").addClass("file_icon file_"+ext)}})).keyup((function(e){13==e.keyCode&&$(this).blur(),e.stopPropagation(),e.preventDefault()})).blur((function(){var _val=$(this).val().replace(/[\r\n]/g,""),config={sfile:data.path,dfile:that.path_resolve(that.file_path,_val)};return data.filename==_val||""==_val?($(".file_list_content .file_tr:nth-child("+(data.index+1)+")").removeClass("editr_tr").find(".file_title").empty().append($(""+data.filename+"")),that.is_editor=!1,!1):that.match_unqualified_string(_val)?layer.msg('The name cannot have /\\:*?"<>| symbol',{icon:2}):(that.rename_file_req(config,(function(res){that.reader_file_list({path:that.file_path},(function(){layer.msg(res.msg,{icon:res.status?1:2})}))})),void(that.is_editor=!1))})).focus()},set_file_share:function(data){var that=this;this.loadY=bt.open({type:1,shift:5,closeBtn:2,area:"450px",title:"Set share "+data.type_tips+"-["+data.filename+"]",btn:["Create","Cancel"],content:'
            Share name
            Expiration date
            Extraction code
            ',yes:function(indexs,layers){var ps=$("[name=ps]").val(),expire=$("[name=expire]:checked").val(),password=$("[name=password]").val();if(""===ps)return layer.msg("No sharing name!",{icon:2}),!1;that.create_download_url({filename:data.path,ps:ps,password:password,expire:expire},(function(res){if(!res.status)return layer.msg(res.msg,{icon:res.status?1:2}),!1;var rdata=res.msg;that.file_list[data.index]=$.extend(that.file_list[data.index],{down_id:rdata.id,down_info:rdata}),that.loadY.close(),that.info_file_share(data),that.reader_file_list_content(that.file_list)}))},success:function(layers,index){$("#random_paw").click((function(){$(this).prev().val(bt.get_random(6))}))}})},info_file_share:function(data){var that=this;if(void 0===data.down_info)return this.get_download_url_find({id:data.down_id},(function(res){that.file_list[data.index]=$.extend(that.file_list[data.index],{down_info:res}),that.file_share_view(that.file_list[data.index],"fonticon")})),!1;this.file_share_view(data,"fonticon")},file_share_view:function(datas,type){var data=datas;"fonticon"==type&&(data=datas.down_info);var that=this,download_url=location.origin+"/down/"+data.token;this.loadY=bt.open({type:1,shift:5,closeBtn:2,area:"550px",title:"Share details-["+data.filename+"]",content:'
            Share name
            Expiration date
            '+(data.expire>new Date("2099-01-01 00:00:00").getTime()/1e3?'Permanent':bt.format_data(data.expire))+'
            ',success:function(layers,index){var copy_url=new ClipboardJS(".copy_url"),copy_paw=new ClipboardJS(".copy_paw");copy_url.on("success",(function(e){layer.msg("Copy link succeeded!",{icon:1}),e.clearSelection()})),copy_paw.on("success",(function(e){layer.msg("Copy link and extraction code succeeded!",{icon:1}),e.clearSelection()})),$(".layer_close").click((function(){layer.close(index)})),$(".QR_code").click((function(){layer.closeAll("tips"),layer.tips('
            ',".QR_code",{area:["150px","150px"],tips:[1,"#ececec"],time:0,shade:[.05,"#000"],shadeClose:!0,success:function(){jQuery("#QR_code").qrcode({render:"canvas",text:download_url,height:130,width:130})}})})),$(".close_down").click((function(){that.remove_download_url({id:data.id,fileName:data.filename},(function(res){that.loadY.close(),"fonticon"==type&&(that.file_list[datas.index].down_id=0,that.reader_file_list_content(that.file_list)),"list"==type&&that.render_share_list(),layer.msg(res.msg,{icon:res.status?1:2})}))}))}})},del_file_or_dir:function(data){var that=this;that.is_recycle?bt.confirm({title:"Delete "+data.type_tips+"[ "+data.filename+" ]",msg:"Comfirm delete "+data.type_tips+"[ "+data.path+" ],it will move to recycle bin after delete, continue?"},(function(){that.del_file_req(data,(function(res){that.reader_file_list({path:that.file_path}),layer.msg(res.msg,{icon:res.status?1:2})}))})):bt.show_confirm("Delete "+data.type_tips+"[ "+data.filename+" ]",'Recycle bin is not currently open, delete '+("dir"==data.type?"directory":"file")+" cannot be restored after, continue?
            ",(function(){that.del_file_req(data,(function(res){that.reader_file_list({path:that.file_path}),layer.msg(res.msg,{icon:res.status?1:2})}))}))},cancel_file_favorites:function(data){var that=this,index=data.index;this.loadY=bt.confirm({title:data.filename+lan.files.unfavorite1,msg:lan.files.unfavorite1+" ["+data.path+"] "+lan.files.continue},(function(){that.$http("del_files_store",{path:data.path},(function(res){res.status&&(that.file_list[index].caret=!1,that.reader_file_list_content(that.file_list),that.load_favorites_index_list()),layer.msg(res.msg,{icon:res.status?1:2})}))}))},set_soft_link:function(data){var that=this;bt_tools.open({title:"Create Softlink",area:"520px",content:{class:"pd20",formLabelWidth:"110px",form:[{label:"Source file",group:{type:"text",name:"sfile",width:"280px",placeholder:"Please select the folder and file to be linked",icon:{type:"glyphicon-folder-open",event:function(ev){},select:"all"},value:"",input:function(ev){}}},{label:"Softlink name",group:{type:"text",name:"name",width:"280px",placeholder:"Please enter the name of the softlink",value:""}}]},init:function(){var e=null,t=setInterval((function(){if($('input[name="sfile"]').length<1&&clearInterval(t),e!=$('input[name="sfile"]').val()){var i=(e=$('input[name="sfile"]').val()).split("/");i.length>1&&$('[name="name"]').val(i[i.length-1])}}),100)},yes:function(e,i,a){delete(e=$.extend(e,{dfile:that.file_path+"/"+e.name})).name,bt_tools.send("files/CreateLink",e,(function(e){e.status&&(layer.close(i),bt.msg(e),that.reader_file_list())}),{tips:"Create Softlink"})}})},set_file_authority:function(data,isPatch){var that=this;that.get_file_authority({path:data.path},(function(rdata){var tex='
            ';that.loadY=layer.open({type:1,closeBtn:2,title:lan.files.set_auth+"["+data.filename+"]",area:"465px",shadeClose:!1,content:'
            Set permission
            Backups list
            '+tex+"
            "+lan.files.file_own+'

            '+lan.files.file_read+'

            '+lan.files.file_write+'

            '+lan.files.file_exec+"

            "+lan.files.file_group+'

            '+lan.files.file_read+'

            '+lan.files.file_write+'

            '+lan.files.file_exec+"

            "+lan.files.file_public+'

            '+lan.files.file_read+'

            '+lan.files.file_write+'

            '+lan.files.file_exec+'

            '+lan.files.file_menu_auth+", "+lan.files.file_own+'
            ",success:function(index,layers){that.edit_access_authority(),$("#access").keyup((function(){that.edit_access_authority()})),$("input[type=checkbox]").change((function(){for(var idName=["owner","group","public"],onacc="",n=0;n

            Please enter the current backup name

            Remarks
            ',yes:function(layerss,index){$(".layer_close").click((function(){layer.close(index)})),that.$http("back_path_permissions",{back_sub_dir:sub_type,path:file,remark:$("input.form-control").val()},(function(edata){if(layer.close(layerss),!edata.status)return layer.msg(edata.msg,{time:1900,icon:2}),!1;if(0==type){var new_back=that.backup_list();$(".buplist").html(new_back)}else if(3==type){var chmod=$("#access").val(),chown=$("#chown").val(),all=$("#accept_all").prop("checked")?"True":"False",data="filename="+encodeURIComponent(file)+"&user="+chown+"&access="+chmod+"&all="+all;Oksend(data),layer.closeAll()}layer.msg(edata.msg,{time:1900,icon:1})}))},btn2:function(){layer.close(layerss)},cancel:function(){layer.close(layerss)}})},backup_list:function(){var all_back="",that=this;this.$http("get_all_back",(function(edata){for(var i=0;i '+date+' "+edata[i][3]+' '+edata[i][1]+' Del '}$(".allback .buplist").html(all_back)}))},manage_backup:function(){var that=this,layerss=layer.open({type:1,closeBtn:2,title:"Manage Backups",area:["630px","500px"],shadeClose:!1,content:'
            Backup time Backup path Name Delect
            ',cancel:function(){layer.close(layerss)},success:function(){that.backup_list(),$("#btn-backup").click((function(e){var backup_path=$("#server_path").val();that.backup_files_permission(backup_path,0)})),$(".allback").on("click",".del_back",(function(){var _id=$(this).parents("tr").attr("data-id");that.del_backup(_id)}))}})},del_backup:function(id){var that=this;layer.confirm("The backup cannot be restored after deletion.
            Continue to delete?",{title:"Confirm delete?",btn:["Yes","No"],closeBtn:2},(function(index,layero){that.$http("del_path_premissions",{id:id},(function(edata){var file=$(".layui-layer-title:eq(0)").text();"Manage Backups"!==file?(file=$(".backup_list").attr("data-path"),that.backup_files_list(file)):$(".allback tbody tr[data-id="+id+"]").remove(),layer.msg(edata.msg,{icon:edata.status?1:2})}))}))},backup_files_list:function(fileName){var that=this;that.$http("get_path_premissions",{path:fileName},(function(edata){var tbody="",cont="";if(0==edata.length)tbody='No data';else for(var i=0;i '+edata[i][4]+" "+edata[i][2]+" "+edata[i][1]+" "+date+' Restore | Del '}cont='
            Fix all permissions to [ Folder: 755, File: 644 ]
            '+tbody+"
            Name permission Owner Backup Time Opt
            ",$(".chmodset").hide(),$(".backup_lists").html(cont),$(".fixper").click((function(){layer.confirm("Note: Under the file or folder all permissions will be fixed to [ Folder: 755, File: 644 ]",{title:"Fix Permissions?",btn:["Confirm","Cancel"],closeBtn:2},(function(index,layero){that.$http("fix_permissions",{path:fileName},(function(res){layer.closeAll(),that.reader_file_list({path:that.file_path,is_operating:!1}),layer.msg(res.msg,{icon:res.status?1:2})}))}))})),$(".restore_backup").click((function(){that.restore_file_permission($(this).attr("data-time"),fileName)})),$(".backup_list").on("click",".del_back",(function(){var _id=$(this).attr("data-id");that.del_backup(_id)}))}))},restore_file_permission:function(restore_time,fileName){var that=this,sub_type=$("#accept_all").prop("checked")?1:0,layerss=layer.open({type:1,closeBtn:2,title:"Confirm restore",area:"330px",shadeClose:!1,btn:["Yes","No"],content:'
            Restore would overwrite the current settings, continue?
            ',yes:function(layerss,index){that.$http("restore_path_permissions",{restore_sub_dir:sub_type,date:restore_time,path:fileName},(function(edata){layer.closeAll(),layer.msg(edata.msg,{icon:1,time:1900})}))},btn2:function(){layer.close(layerss)},cancel:function(){layer.close(layerss)}})},get_present_task_view:function(){this.file_present_task=layer.open({type:1,title:"Real-time task queue",area:"500px",closeBtn:2,skin:"present_task_list",shadeClose:!1,shade:!1,offset:"auto",content:'
            '})},render_present_task_list:function(){var that=this;this.get_task_req({status:-3},(function(lists){if(0==lists.length)return layer.close(that.file_present_task),that.file_present_task=null,void that.reader_file_list({path:that.file_path,is_operating:!1});var task_body="",is_add=!1;$.each(lists,(function(index,item){-1==item.status?(that.file_present_task||that.get_present_task_view(),"1"==item.type?task_body+='
            • '+lan.layout.download+item.shell+''+item.log.pre+'%'+lan.public.cancel+'
              '+item.log.used+"/"+ToSize(item.log.total)+''+(0==item.log.speed?lan.layout.connect:item.log.speed)+'/s'+lan.files.expected_to_be+": "+item.log.time+"
            ":task_body+='
            '+item.name+": "+item.shell+''+lan.public.cancel+'
            '+item.log+"
            "):(is_add||(task_body+='
            '+lan.layout.wait_task+'
              ',is_add=!0),task_body+='
            • '+item.name+": "+item.shell+'X
            • ')})),that.file_present_task&&(is_add&&(task_body+="
            "),$(".message-list").html(task_body)),setTimeout((function(){that.render_present_task_list()}),1e3)}))},remove_present_task:function(id){var that=this;layer.confirm("Do you want to cancel the upload of files? It need to delete the uploaded files manually. Continue?",{title:"Cancel file upload",icon:0},(function(indexs){bt.send("remove_task","task/remove_task",{id:id},(function(rdata){layer.msg(rdata.msg,{icon:1}),layer.close(that.file_present_task),that.file_present_task=null})),layer.close(indexs)}))},edit_access_authority:function(){for(var access=$("#access").val(),idName=["owner","group","public"],n=0;nidName.length))switch(onacc>7&&$("#access").val(access.substr(0,access.length-1)),onacc){case"1":$("#"+idName[i]+"_x").prop("checked",!0);break;case"2":$("#"+idName[i]+"_w").prop("checked",!0);break;case"3":$("#"+idName[i]+"_x").prop("checked",!0),$("#"+idName[i]+"_w").prop("checked",!0);break;case"4":$("#"+idName[i]+"_r").prop("checked",!0);break;case"5":$("#"+idName[i]+"_r").prop("checked",!0),$("#"+idName[i]+"_x").prop("checked",!0);break;case"6":$("#"+idName[i]+"_r").prop("checked",!0),$("#"+idName[i]+"_w").prop("checked",!0);break;case"7":$("#"+idName[i]+"_r").prop("checked",!0),$("#"+idName[i]+"_w").prop("checked",!0),$("#"+idName[i]+"_x").prop("checked",!0)}}},get_file_authority:function(data,callback){this.$http("GetFileAccess",{filename:data.path},(function(rdata){callback&&callback(rdata)}))},set_dir_kill:function(data){var that=this;"php"==data.ext?that.$http("file_webshell_check",{filename:data.path},(function(rdata){layer.msg(rdata.msg,{icon:rdata.status?1:2})})):layer.confirm("目录查杀将包含子目录中的php文件,是否操作?",{title:"目录查杀["+data.filename+"]",closeBtn:2,icon:3},(function(index){that.$http("dir_webshell_check",{path:data.path},(function(rdata){layer.msg(rdata.msg,{icon:rdata.status?1:2})}))}))},path_resolve:function(paths,param){var path="",split="";return Array.isArray(param)||(param=[param]),paths.replace(/([\/|\/]*)$/,(function($1){return split=$1,"www"})),$.each(param,(function(index,item){path+="/"+item})),(paths+path).replace("//","/")},get_ext_name:function(fileName){for(var extArr=fileName.split("."),exts=["folder","folder-unempty","sql","c","cpp","cs","flv","css","js","htm","html","java","log","mht","php","url","xml","ai","bmp","cdr","gif","ico","jpeg","jpg","JPG","png","psd","webp","ape","avi","mkv","mov","mp3","mp4","mpeg","mpg","rm","rmvb","swf","wav","webm","wma","wmv","rtf","docx","fdf","potm","pptx","txt","xlsb","xlsx","7z","cab","iso","rar","zip","gz","bt","file","apk","bookfolder","folder-empty","fromchromefolder","documentfolder","fromphonefolder","mix","musicfolder","picturefolder","videofolder","sefolder","access","mdb","accdb","fla","doc","docm","dotx","dotm","dot","pdf","ppt","pptm","pot","xls","csv","xlsm"],extLastName=extArr[extArr.length-1],i=0;i')},yes:function(){var ress;if(""==form.getVal().dfile)return layer.msg("Please select a valid address",{icon:2});form.submitForm((function(res,datas){setTimeout((function(){that.reader_file_list({path:datas.path})}),1e3),null!=res&&null!=res||layer.msg(lan.files.zip_ok,{icon:1}),res.status&&that.render_present_task_list(),layer.close(loadT)}))}})}))},unpack_file_to_path:function(data){var that=this,_type="zip",spath="";spath=data.path.substring(0,data.path.lastIndexOf("/")),this.reader_form_line({url:"UnZip",overall:{width:"310px"},data:[{label:"File name",name:"z_name",placeholder:"Compress file name",value:data.path},{label:"Compress path",name:"z_path",placeholder:"Compress path",value:spath},{label:"Encoding",name:"z_code",type:"select",value:"UTF-8",list:[["UTF-8","UTF-8"],["gb18030","GBK"]]}],beforeSend:function(updata){return{sfile:updata.z_name,dfile:updata.z_path,type:_type,coding:updata.z_code,password:updata.z_password}}},(function(form,html){var loadT=layer.open({type:1,title:"Decompress file",area:"520px",shadeClose:!1,closeBtn:2,skin:"unpack_file_view",btn:["Comfirm","Cancel"],content:html[0].outerHTML,success:function(){"gz"==data.ext&&(_type="tar"),"zip"==_type&&$(".unpack_file_view .line:nth-child(2)").append('
            Password
            ')},yes:function(){var ress=form.getVal();return""==ress.z_name?layer.msg("Please enter the file name path",{icon:2}):""==ress.z_path?layer.msg("Please enter the decompression address",{icon:2}):void form.submitForm((function(res,datas){layer.close(loadT),setTimeout((function(){that.reader_file_list({path:datas.path})}),1e3),res.status&&that.render_present_task_list(),layer.msg(res.msg,{icon:res.status?1:2})}))}})}))},match_unqualified_string:function(item){var containSpecial;return RegExp(/[(\ )(\*)(\|)(\\)(\:)(\")(\/)(\<)(\>)(\?)(\)]+/).test(item)},reader_form_line:function(config,callback){var that=this,random=bt.get_random(10),html=$('
            '),data=config,eventList=[],that=this;Array.isArray(config)||(data=config.data),$.each(data,(function(index,item){var labelWidth=item.labelWidth||config.overall.labelWidth||null,event_random=bt.get_random(10),width=item.labelWidth||config.overall.width||null,form_line=$('
            "+(item.label||"")+'
            '),form_el=$(function(){switch(item.type){case"select":return"";case"text":default:return"'}}(item));(item.eventType||item.event)&&(Array.isArray(item.eventType)||(item.eventType=[item.eventType]),$.each(item.eventType,(function(index,items){if(eventList.push({el:event_random,type:items||"click",event:item[items]||null}),config.el){var els=$('[data-event="'+item.el+'"]');if(item[items])"enter"==items?els.on("keyup",(function(e){13==e.keyCode&&item.event(e)})):els.on(item||"click",item.event);else if("focus"==items){var vals=els.val();""!=vals&&els.val("").focus().val(vals)}else els[items]()}}))),form_line.find(".info-r").append(form_el),html.append(form_line)})),config.el&&$(config.el).empty().append(html),callback&&callback({getVal:function(){return $("#"+random).serializeObject()},setEvent:function(){$.each(eventList,(function(index,item){var els=$('[data-event="'+item.el+'"]');if(null===item.event)if("focus"==item.type){var vals=els.val();""!=vals&&els.val("").focus().val(vals)}else els[item.type]();else"enter"==item.type?els.on("keyup",(function(e){13==e.keyCode&&item.event(e)})):els.on(item.type,item.event)}))},submitForm:function(callback){var data=this.getVal();config.beforeSend&&(data=config.beforeSend(data)),that.loadT=bt.load("submitting the form, please wait..."),bt.send(config.url,"files/"+config.url,data,(function(rdata){that.loadT.close(),callback&&callback(rdata,data)}))}},html)},$http:function(data,parem,callback){var that=this,loadT="";"string"==typeof data?("object"!=typeof parem&&(callback=parem,parem={}),Array.isArray(this.method_list[data])||(this.method_list[data]=["files",this.method_list[data]]),this.$http({method:data,tips:!!this.method_list[data][1]&&this.method_list[data][1],module:this.method_list[data][0],data:parem,msg:!0},callback)):(void 0!==data.tips&&data.tips&&(loadT=bt.load(data.tips)),bt.send(data.method,(data.module||"files")+"/"+data.method,data.data||{},(function(res){if(""!=loadT&&loadT.close(),"string"==typeof res&&(res=JSON.parse(res)),!1===res.status&&res.msg)return bt.msg(res),!1;parem&&parem(res)})))}};bt_file.init(),Function.prototype.delay=function(that,arry,time){return Array.isArray(arry)||(time=arry,arry=[]),void 0===time&&(time=0),setTimeout(this.apply(that,arry),time),this},jQuery.prototype.serializeObject=function(){var a,o,h,i,e;for(a=this.serializeArray(),h=(o={}).hasOwnProperty,i=0;i','') + var tmp = error_body.split('During handling of the above exception, another exception occurred:') + error_body = tmp[tmp.length-1]; + var error_msg = '
            \ +

            出错了,面板运行时发生错误!

            \ +
            '+error_body.trim()+'
            \ +
              \ +
            • 很抱歉,面板运行时意外发生错误,请尝试按以下顺序尝试解除此错误:
            • \ +
            • 1、在[首页]右上角点击修复面板,并退出面板重新登录。
            • \ +
            • 2、如上述尝试未能解除此错误,请截图此窗口到宝塔论坛发贴寻求帮助, 论坛地址:https://www.bt.cn/bbs
            • \ +
            \ +
            ' + + }else{ + var error_msg = jqXHR.responseText; + } + $(".layui-layer-padding").parents('.layer-anim').remove(); + $(".layui-layer-shade").remove(); + setTimeout(function(){ + layer.open({ + title: false, + content: error_msg, + closeBtn:2, + area: ["1000px","800px"], + btn:false, + shadeClose:false, + shade:0.3, + success:function(){ + $('pre').scrollTop(100000000000) + } + }); + },100) + } + } // dataFilter: ajax_decrypt, // beforeSend: ajax_encrypt }); - } + } } ajaxSetup(); @@ -3171,20 +3246,12 @@ function ActionTask() { }) } -function RemoveTask(b) { - var a = layer.msg(lan.public.the_del, { - icon: 16, - time: 0, - shade: [0.3, "#000"] - }); - $.post("/files?action=RemoveTask", "id=" + b, function(c) { - layer.close(a); - layer.msg(c.msg, { - icon: c.status ? 1 : 5 - }); - }).error(function() { - layer.msg(lan.bt.task_close, { icon: 1 }); - }); +function RemoveTask(id) { + var loadT = bt.load(lan.public.the_del); + bt.send('RemoveTask','files/RemoveTask',{id:id},function(res){ + bt.msg(res) + reader_realtime_tasks() + }) } function GetTaskList(a) { @@ -3692,30 +3759,183 @@ function getSpeed(sele) { }); } //消息盒子 -function messagebox() { - layer.open({ - type: 1, - title: lan.bt.task_title, - area: "750px", - closeBtn: 2, - shadeClose: false, - content: '
            \ -
            \ -
            \ -

            ' + lan.bt.task_list + '(0)

            \ -

            ' + lan.bt.task_msg + '(0)

            \ -

            ' + lan.public.exec_log + '

            \ -
            \ -
            \ -
            \ -
            \ -
            \ -
            ' - }); - $(".bt-w-menu p").click(function() { - $(this).addClass("bgw").siblings().removeClass("bgw"); - }); - tasklist(); +function messagebox(){ + layer.open({ + type: 1, + title: lan.bt.task_title, + area: "680px", + closeBtn: 2, + shadeClose: false, + content: '
            ' + + '
            ' + + '
            ' + + '

            '+ lan.bt.task_list +' (0)

            ' + + '

            '+ lan.bt.task_msg +' (0)

            ' + + '

            '+lan.public.exec_log+'

            ' + + '
            ' + + '
            ' + + '
              '+ + '
              '+ + '
              '+ + '
              ' + + '
              ' + + '
              ', + success: function(layers,indexs){ + $(layers).find('.bt-w-menu p').on('click',function(){ + var index = $(this).index() + $(this).addClass('bgw').siblings().removeClass('bgw'); + $(layers).find('.bt-w-con .bt-w-item:eq('+ index +')').addClass('active').siblings().removeClass('active'); + switch (index) { + case 0: + reader_realtime_tasks() + break; + case 1: + reader_message_list() + break; + case 2: + var loadT = bt.load('正在获取执行日志,请稍后...') + bt.send('GetExecLog','files/GetExecLog',{},function(res){ + loadT.close(); + var exec_log = $('#execLog'); + console.log(exec_log) + exec_log.html(res) + exec_log[0].scrollTop = exec_log[0].scrollHeight + }) + break; + } + }) + reader_realtime_tasks() + setTimeout(function(){ + reader_realtime_tasks() + },1000) + reader_message_list() + } + }); +} + +function get_message_data(page,callback){ + if(typeof page === "function") callback = page,page = 1; + var loadT = bt.load('正在获取消息列表,请稍后...'); + bt.send("getData","data/getData",{ + tojs:'reader_message_list', + table:'tasks', + result:'2,4,6,8', + limit:'11', + search:'1', + p:page + },function(res){ + loadT.close(); + if(callback) callback(res); + }) +} + +function reader_message_list(page){ + get_message_data(page,function(res){ + var html = "",f = false,task_count = 0; + for (var i = 0; i < res.data.length; i++) { + var item = res.data[i]; + if (item.status !== '1') { + task_count ++; + continue; + } + html += '
              ' + item.name + '【' + lan.bt.task_ok + '】' + lan.bt.time + (item.end - item.start) + lan.bt.s + '
              ' + item.addtime + '' + } + var con = '
              \ + \ + '+ html + '\ +
              '+ lan.bt.task_name + '' + lan.bt.task_time + '
              \ +
              \ + \ +
              \ +
              '; + + + var msg_count = res.page.match(/\'Pcount\'>.+<\/span>/)[0].replace(/[^0-9]/ig, ""); + $("#taskCompleteNum").text(parseInt(msg_count) - task_count); + $("#messageContent").html(con); + $("#taskPage").html(res.page); + }) +} + + +function get_realtime_tasks(callback){ + bt.send('GetTaskSpeed','files/GetTaskSpeed',{},function(res){ + if(callback) callback(res) + }) +} + +var initTime = null,messageBoxWssock = null; + +function reader_realtime_tasks(refresh){ + get_realtime_tasks(function(res){ + var command_install_list = $('#command_install_list'), + loading = 'data:image/gif;base64,R0lGODlhDgACAIAAAHNzcwAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQFDgABACwAAAAAAgACAAACAoRRACH5BAUOAAEALAQAAAACAAIAAAIChFEAIfkEBQ4AAQAsCAAAAAIAAgAAAgKEUQAh+QQJDgABACwAAAAADgACAAACBoyPBpu9BQA7', + html = '', + message = res.msg, + task = res.task; + $('#taskNum').html(typeof res.task === "undefined"?0:res.task.length); + if(typeof res.task === "undefined"){ + html = '
              '+lan.bt.task_not_list+'
              ' + lan.public.task_long_time_not_exec + '
              ' + command_install_list.html(html) + }else{ + var shell = '', message_split = message.split("\n"); + for(var j = 0; j < message_split.length; j++) { + shell += message_split[j] + "
              "; + } + if(command_install_list.find('li').length){ + if(command_install_list.find('li').length > res.task.length) command_install_list.find('li:eq(0)').remove(); + if(task[0].status !== '0' && !command_install_list.find('pre').length) command_install_list.find('li:eq(0)').append('
              ' + shell +'
              ') + messageBoxWssock.el = command_install_list.find('pre'); + }else{ + for (var i = 0; i < task.length; i++) { + var item = task[i], task_html = '', del_task = ''+ lan.public.del +'',loading_img = ""; + if(item.status === '-1' && item.type === 'download'){ + task_html = "
              " + item.name + "" + (ToSize(message.used) + "/" + ToSize(message.total)) + "" + message.pre + "%"+ lan.bt.task_downloading +" "+ loading_img +" | "+ del_task +""; + }else{ + task_html += '' + item.name + ''; + task_html += ''; + if(item.status !== "-1"){ + task_html += lan.bt.task_sleep + ' | ' + del_task; + }else{ + var is_scan = item.name.indexOf("扫描") !== -1; + task_html += (is_scan?lan.bt.task_scan:lan.bt.task_install) + ' ' + loading_img + ' | ' + del_task; + } + task_html += ""; + if(item.type !== "download" && item.status === "-1"){ + task_html += '
              ' + shell +'
              ' + } + } + html += "
            • "+ task_html +"
            • "; + } + command_install_list.find('ul').append(html); + } + if(task[0].status === '0'){ + setTimeout(function(){ + reader_realtime_tasks(true) + },100) + } + if(command_install_list.find('pre').length){ + var pre = command_install_list.find('pre') + pre.scrollTop(pre[0].scrollHeight) + } + if(!refresh){ + messageBoxWssock = bt_tools.command_line_output({ + el:'#command_install_list .command_output_pre', + area:['100%','200px'], + shell:'tail -n 100 -f /tmp/panelExec.log', + message:function(res){ + if(res.indexOf('|-Successify ---Script execution completed---') > -1){ + setTimeout(function(){ + reader_realtime_tasks(true) + reader_message_list() + },100) + } + } + } + ); + } + } + }) } //取执行日志 @@ -3986,7 +4206,9 @@ var Term = { }, //连接服务器成功 on_open:function(ws_event){ - Term.send(JSON.stringify(Term.ssh_info || {})) + var http_token = $("#request_token_head").attr('token'); + Term.send(JSON.stringify({'x-http-token':http_token})) + if(JSON.stringify(Term.ssh_info) !== '{}') Term.send(JSON.stringify(Term.ssh_info)) // Term.term.FitAddon.fit(); // Term.resize(); // var f_path = $("#fileInputPath").val(); @@ -4166,10 +4388,10 @@ var Term = { // }, run: function (ssh_info) { - if($("#panel_debug").attr("data") == 'True') { - layer.msg('Error: unable to create websocket connection, please close 【Developer mode】 on the settings page!',{icon:2,time:5000}); - return; - } + // if($("#panel_debug").attr("data") == 'True') { + // layer.msg('Error: unable to create websocket connection, please close 【Developer mode】 on the settings page!',{icon:2,time:5000}); + // return; + // } var loadT = layer.msg('It is loading the files required by the terminal. Please wait...', { icon: 16, time: 0, shade: 0.3 }); loadScript([ "/static/js/xterm.js" diff --git a/BTPanel/static/js/public_backup.js b/BTPanel/static/js/public_backup.js index 0c0b4139..252374f8 100644 --- a/BTPanel/static/js/public_backup.js +++ b/BTPanel/static/js/public_backup.js @@ -517,9 +517,7 @@ var bt = { } if (callback) callback(rdata); - }).error(function(e, f) { - if (callback) callback('error'); - }); + }) } }, linux_format_param: function(param) { @@ -551,11 +549,11 @@ var bt = { var btnObj = { title: config.title ? config.title : false, shadeClose: config.shadeClose ? config.shadeClose : true, - closeBtn: config.closeBtn ? config.closeBtn : 0, + closeBtn: config.closeBtn ? config.closeBtn : 2, scrollbar: true, - shade: 0.3, + shade: 0.3 }; - if (!config.hasOwnProperty('time')) config.time = 2000; + if (!config.hasOwnProperty('time')) config.time = 0; if (typeof config.msg == 'string' && bt.contains(config.msg, 'ERROR')) config.time = 0; if (config.hasOwnProperty('icon')) { @@ -572,7 +570,7 @@ var bt = { if (config.msg) msg += config.msg; if (config.msg_error) msg += config.msg_error; if (config.msg_solve) msg += config.msg_solve; - + if(config.status) $.extend(btnObj,{closeBtn:0,time:2000}); layer.msg(msg, btnObj); }, confirm: function(config, callback, callback1) { @@ -3886,7 +3884,10 @@ bt.soft = { bt.soft.pro.get_product_discount_by(config.pid,function(rdata){ //rdata = {"36": {"discount": 1, "did": 0, "price": 3564, "name": "正常", "sprice": 3564}, "24": {"discount": 1, "did": 0, "price": 2376, "name": "正常", "sprice": 2376}, "12": {"discount": 1, "did": 0, "price": 1188, "name": "正常", "sprice": 1188}, "6": {"discount": 1, "did": 0, "price": 594, "name": "正常", "sprice": 594}, "3": {"discount": 1, "did": 0, "price": 297, "name": "正常", "sprice": 297}, "1": {"discount": 1, "did": 0, "price": 99, "name": "正常", "sprice": 99}, "pid": "100000045"}; if(typeof rdata.status === "boolean"){ - if(!rdata.status) return false; + if(!rdata.status) { + bt.msg({status:false, msg:rdata.msg}) + return false; + } } that.product_cache[config.pid] = rdata; setTimeout(function(){ delete that.product_cache[config.pid] },60000); @@ -4020,7 +4021,8 @@ bt.soft = { if (rdata.status === false){ bt.set_cookie('force', 1); if (soft) soft.flush_cache(); - layer.msg(rdata.msg, { icon: 2 }); + // layer.msg(rdata.msg, { icon: 2 }); + bt.msg({status:false,msg:rdata.msg}) return; } config.pay = parseInt($('#libPay-mode .pay-cycle-btn.active').data('condition')); @@ -4484,7 +4486,8 @@ bt.soft = { if (rdata.status === false) { bt.set_cookie('force', 1); if (soft) soft.flush_cache(); - layer.msg(rdata.msg, { icon: 2 }); + // layer.msg(rdata.msg, { icon: 2 }); + bt.msg({status:false,msg:rdata.msg}) return; } $(".pay-wx").html(''); @@ -5833,6 +5836,17 @@ bt.site = { if (callback) callback(rdata); }) }, + get_site_error_logs: function (siteName, callback) { + var loading = bt.load(); + bt.send('get_site_errlog', 'site/get_site_errlog', { + siteName: siteName + }, function (rdata) { + loading.close(); + if (rdata.status !== true) rdata.msg = ''; + if (rdata.msg == '') rdata.msg = lan.public_backup.no_log; + if (callback) callback(rdata); + }) + }, get_site_ssl: function(siteName, callback) { var loadT = bt.load(lan.site.the_msg); bt.send('GetSSL', 'site/GetSSL', { siteName: siteName }, function(rdata) { diff --git a/BTPanel/static/js/site.js b/BTPanel/static/js/site.js index e6cc9265..d3c2745c 100644 --- a/BTPanel/static/js/site.js +++ b/BTPanel/static/js/site.js @@ -68,7 +68,7 @@ var site_table = bt_tools.table({ $('.site-menu p:eq(8)').click(); },500); }}, - {title:lan.site.operate,type:'group',width:118,align:'right',group:[ + {title:lan.site.operate,type:'group',width:119,align:'right',group:[ { title:'WAF', event:function(row,index,ev,key,that){ @@ -302,7 +302,7 @@ var site_table = bt_tools.table({ if(checked) param[$(this).attr('name')] = checked?1:0; }) if(callback) callback(param); - },"
              "); + },"
              "); } } ], @@ -662,54 +662,9 @@ var site = { }) }, 1000); }, - // add_site: function(callback) { - // bt.site.add_site(function(rdata) { - // if (rdata.siteStatus) { - // if(callback) callback(rdata); - // //site.get_list(); - // var html = ''; - // var ftpData = ''; - // if (rdata.ftpStatus) { - // var list = []; - // list.push({ title: lan.site.user, val: rdata.ftpUser }); - // list.push({ title: lan.site.password, val: rdata.ftpPass }); - // var item = {}; - // item.title = lan.site.ftp; - // item.list = list; - // ftpData = bt.render_ps(item); - // } - // var sqlData = ''; - // if (rdata.databaseStatus) { - // var list = []; - // list.push({ title: lan.site.database_name, val: rdata.databaseUser }); - // list.push({ title: lan.site.user, val: rdata.databaseUser }); - // list.push({ title: lan.site.password, val: rdata.databasePass }); - // var item = {}; - // item.title = lan.site.database_txt; - // item.list = list; - // sqlData = bt.render_ps(item); - // } - // if (ftpData == '' && sqlData == '') { - // bt.msg({ msg: lan.site.success_txt, icon: 1 }) - // } else { - // bt.open({ - // type: 1, - // area: '600px', - // title: lan.site.success_txt, - // closeBtn: 2, - // shadeClose: false, - // content: "
              " + ftpData + sqlData + "
              " - // }); - - // if ($(".success-msg").height() < 150) { - // $(".success-msg").find("img").css({ "width": "150px", "margin-top": "30px" }); - // } - // } - // } else { - // bt.msg(rdata); - // } - // }) - // }, + /** + * @description 添加站点 + */ add_site: function (callback) { var add_web = bt_tools.form({ data:{}, //用于存储初始值和编辑时的赋值内容 @@ -1032,6 +987,11 @@ var site = { }, yes:function(indexs){ var formValue = !web_tab.active?add_web.$get_form_value():bath_web.$get_form_value(); + console.log(formValue) + if(formValue.webname === ''){ + bt.msg({status:false,msg:'The website domain name cannot be empty!'}) + return false; + } if(!web_tab.active){ // 创建站点 var loading = bt.load(); add_web.$get_form_element(true); @@ -1866,6 +1826,7 @@ var site = { var pdata = { php_version: $("select[name='php_version']").val(), composer_args: $("select[name='composer_args']").val(), + composer_cmd: $("input[name='composer_cmd']").val(), repo: $("select[name='repo']").val(), path: $("input[name='composer_path']").val(), user: $("select[name='composer_user']").val() @@ -1939,6 +1900,11 @@ var site = { '' + '' + '' + + + '
              Extra commands
              ' + + '' + + '
              ' + + '
              Source
              ' + '' + // }, + // { + // text: '切换', + // name: 'btn_change_phpversion', + // type: 'button', + // callback: function(pdata) { + // var other = $('.other-version').val(); + // if(pdata.versions == 'other' && other == ''){ + // layer.msg('自定义PHP版本时,PHP连接配置不能为空'); + // $('.other-version').focus(); + // return; + // } + // bt.site.set_phpversion(web.name, pdata.versions, other, function(ret) { + // if (ret.status) { + // var versions = $('[name="versions"]').val(); + // versions = versions.slice(0, versions.length - 1) + '.' + versions.slice(-1); + // if (versions == '0.0') versions = '静态'; + // site_table.$refresh_table_list(true); + // site.reload() + // setTimeout(function() { + // bt.msg(ret); + // }, 1000); + // }else{ + // bt.msg(ret); + // } + + // }) + // } + // } + // ] + // } + // var _form_data = bt.render_form_line(data); + // var _html = $(_form_data.html); + // _html.append(bt.render_help([lan.site.switch_php_help1, lan.site.switch_php_help2, lan.site.switch_php_help3])); + // $('#webedit-con').append(_html); + // bt.render_clicks(_form_data.clicks); + // $('#webedit-con').append('
              ' + lan.site.session_off + '
              ' + bt.render_help([lan.site.independent_storage])); + + // function get_session_status() { + // var loading = bt.load('Getting session status...'); + // bt.send('get_php_session_path', 'config/get_php_session_path', { id: web.id }, function(tdata) { + // loading.close(); + // $('#session_switch').prop("checked", tdata); + // }) + // }; + // get_session_status() + // $('#session_switch').click(function() { + // var val = $(this).prop('checked'); + // bt.send('set_php_session_path', 'config/set_php_session_path', { id: web.id, act: val ? 1 : 0 }, function(rdata) { + // get_session_status(); + // bt.msg(rdata) + // }); + // }) + var data = { items: [ - { title: lan.site.php_ver, name: 'versions', value: sdata.phpversion, type: 'select', items: versions }, { - text: lan.site.switch, + title: 'PHP version', + name: 'versions', + value: sdata.phpversion, + type: 'select', + items: versions , + ps:'' + }, + { + text: 'Switch', name: 'btn_change_phpversion', type: 'button', callback: function(pdata) { - bt.site.set_phpversion(web.name, pdata.versions, function(ret) { - if (ret.status) site.reload(8) - bt.msg(ret); + var other = $('.other-version').val(); + if(pdata.versions == 'other' && other == ''){ + layer.msg('When customizing the PHP version, the PHP connection configuration cannot be empty'); + $('.other-version').focus(); + return; + } + bt.site.set_phpversion(web.name, pdata.versions, other, function(ret) { + if (ret.status) { + var versions = $('[name="versions"]').val(); + versions = versions.slice(0, versions.length - 1) + '.' + versions.slice(-1); + if (versions == '0.0') versions = 'Static'; + site_table.$refresh_table_list(true); + site.reload() + setTimeout(function() { + bt.msg(ret); + }, 1000); + }else{ + bt.msg(ret); + } }) } } @@ -3445,13 +3499,30 @@ var site = { } var _form_data = bt.render_form_line(data); var _html = $(_form_data.html); - _html.append(bt.render_help([lan.site.switch_php_help1, lan.site.switch_php_help2, lan.site.switch_php_help3])); + _html.append(bt.render_help(['Select the version according to your program requirements', 'Try not to use PHP5.2 unless you have to, as this can reduce your server security', 'PHP7 does not support the MySQL extension. The default installation is mysqli and mysql-pdo',"[Customize] You can customize the PHP connection information by selecting the available PHP connection configuration","[Customize] Currently only support NGINX","Support TCP or UNIX configuration. Example: 192.168.1.25:9001 or unix:/tmp/php8.sock"])); $('#webedit-con').append(_html); bt.render_clicks(_form_data.clicks); - $('#webedit-con').append('
              ' + lan.site.session_off + '
              ' + bt.render_help([lan.site.independent_storage])); + if(sdata.phpversion != 'other'){ + $('#webedit-con').append('
              ' + lan.site.session_off + '
              ' + + bt.render_help(['When enabled, session files will be stored in a separate folder, not in a common storage location with other sites', 'Do not enable this option if you are saving sessions to caches such as memcache/redis in your PHP configuration'])); + } + if(sdata.phpversion != 'other'){ + $('.other-version').hide(); + } + setTimeout(function(){ + $('select[name="versions"]').change(function(){ + var phpversion = $(this).val(); + console.log(phpversion); + if(phpversion == 'other'){ + $('.other-version').show(); + }else{ + $('.other-version').hide(); + } + }); + },500); function get_session_status() { - var loading = bt.load('Getting session status...'); + var loading = bt.load('Please wait while getting session status'); bt.send('get_php_session_path', 'config/get_php_session_path', { id: web.id }, function(tdata) { loading.close(); $('#session_switch').prop("checked", tdata); @@ -3461,9 +3532,11 @@ var site = { $('#session_switch').click(function() { var val = $(this).prop('checked'); bt.send('set_php_session_path', 'config/set_php_session_path', { id: web.id, act: val ? 1 : 0 }, function(rdata) { - get_session_status(); bt.msg(rdata) - }); + }) + setTimeout(function() { + get_session_status(); + }, 500); }) }) }) @@ -4314,28 +4387,24 @@ var site = { }) }, get_site_logs: function(web) { - bt.site.get_site_logs(web.name, function(rdata) { - var robj = $('#webedit-con'),_form_data; - var logs = { class: 'bt-logs', items: [{ name: 'site_logs', height: '547px', value: rdata.msg, width: '100%', type: 'textarea' }] }; - var _form_data = bt.render_form_line(logs); - robj.append(_form_data.html); - robj.find('.site_logs').css('resize','none'); - bt.render_clicks(_form_data.clicks); - $('textarea[name="site_logs"]').attr('readonly', true); - $('textarea[name="site_logs"]').scrollTop(100000000000); - var tabs = '
              accesslogerrorlog
              '; - $('textarea[name="site_logs"]').before(tabs); - $('#logs_tabs').on('click','span' ,function () { - var url = $(this).attr('data-url'), - loadT = bt.load(); - if(!$(this).hasClass('on')) $(this).addClass('on').siblings().removeClass('on'); - bt.send(url, 'site/'+url,{siteName:web.name}, function(rdata) { - loadT.close(); - var _text = (rdata.msg=='')?'Currently no logs':rdata.msg; - $('textarea[name="site_logs"]').val(_text); - }); - }); - }) + $('#webedit-con').append('
              ') + var serverType = bt.get_cookie('serverType'),shell = 'tail -n 100 -f /www/wwwlogs/'+ web.name; + var _tab = [{ + title: "Access log", + on: true, + callback:function(robj){ + var shellCopy = shell + (serverType === 'nginx'?'.':serverType === 'apache'?'-access_':'_ols.access_') + 'log'; + bt_tools.command_line_output({ el:'#webedit-con .tab-con', shell:shellCopy,area:['100%','580px']}) + } + },{ + title: "Error log", + callback:function(robj){ + var shellCopy = shell + (serverType === 'nginx'?'.error.':serverType === 'apache'?'-error_':'_ols.error_') + 'log'; + bt_tools.command_line_output({ el:'#webedit-con .tab-con', shell:shellCopy,area:['100%','580px']}) + } + }] + bt.render_tab('tabLogs',_tab); + $('#tabLogs span:eq(0)').click(); } }, create_let: function(ddata, callback) { diff --git a/BTPanel/static/js/soft.js b/BTPanel/static/js/soft.js index dbc6cdf8..122e41c5 100644 --- a/BTPanel/static/js/soft.js +++ b/BTPanel/static/js/soft.js @@ -9,7 +9,7 @@ var soft = { if (type == undefined || type == 'null' || type == 'undefined') type = 0; if (!search) search = $("#SearchValue").val(); if (search == undefined || search == 'null' || search == 'undefined' || search == '') search = undefined; - var _this = this; + var _this = this, commonly_software = $('#commonly_software'); var istype = getCookie('softType'); if(istype == 'undefined' || istype == 'null' || !istype){ istype = 0; @@ -18,6 +18,7 @@ var soft = { if (page == 0) page = bt.get_cookie('p' + type); if (type == '11'){ soft.get_dep_list(1); + commonly_software.hide(); return; } soft.is_install = false; @@ -59,8 +60,10 @@ var soft = { $(this).addClass("on").siblings().removeClass("on"); if (_type !== '11') { soft.get_list(0, _type); + commonly_software.show(); } else { soft.get_dep_list(0); + commonly_software.hide(); } }) @@ -636,6 +639,21 @@ var soft = { } } }, + /** + * @description 设置软件信息 + * @param {object} rdata 软件列表请求数据 + * @param {string} type 列表类型 + */ + render_soft_recommend: function () { + bt.send('get_usually_plugin', 'plugin/get_usually_plugin', {}, function (res) { + var html = ''; + for (var i = 0; i < res.length; i++) { + var item = res[i]; + html += '
              ' + item.title + '
              ' + } + $('#commonly_software .commonly_software_list').html(html) + }) + }, render_tips_btn:function(node,arry){ if(!Array.isArray(arry)) arry = [arry] for(var i=0;i
              '); + console.log(this.config.height) + if ($(_that.config.el + '.divtable').length === 0) $(_that.config.el).append('
              '); } this.$reader_content(); if(_that.config.url !== undefined){ @@ -50,7 +52,7 @@ var bt_tools = { }else if(this.config.data !== undefined){ this.$reader_content(this.config.data); }else { - alert(lan.public.miss_data_or_url); + alert(lan['public'].miss_data_or_url); } if(this.config.methods){ //挂载实例方法 $.extend(this,this.config.methods); @@ -60,7 +62,7 @@ var bt_tools = { /** * @description 刷新表格数据 * @return void - */ + */ $refresh_table_list:function(load){ var _that = this,loadT; if(load) loadT = bt.load(lan.database.get_data); @@ -90,7 +92,7 @@ var bt_tools = { * @param {object} data 渲染的数据 * @param {number} page 数据分页 * @return void - */ + */ $reader_content:function(data,page){ var _that = this,thead = '',tbody = '',i = 0,column = this.config.column,event_list = {},checkbox = $(_that.config.el + ' .checkbox_' + _that.random); data = data || []; @@ -127,14 +129,14 @@ var bt_tools = { event_list = $.extend(event_list,template[1]); template = template[0]; } - tbody += ''+ template +''; + tbody += ''+ template +''; if(i === 0){ if(!event_list[className] && item.event) event_list[className] = {event:item.event,eventType:'click',type:'rows'}; } } } if(data.length > 0) tbody += '' - if(data.length == 0) tbody += ''+ (this.config.default || lan.public.empty) +''; + if(data.length == 0) tbody += ''+ (this.config['default'] || lan['public'].empty) +''; i++; } while (i < data.length); if(!this.init) this.$style_bind(this.style_list); @@ -156,7 +158,7 @@ var bt_tools = { * @param {object} rows 当前元素数据 * @param {number} j 当前模板index * @return void - */ + */ $custom_template_render:function(item,rows,j){ var className= 'event-'+ item.fid +'-'+ this.random,_template = item.template(rows,j),$template = $(_template); if($template.length>0){ @@ -174,7 +176,7 @@ var bt_tools = { * @description 替换table数据 * @param {string} newValue 内容数据 * @return void - */ + */ $modify_row_data:function(newValue){ this.event_rows_model.rows = $.extend(this.event_rows_model.rows,newValue); var row_model = this.event_rows_model,template = null; @@ -190,7 +192,7 @@ var bt_tools = { * @description 批量执行程序 * @param {object} config 配置文件 * @return void - */ + */ $batch_success_table:function(config){ var _that = this; bt.open({ @@ -199,7 +201,7 @@ var bt_tools = { area:config.area || ['380px','350px'], shadeClose:false, closeBtn:2, - content:config.content || '
              '+ config.title +' '+lan.public.success+'
              '+ config.html +'
              '+ config.th +''+lan.public.result+'
              ', + content:config.content || '
              '+ config.title +' '+lan['public'].success+'
              '+ config.html +'
              '+ config.th +''+lan['public'].result+'
              ', success:function(){ _that.$fixed_table_thead('.fiexd_thead'); } @@ -217,7 +219,7 @@ var bt_tools = { * @description 固定表头 * @param {string} el DOM选择器 * @return void - */ + */ $fixed_table_thead:function(el){ $(el).scroll(function(){ var scrollTop = this.scrollTop; @@ -228,30 +230,30 @@ var bt_tools = { /** * @description 设置批量操作显示 * @returns void 无 - */ + */ $set_batch_view:function(){ var bt_select_val = $(this.config.el + ' .bt_select_value'), - bt_select_btn = $(this.config.el + ' .bt_table_select_group').next(); + bt_select_btn = $(this.config.el + ' .bt_table_select_group').next(); if (typeof this.config.batch != "undefined") { //判断是否存在批量操作 - var bt_select_btn = $(this.config.el + ' .set_batch_option'); - if (typeof this.config.batch.config != "undefined") { // 判断批量操作是多个还是单个 - if (this.checkbox_list.length > 0) { - bt_select_btn.removeClass('bt-disabled btn-default').addClass('btn-success').text(lan.public.please_choose + this.batch_active.title + '(' + lan.public.selected + this.checkbox_list.length + ')') + var bt_select_btn = $(this.config.el + ' .set_batch_option'); + if (typeof this.config.batch.config != "undefined") { // 判断批量操作是多个还是单个 + if (this.checkbox_list.length > 0) { + bt_select_btn.removeClass('bt-disabled btn-default').addClass('btn-success').text(lan['public'].please_choose + this.batch_active.title + '(' + lan['public'].selected + this.checkbox_list.length + ')') + } else { + bt_select_btn.addClass('bt-disabled btn-default').removeClass('btn-success').text(lan['public'].please_choose + this.batch_active.title); + } } else { - bt_select_btn.addClass('bt-disabled btn-default').removeClass('btn-success').text(lan.public.please_choose + this.batch_active.title); + var bt_select_val = $(this.config.el + ' .bt_select_value'); + if (this.checkbox_list.length > 0) { + bt_select_btn.removeClass('bt-disabled btn-default').addClass('btn-success').prev().removeClass('bt-disabled'); + bt_select_val.find('em').html('(' + lan['public'].selected + this.checkbox_list.length + ')'); + } else { + bt_select_btn.addClass('bt-disabled btn-default').removeClass('btn-success').prev().addClass('bt-disabled'); + bt_select_val.children().eq(0).html(lan['public'].please_choose + ''); + bt_select_val.next().find('li').removeClass('active'); + this.batch_active = {}; + } } - } else { - var bt_select_val = $(this.config.el + ' .bt_select_value'); - if (this.checkbox_list.length > 0) { - bt_select_btn.removeClass('bt-disabled btn-default').addClass('btn-success').prev().removeClass('bt-disabled'); - bt_select_val.find('em').html('(' + lan.public.selected + this.checkbox_list.length + ')'); - } else { - bt_select_btn.addClass('bt-disabled btn-default').removeClass('btn-success').prev().addClass('bt-disabled'); - bt_select_val.children().eq(0).html(lan.public.please_choose + ''); - bt_select_val.next().find('li').removeClass('active'); - this.batch_active = {}; - } - } } }, @@ -260,16 +262,16 @@ var bt_tools = { * @param {object} data 渲染的数据 * @param {object} rows 渲染的模板 * @return void - */ - $reader_column_type:function(item,rows){ + */ + $reader_column_type:function(item,rows){ var value = rows[item.fid],event_list = {},className = '',config = [],_that = this; switch(item.type){ case 'text': //普通文本 config = [value,event_list]; - break; + break; case 'checkbox': //单选内容 config = ['',event_list]; - break; + break; case 'password': var _copy = '',_eye_open ='',className = 'ico_'+ _that.random +'_',html = '**********' if(item.eye_open){ @@ -281,19 +283,19 @@ var bt_tools = { if(!event_list[className+'copy']) event_list[className+'copy'] = {type:'copy_password'}; } config = [html,event_list]; - break; + break; case 'link': //超链接类型 className = 'click_'+ item.fid + '_' +this.random; if(!event_list[className] && item.event) event_list[className] = {event:item.event,type:'rows'}; config = [''+ value +'',event_list]; - break; + break; case 'input': //可编辑类型 blurName = 'blur_'+ item.fid + '_' +this.random; keyupName = 'keyup_'+ item.fid + '_' +this.random; if(!event_list[blurName] && item.blur) event_list[blurName] = {event:item.blur,eventType:'blur',type:'rows'}; if(!event_list[keyupName] && item.keyup) event_list[keyupName] = {event:item.keyup,eventType:'keyup',type:'rows'}; config = ['',event_list]; - break; + break; case 'status': // 状态类型 var active = ''; className = 'click_'+ item.fid + '_' +this.random; @@ -302,10 +304,10 @@ var bt_tools = { }); if(!event_list[className] && item.event) event_list[className] = {event:item.event,type:'rows'}; config = [''+ active[1] +''+ (item.config.icon?'':'') +'',event_list]; - break; + break; case 'switch': //开关类型 // config = ['
              ',event_list]; - break; + break; case 'group': var _html = ''; $.each(item.group,function(index,items){ @@ -324,10 +326,10 @@ var bt_tools = { if(!event_list[className] && items.event) event_list[className] = {event:items.event,type:'rows'}; }); config = [_html,event_list]; - break; + break; default: config = [value,event_list]; - break; + break; } return config; }, @@ -336,7 +338,7 @@ var bt_tools = { * @description 渲染工具条 * @param {object} data 配置参数 * @return void - */ + */ $reader_tootls:function(config){ var _that = this,event_list = {}; /** @@ -346,7 +348,7 @@ var bt_tools = { */ function request(active,check_list){ var loadT = bt.load(active.title +lan.site.executing),batch_config = {}, - list = _that.$get_data_batch_list(active.paramId,check_list); + list = _that.$get_data_batch_list(active.paramId,check_list); if(!active.beforeRequest){ batch_config[active.paramName] = list.join(','); }else{ @@ -364,7 +366,7 @@ var bt_tools = { html += ''+ key +'
              '+ item +'
              '; }); $.each(res.success,function(index,item){ - html += ''+ item +'
              '+lan.public.success+'
              '; + html += ''+ item +'
              '+lan['public'].success+'
              '; }); _that.$batch_success_table({title:active.title,th:active.theadName,html:html}); _that.$refresh_table_list(true); @@ -388,7 +390,7 @@ var bt_tools = { start_batch:function(param,callback){ var _this = this; if(active.load){ - this.loadT = layer.msg(lan.public.executeing+ active.title +','+lan.public.schedule+':0/'+ this.check_list.length +','+lan.public.please_wait+ (active.clear?'cancel':''),$.extend({icon:16,skin:'batch_tips',shade:.3,time:0},active.clear?{area:'420px'}:{})); + this.loadT = layer.msg(lan['public'].executeing+ active.title +','+lan['public'].schedule+':0/'+ this.check_list.length +','+lan['public'].please_wait+ (active.clear?'cancel':''),$.extend({icon:16,skin:'batch_tips',shade:.3,time:0},active.clear?{area:'420px'}:{})); $('#layui-layer'+_this.loadT).on('click','.clear_batch',function(){ _this.clear_bacth(); }); @@ -417,13 +419,13 @@ var bt_tools = { delete this.config.param['bacth']; } if(!_this.bacth_status) return false; - if(active.load) $('#layui-layer'+_this.loadT).find('.layui-layer-content').html(''+lan.public.executeing+ active.title +','+lan.public.schedule+':'+ index +'/'+ _this.check_list.length +','+lan.public.please_wait+ (active.clear?'cancel':'')); + if(active.load) $('#layui-layer'+_this.loadT).find('.layui-layer-content').html(''+lan['public'].executeing+ active.title +','+lan['public'].schedule+':'+ index +'/'+ _this.check_list.length +','+lan['public'].please_wait+ (active.clear?'cancel':'')); bt_tools.send({ url:this.config.url, data:this.config.param, bacth:true, },function(res){ - $.extend(_this.check_list[index],{request:{status:typeof res.status === "boolean"?res.status:false,msg:res.msg || lan.public.request_error}}); + $.extend(_this.check_list[index],{request:{status:typeof res.status === "boolean"?res.status:false,msg:res.msg || lan['public'].request_error}}); index++; _this.bacth(index,callback); }); @@ -441,11 +443,11 @@ var bt_tools = { }else{ if(!active.confirm){ if(active.confirmVerify){ - bt.show_confirm(active.title+lan.public.in_bulk,active.title +lan.public.in_bulk+','+lan.public.risk_prompt,request) + bt.show_confirm(active.title+lan['public'].in_bulk,active.title +lan['public'].in_bulk+','+lan['public'].risk_prompt,request) }else{ bt.confirm({ - title:active.title+lan.public.in_bulk, - msg:active.title+lan.public.in_bulk+','+lan.public.risk_prompt, + title:active.title+lan['public'].in_bulk, + msg:active.title+lan['public'].in_bulk+','+lan['public'].risk_prompt, },function(){ if(request) request(active,check_list) }); @@ -477,14 +479,14 @@ var bt_tools = { } if(!event_list[_btn]) event_list[_btn] = {event:items.event,type:'button'}; }); - break; + break; case 'search': this.config.search = item; var _input = 'search_input_'+this.random,_btn = 'search_btn_'+ this.random; template = ''; if(!event_list[_input]) event_list[_input] = {eventType:'keyup',type:'search_input'}; if(!event_list[_btn]) event_list[_btn] = {type:'search_btn'}; - break; + break; case 'batch': this.config.batch = item; var batch_list = [],_html = '',active = item.config; @@ -505,10 +507,10 @@ var bt_tools = { active.param = $.extend(active.param,param); execute_batch(active,check_list,callback); }); - break; + break; case 'undefined': execute_batch(active,check_list); - break; + break; case 'object': var config = active.confirm; bt.open({ @@ -526,7 +528,7 @@ var bt_tools = { }); } }); - break; + break; } }); }else{ @@ -569,7 +571,7 @@ var bt_tools = { $(_that.config.el).on('click','.bt_table_select_group .item',function(e){ var _text = $(this).text(),_index = $(this).index(); $(this).addClass('active').siblings().removeClass('active'); - $(_that.config.el +' .bt_select_tips').html(_text + lan.public.in_bulk+'('+lan.site.have_been_selected+ _that.checkbox_list.length +')'); + $(_that.config.el +' .bt_select_tips').html(_text + lan['public'].in_bulk+'('+lan.site.have_been_selected+ _that.checkbox_list.length +')'); _that.batch_active = batch_list[_index]; if(!_that.checked) $('.bt_table_select_group').removeClass('active'); }); @@ -585,7 +587,7 @@ var bt_tools = { } if(JSON.stringify(active) === '{}'){ var bt_table_select_group = $(_that.config.el + ' .bt_table_select_group'); - layer.tips(lan.public.select_opt_type,bt_table_select_group,{tips:[1,'red'],time: 2000}); + layer.tips(lan['public'].select_opt_type,bt_table_select_group,{tips:[1,'red'],time: 2000}); bt_table_select_group.css('border','1px solid red'); setTimeout(function(){ bt_table_select_group.removeAttr('style'); @@ -598,16 +600,16 @@ var bt_tools = { active.param = $.extend(active.param,param); execute_batch(active,check_list,callback); }); - break; + break; case 'undefined': execute_batch(active,check_list); - break; + break; case 'object': var config = active.confirm; bt.open({ - title:config.title || lan.public.bulk_opt, + title:config.title || lan['public'].bulk_opt, area:config.area || '350px', - btn:config.btn || [lan.public.confirm,lan.public.cancel], + btn:config.btn || [lan['public'].confirm,lan['public'].cancel], content:config.content, success:function(layero,index){ config.success(layero,index,active); @@ -619,13 +621,13 @@ var bt_tools = { }); } }); - break; + break; } }); } - // template = '
              '+lan.public.select_opt_type+'
                '+ _html +'
              '; - template = '
              '+ (typeof item.config != 'undefined'?'':'
              '+lan.public.select_opt_type+'
                '+ _html +'
              ') +'
              '; - break; + // template = '
              '+lan['public'].select_opt_type+'
                '+ _html +'
              '; + template = '
              '+ (typeof item.config != 'undefined'?'':'
              '+lan['public'].select_opt_type+'
                '+ _html +'
              ') +'
              '; + break; // case 'batch_btn': // _that.batch = item; // $(_that.config.el).on('click','.set_batch_option',function(e){ @@ -652,9 +654,9 @@ var bt_tools = { // case 'object': // var config = active.confirm; // bt.open({ - // title:config.title || lan.public.exec, + // title:config.title || lan['public'].exec, // area:config.area || '350px', - // btn:config.btn || [lan.public.confirm,lan.public.cancel], + // btn:config.btn || [lan['public'].confirm,lan['public'].cancel], // content:config.content, // success:function(layero,index){ // config.success(layero,index,active); @@ -669,14 +671,14 @@ var bt_tools = { // break; // } // }); - // template = '
              '; + // template = '
              '; // break; case 'page': this.config.page = item; var pageNumber = bt.get_cookie(this.config.cookiePrefix+'_'+ this.config.page.numberParam); if(this.config.cookiePrefix && pageNumber) this.config.page.number = pageNumber; template = this.$reader_page(this.config.page,'
              1 '+lan.public_backup.total+'
              '); - break; + break; } if(template){ var tools_group = $(_that.config.el + ' .tootls_'+ item.positon[1]); @@ -702,7 +704,7 @@ var bt_tools = { * @description 获取数据批量列表 * @param {string} 需要获取的字段 * @return {array} 当前需要批量列表 - */ + */ $get_data_batch_list:function(fid,data){ var arry = []; $.each(data || this.data,function(index,item){ @@ -733,7 +735,7 @@ var bt_tools = { if(config.jump){ var inputName = 'page_jump_input-'+ this.random; var btnName = 'page_jump_btn_'+ this.random; - template += '
              '+lan.public.jump_to_page+'
              ' + template += '
              '+lan['public'].jump_to_page+'
              ' eventList[inputName] = {eventType:'keyup',type:'page_jump_input'}; eventList[btnName] = {type:'page_jump_btn'}; } @@ -748,26 +750,26 @@ var bt_tools = { * @param {object} rows 当前行数据 * @return {stinrg} className class类名 * @return void - */ + */ $dynamic_merge_style:function(column,index){ var str = ''; $.each(column,function(key,item){ switch(key){ case 'align': str += 'text-align:'+ item +';'; - break; + break; case 'width': str += 'width:'+ (typeof item == 'string'?item:item +'px') +';'; - break; + break; case 'style': str += item; - break; + break; case 'minWidth': str += 'min-width:'+ (typeof item == 'string'?item:item +'px') +';'; - break; + break; case 'maxWidth': str += 'max-width:'+ (typeof item == 'string'?item:item +'px') +';'; - break; + break; } }); return {index:index,css:str}; @@ -794,7 +796,7 @@ var bt_tools = { index:index } arry = [_that.event_rows_model.rows,_that.event_rows_model.index,ev,key,_that]; - break; + break; case 'sort': var model = _that.config.column[data1.index]; if($(this).hasClass('sort-active')) $('.sort_'+ _that.random + ' .sort-active').data({'sort':'desc'}); @@ -809,7 +811,7 @@ var bt_tools = { } _that.config.sort = _that.config.sortParam({name:model.fid,sort:data1.sort}) _that.$refresh_table_list(true); - break; + break; case 'checkbox': var all = $(_that.config.el + ' [data-checkbox="all"]'),checkbox_list = $(_that.config.el +' tbody .checkbox_'+_that.random); if(data1.checkbox == undefined){ @@ -846,54 +848,54 @@ var bt_tools = { } } _that.$set_batch_view(); - break; + break; case 'button': arry.push(ev,_that); - break; + break; case 'search_focus': var search_tips = $(_that.config.el+' .bt_search_tips'); if($(_that.config.el + ' .bt_search_tips').length > 0){ search_tips.remove(); } - break; + break; case 'search_input': if(ev.keyCode == 13){ $(_that.config.el +' .search_btn_'+ _that.random).click(); return false; } - break; + break; case 'search_btn': var _search = $(_that.config.el+' .search_input'),val = $(_that.config.el+' .search_input').val(); _that.config.search.value = val; _search.append('
              '+ val +'
              '); _that.$refresh_table_list(true); - break; + break; case 'page_select': var limit = parseInt($(this).val()); _that.config.page.number = limit; _that.config.page.page = 1; _that.$refresh_table_list(true); return false; - break; + break; case 'page_jump_input': if(ev.keyCode == 13){ $(_that.config.el +' .page_jump_btn_'+ _that.random).click(); $(this).focus(); } return false; - break; + break; case 'page_jump_btn': var jump_page = parseInt($(_that.config.el +' .page_jump_input-'+ _that.random).val()),max_number = Math.ceil(_that.config.page.total/ _that.config.page.number); if(jump_page > max_number) jump_page = _that.config.page.page; _that.config.page.page = jump_page; _that.$refresh_table_list(true); - break; + break; case 'cut_page_number': var page = parseInt($(this).attr('href').match(/([0-9]*)$/)[0]) _that.config.page.page = page; _that.$refresh_table_list(true); return false; - break; + break; case 'eye_open_password': if($(this).hasClass('glyphicon-eye-open')){ $(this).addClass('glyphicon-eye-close').removeClass('glyphicon-eye-open'); @@ -903,11 +905,11 @@ var bt_tools = { $(this).prev().html('**********'); } return false; - break; + break; case 'copy_password': bt.pub.copy_pass(_that.data[index].password); return false; - break; + break; } if(item.event) item.event.apply(this,arry); }); @@ -936,7 +938,7 @@ var bt_tools = { /** * @deprecated 获取WIN高度或宽度 * @returns 返回当期的宽度和高度 - */ + */ $get_win_area:function(){ return [window.innerWidth,window.innerHeight]; }, @@ -945,7 +947,7 @@ var bt_tools = { * @description 请求数据, * @param {object} param 参数和请求路径 * @return void - */ + */ $http:function(success){ var param = {},config = this.config,_page = config.page,_search = config.search,_sort = config.sort || {}; if(_page){ @@ -974,14 +976,14 @@ var bt_tools = { * @param {object|string} data 当前 {path:[string] 选择路径,title:[string] title标题,ext:[array]限制的文件类型},或选择目录地址,可以为空,为空这默认使用当前目录作为选择目录 * @param {function} 回调函数,选择完成后的操作 * @return void - */ + */ select_file:function(data,callback){ - if(typeof data === 'string') data = {path:data,type:2,title:lan.public.select_fileordir,ext:[],limit:''}; + if(typeof data === 'string') data = {path:data,type:2,title:lan['public'].select_fileordir,ext:[],limit:''}; if(typeof data === 'function') type = callback,callback = data,data = {path:bt.get_cookie('Path')}; if(typeof type !== 'number') type = 0; var that = this,select_file = { type:type, - type_tips:type == 0?lan.public.dir:(type == 1?lan.site.file:lan.public.fileordir), + type_tips:type == 0?lan['public'].dir:(type == 1?lan.site.file:lan['public'].fileordir), select_list:[], select_path:bt.get_cookie('Path') || (bt.os == 'Windows'?setup_path:'/www/wwwroot'), select_config:{}, @@ -991,11 +993,11 @@ var bt_tools = { this.scroll_width = select_file.getScrollbarWidth(); layer.open({ type:1, - title: data.title || (lan.public.select + _this.type_tips), + title: data.title || (lan['public'].select + _this.type_tips), shadeClose:false, closeBtn:1, area:['650px','550px'], - content:'
              '+lan.public.name+''+lan.public.modify_time+''+lan.site.redirect_type+'
              文件修改时间类型
              '+ _this.type_tips +'名:
              ', + content:'
              '+lan['public'].name+''+lan['public'].modify_time+''+lan.site.redirect_type+'
              文件修改时间类型
              '+ _this.type_tips +'名:
              ', success:function(){ _this.evnet_bind(); _this.render_file_list(function(){ @@ -1007,7 +1009,7 @@ var bt_tools = { }, /** * @description 事件绑定 - */ + */ evnet_bind:function(){ var _this = this; $('#select_dir_list').on('click','tr',function(){ @@ -1035,15 +1037,15 @@ var bt_tools = { var x = ev.clientX,th = $(this).parent(),th_index = th.index(),th_width = th[0].clientWidth,min_width = parseInt($(this).parent().attr('data-min')),timeOut = null; if(ev.which === 1){ var document_mousemove = function(e){ - var move_x = e.clientX,offset_x = move_x - x,_width = th_width + offset_x; - timeOut = setTimeout(function(){ - _this.set_select_width(th_index,'width:'+_width+'px'); - },0); - }, - document_mouseup = function(){ - $(this).unbind(document_mousemove); - $(this).unbind(document_mouseup); - }; + var move_x = e.clientX,offset_x = move_x - x,_width = th_width + offset_x; + timeOut = setTimeout(function(){ + _this.set_select_width(th_index,'width:'+_width+'px'); + },0); + }, + document_mouseup = function(){ + $(this).unbind(document_mousemove); + $(this).unbind(document_mouseup); + }; $(document).on('mousemove',document_mousemove).one('mouseup',function(){ $(this).unbind(document_mousemove); $(this).unbind(this); @@ -1071,7 +1073,7 @@ var bt_tools = { /** * @description 设置当前路径宽度 * @param {} - */ + */ set_path_width:function(width){ var _width = 0,_dir_view = $('.file_dir_view')[0].offsetWidth,_item = $('.file_dir_view .file_dir_item'),_arry = [],_width =0; $('.file_dir_view .file_dir_item').each(function(){ @@ -1091,7 +1093,7 @@ var bt_tools = { /** * @description 渲染文件列表 * @param {object} data 配置参数,包含path路径、serarch搜索字段 - */ + */ render_file_list:function(data,callback){ var mount_html = '',dir_html = '',_this = this,datas = {path:this.select_path,sort:'type',disk:true}; if(typeof data == "undefined") data = datas; @@ -1114,7 +1116,7 @@ var bt_tools = { mount_html += '
              '+ ''+ ''+ name +''+ - '
              '; + '
              '; }); $.each(arry,function(index,item){ var mtime = bt.format_data(item.mtime),type = (item.type == 'dir'?'文件夹':'文件'); @@ -1133,7 +1135,7 @@ var bt_tools = { * @description 渲染路径列表 * @param {Function} callback 回调函数 * @return void - */ + */ render_path_list:function(path,callback){ var html = '
              ', path_before = '',dir_list = path.split("/").splice(1),first_dir = path.split("/")[0]; if(bt.os === 'Windows'){ @@ -1164,7 +1166,7 @@ var bt_tools = { * @description 设置标题宽度 * @param {string} th_index 表头序列号 * @param {string} style class样式 - */ + */ set_select_width:function(th_index,style){ var _this = this,className = '.select_dir_list tbody td:nth-child('+ (th_index+1) +')>span,.select_dir_list thead th:nth-child('+ (th_index+1) +')>span',style_index = $('#th-index-'+th_index); if(style_index.length > 0){ @@ -1204,7 +1206,7 @@ var bt_tools = { * @description 渲染Form表单 * @param {*} config * @return 当前实例对象 - */ + */ form: function (config) { var _that = this; function ReaderForm(config) { @@ -1243,7 +1245,7 @@ var bt_tools = { html += that.$reader_content_row(index, item); }); that.element = $('
              ' + html + '
              '); - _content = $('
              '); + _content = $('
              '); _content.append(that.element); if (callback) callback(); return _content[0].outerHTML; @@ -1257,11 +1259,11 @@ var bt_tools = { */ $reader_content_row: function (index, data) { var that = this,help = data.help,labelWidth = this.config.formLabelWidth || data.formLabelWidth; - return '
              ' + + return '
              ' + (data.label ? '' + data.label + '' : '') + '
              ' + that.$reader_form_element(data.group, index) + - (help ? ('
              ' + help.list.join('
              ') + '
              ') : '') + + (help ? ('
              ' + help.list.join('
              ') + '
              ') : '') + '
              ' + '
              '; }, @@ -1288,97 +1290,97 @@ var bt_tools = { * @return: viod */ $reader_form_element:function(data,index){ - var that = this,config = [],html = '',event_list = {}; - if(!Array.isArray(data)) data = [data]; - $.each(data,function(key,item){ - var style = that.$reader_style(item.style) + _that.$verify(item.width,'width','style'), - attribute = that.$verify_group(item,['name','value','placeholder','disabled','readonly','autofocus','autocomplete','min','max']), - event_group = that.$create_event_config(item), - eventName = ''; - html += item.label?''+ item.label +'':''; - if(typeof item['name'] !== "undefined") event_list[item.name] = event_group; - switch(item.type){ - case 'text': // 文本选择 - case 'checkbox': // 复选框 - case 'password': // 密码 - case 'radio': // 单选框 - case 'number': // 数字 - var _event = 'event_'+ item.name +'_'+ that.random,is_checkbox = item.type === 'checkbox'?true:false; - if(item.type === 'radio'){ - $.each(item.label_tips,function(index,items){ - if(item.block) html += '
              '; - html += ''; - html += ''; - if(item.block) html += '
              '; - }) - }else{ - if(item.block) html += '
              '; - html += ''; - if(item.type == 'checkbox') html += ''; - if(item.block) html += '
              '; - that.event_list[_event] = {'click':{event:item.event}} - } - if(item.icon){ - html += ''; - event_list[item.name+'_icon'] = {'click':{type:'select_path',config:item}}; - } - break; - case 'textarea': - html += ''; - $.each(['blur','focus','input'],function(index,items){ - if(item.tips){ - var added = null; - switch(items){ - case 'blur': - added = function(ev,item){ - if($(this).val() === '') $(this).next().show(); - layer.close(item.tips.loadT); - } - break; - case 'focus': - added = function(ev,item){ - $(this).next().hide(); - item.tips.loadT = layer.tips(tips,$(this),{tips:[1,'#20a53a'],time:0,area:$(this).width()}) - } - break; - } - } - event_list[item.name][items]?(event_list[item.name][items]['added'] = added):(event_list[item.name][items] = {type:item.type,cust:false,event:item[items],added:added}); - }); - if(item.tips){ - var tips = ''; - if(typeof item.tips.list === "undefined"){ - tips = item.tips.text; - }else{ - tips = item.tips.list.join('
              '); - } - html += '
              '+ tips +'
              '; - event_list[item.name+'_tips'] = {'click':{type:'textarea_tips',config:item}}; - } - break; - case 'select': - html += that.$reader_select(item,style,attribute,index); - that.event_list['custom_select'] = {'click':{type:'custom_select',children:'.bt_select_value'}}; - that.event_list['custom_select_item'] = {'click':{type:'custom_select_item',children:'li.item'}}; - break; - case 'link': - eventName = 'event_' + bt.get_random(6); - html += ''+ item.title +''; - that.event_list[eventName] = {'click':{type:'link_event',event:item.event}} - break; - case 'help': - var _html = ''; - $.each(item.list,function(index,items){ - _html += '
            • '+items +'
            • '; - }) - html += '
                '+ _html +'
              '; - break; - } - that.form_config[item.name] = item; - }); - $.extend(that.event_list,event_list); - return html; - }, + var that = this,config = [],html = '',event_list = {}; + if(!Array.isArray(data)) data = [data]; + $.each(data,function(key,item){ + var style = that.$reader_style(item.style) + _that.$verify(item.width,'width','style'), + attribute = that.$verify_group(item,['name','value','placeholder','disabled','readonly','autofocus','autocomplete','min','max']), + event_group = that.$create_event_config(item), + eventName = ''; + html += item.label?''+ item.label +'':''; + if(typeof item['name'] !== "undefined") event_list[item.name] = event_group; + switch(item.type){ + case 'text': // 文本选择 + case 'checkbox': // 复选框 + case 'password': // 密码 + case 'radio': // 单选框 + case 'number': // 数字 + var _event = 'event_'+ item.name +'_'+ that.random,is_checkbox = item.type === 'checkbox'?true:false; + if(item.type === 'radio'){ + $.each(item.label_tips,function(index,items){ + if(item.block) html += '
              '; + html += ''; + html += ''; + if(item.block) html += '
              '; + }) + }else{ + if(item.block) html += '
              '; + html += ''; + if(item.type == 'checkbox') html += ''; + if(item.block) html += '
              '; + that.event_list[_event] = {'click':{event:item.event}} + } + if(item.icon){ + html += ''; + event_list[item.name+'_icon'] = {'click':{type:'select_path',config:item}}; + } + break; + case 'textarea': + html += ''; + $.each(['blur','focus','input'],function(index,items){ + if(item.tips){ + var added = null; + switch(items){ + case 'blur': + added = function(ev,item){ + if($(this).val() === '') $(this).next().show(); + layer.close(item.tips.loadT); + } + break; + case 'focus': + added = function(ev,item){ + $(this).next().hide(); + item.tips.loadT = layer.tips(tips,$(this),{tips:[1,'#20a53a'],time:0,area:$(this).width()}) + } + break; + } + } + event_list[item.name][items]?(event_list[item.name][items]['added'] = added):(event_list[item.name][items] = {type:item.type,cust:false,event:item[items],added:added}); + }); + if(item.tips){ + var tips = ''; + if(typeof item.tips.list === "undefined"){ + tips = item.tips.text; + }else{ + tips = item.tips.list.join('
              '); + } + html += '
              '+ tips +'
              '; + event_list[item.name+'_tips'] = {'click':{type:'textarea_tips',config:item}}; + } + break; + case 'select': + html += that.$reader_select(item,style,attribute,index); + that.event_list['custom_select'] = {'click':{type:'custom_select',children:'.bt_select_value'}}; + that.event_list['custom_select_item'] = {'click':{type:'custom_select_item',children:'li.item'}}; + break; + case 'link': + eventName = 'event_' + bt.get_random(6); + html += ''+ item.title +''; + that.event_list[eventName] = {'click':{type:'link_event',event:item.event}} + break; + case 'help': + var _html = ''; + $.each(item.list,function(index,items){ + _html += '
            • '+items +'
            • '; + }) + html += '
                '+ _html +'
              '; + break; + } + that.form_config[item.name] = item; + }); + $.extend(that.event_list,event_list); + return html; + }, /** * @description 创建事件配置 * @param {object} item 行内配置 @@ -1456,7 +1458,7 @@ var bt_tools = { option += ''; }); if (!active.title && Array.isArray(item.list)) active = item.list[0]; - return '
              ' + + return '
              ' + '' + (active.title || 'Getting data...') + '' + '
                ' + (list || '') + '
              ' + '' + (option || '') + '' + @@ -1552,7 +1554,7 @@ var bt_tools = { }else{ $(this).prev().removeClass('active'); } - break; + break; } if (items.event) items.event.apply(this, [value,form, that, config, ev]); // 事件 if (items.added) items.added.apply(this, [ev,config,form]); @@ -1660,7 +1662,7 @@ var bt_tools = { }, /** * @description 验证form表单 - */ + */ $verify_form:function(){ var form_list = {},form = this.config.form,form_value = this.$get_form_value(),form_element = this.$get_form_element(true); for(var key = 0; key< form.length; key++){ @@ -1684,7 +1686,7 @@ var bt_tools = { * @description 提交内容,需要传入url * @param {Object|Function} param 附加参数或回调函数 * @param {Function} callback 回调 - */ + */ $submit: function (param,callback,tips) { var form = this.$verify_form(); if(typeof param === "function") tips = callback,callback = param,param = {}; @@ -1712,7 +1714,7 @@ var bt_tools = { * @description tab切换,支持三种模式 * @param {object} config * @return 当前实例对象 - */ + */ tab:function(config){ var _that = this; function ReaderTab(config){ @@ -1753,12 +1755,12 @@ var bt_tools = { _tab += ''+ item.title +''; _tab_con += '
              '+ (active?item.content:'') +'
              '; }); - that.element = $('
              '+ _tab +'
              '+ _tab_con +'
              '); + that.element = $('
              '+ _tab +'
              '+ _tab_con +'
              '); return that.element[0].outerHTML; }, /** * @description 渲染指定tab内容 - */ + */ $reader_find:function(){ }, @@ -1802,41 +1804,41 @@ var bt_tools = { * @description 弹窗方法,有默认的参数和重构的参数 * @param {object} config 和layer参数一致 * @require 当前关闭弹窗方法 - */ + */ open:function(config){ - var _config = {},layerT = null,form = null; - _config = $.extend({type: 1,area: '640px',closeBtn: 2,btn: ['Yes', 'No']},config); - if(typeof _config.content == "object"){ - var param = _config.content; - form = bt_tools.form(param); - _config.success = function(layero,indexs){ - form.$event_bind(); - if(typeof _config.init != "undefined") _config.init(layero,indexs); - } - _config.yes = function(indexs,layero){ - var form_val = form.$verify_form(); - if(!form_val) return false; - if(typeof config.yes != "undefined"){ - var yes = config.yes.apply(form,[form_val,indexs,layero]); - if(!yes) return false; - } - } - _config.content = form.$reader_content(); - } - layerT = layer.open(_config); - return { - close: function () { - layer.close(layerT); - }, - form:form - } + var _config = {},layerT = null,form = null; + _config = $.extend({type: 1,area: '640px',closeBtn: 2,btn: ['Yes', 'No']},config); + if(typeof _config.content == "object"){ + var param = _config.content; + form = bt_tools.form(param); + _config.success = function(layero,indexs){ + form.$event_bind(); + if(typeof _config.init != "undefined") _config.init(layero,indexs); + } + _config.yes = function(indexs,layero){ + var form_val = form.$verify_form(); + if(!form_val) return false; + if(typeof config.yes != "undefined"){ + var yes = config.yes.apply(form,[form_val,indexs,layero]); + if(!yes) return false; + } + } + _config.content = form.$reader_content(); + } + layerT = layer.open(_config); + return { + close: function () { + layer.close(layerT); + }, + form:form + } }, /** * @description 封装msg方法 * @param {object|string} param1 配置参数,请求方法参数 * @param {number} param2 图标ID * @require 当前关闭弹窗方法 - */ + */ msg:function(param1,param2){ var layerT = null,msg = '',config = {}; if(typeof param1 === "object"){ @@ -1859,7 +1861,7 @@ var bt_tools = { * @param {String} value 内容/值 * @param {String|Boolean} attr 属性 * @param {String} type 属性 - */ + */ $verify:function(value,attr,type){ if(!value) return ''; if(type === true) return value?' '+ attr:''; @@ -1877,31 +1879,31 @@ var bt_tools = { select_path:function(datas,callback,type,limit){ //if(typeof data === 'string') data = {path:data}; //if(typeof data === 'function') type = callback,callback = data,data = {path:bt.get_cookie('Path')}; - if(typeof type !== 'number') type = 1; - if(typeof limit !== 'number') limit = false; - bt.set_cookie('Path','/www/server/panel/BTPanel/static'); - var that = this, - select_file = { - type:type, - type_tips:type == 0?'目录':(type == 1?'文件':'目录或文件'), - type_limit:type == 0?'dir':(type == 1?'file':'all'), - select_list:[], - select_path:bt.get_cookie('Path') || (bt.os == 'Windows'?setup_path:'/www/wwwroot'), - select_config:{}, - scroll_width:0, - file_path: bt.get_cookie('Path'), - file_operating:[], - area : [window.innerWidth, window.innerHeight], - reader_view:function(){ - var _this = this; - this.scroll_width = select_file.getScrollbarWidth(); - layer.open({ - type:1, - title: datas.title || ('选择' + _this.type_tips), - shadeClose:false, - closeBtn: 2, - area:['650px','555px'], - content:'
              \ + if(typeof type !== 'number') type = 1; + if(typeof limit !== 'number') limit = false; + bt.set_cookie('Path','/www/server/panel/BTPanel/static'); + var that = this, + select_file = { + type:type, + type_tips:type == 0?'目录':(type == 1?'文件':'目录或文件'), + type_limit:type == 0?'dir':(type == 1?'file':'all'), + select_list:[], + select_path:bt.get_cookie('Path') || (bt.os == 'Windows'?setup_path:'/www/wwwroot'), + select_config:{}, + scroll_width:0, + file_path: bt.get_cookie('Path'), + file_operating:[], + area : [window.innerWidth, window.innerHeight], + reader_view:function(){ + var _this = this; + this.scroll_width = select_file.getScrollbarWidth(); + layer.open({ + type:1, + title: datas.title || ('选择' + _this.type_tips), + shadeClose:false, + closeBtn: 2, + area:['650px','555px'], + content:'
              \
              \
              \
              \ @@ -1956,1077 +1958,1077 @@ var bt_tools = {
              \
              \
              ', - success:function(){ - //_this.event_bind(); - _this.render_file_list(); - $('.select_list_thaed').css('right',_this.scroll_width+'px'); - } - }); - }, - /** - * @description 渲染文件列表 - * @param {object} data 配置参数,包含path路径、serarch搜索字段 - */ - render_file_list:function(data,callback){ - var mount_html = '',dir_html = '',_this = this,datas = {path:this.select_path,sort:'type',disk:true}; - if(typeof data == "undefined") data = datas; - if(typeof data == "function") callback = data,data = datas; - _this.select_config = $.extend(datas,data); - that.$http('GetDir',_this.select_config,function(rdata){ - var disk_list = rdata.DISK,dir_list = $.merge(_this.data_reconstruction(rdata.DIR,'DIR') ,_this.data_reconstruction(rdata.FILES)); - _this.select_list = dir_list; - _this.render_path_list(); - $.each(disk_list,function(index,item){ - var name = (item.path == '/'?'根目录':item.path.indexOf(':/') > -1?('本地磁盘('+ item.path.match(/[A-Z]+/)[0])+ ':)':item.path) - mount_html += '
              '+ - ''+ - ''+ name +''+ - '
              '; - }); + success:function(){ + //_this.event_bind(); + _this.render_file_list(); + $('.select_list_thaed').css('right',_this.scroll_width+'px'); + } + }); + }, + /** + * @description 渲染文件列表 + * @param {object} data 配置参数,包含path路径、serarch搜索字段 + */ + render_file_list:function(data,callback){ + var mount_html = '',dir_html = '',_this = this,datas = {path:this.select_path,sort:'type',disk:true}; + if(typeof data == "undefined") data = datas; + if(typeof data == "function") callback = data,data = datas; + _this.select_config = $.extend(datas,data); + that.$http('GetDir',_this.select_config,function(rdata){ + var disk_list = rdata.DISK,dir_list = $.merge(_this.data_reconstruction(rdata.DIR,'DIR') ,_this.data_reconstruction(rdata.FILES)); + _this.select_list = dir_list; + _this.render_path_list(); + $.each(disk_list,function(index,item){ + var name = (item.path == '/'?'根目录':item.path.indexOf(':/') > -1?('本地磁盘('+ item.path.match(/[A-Z]+/)[0])+ ':)':item.path) + mount_html += '
              '+ + ''+ + ''+ name +''+ + '
              '; + }); - $.each(dir_list,function(index,item){ - if((_this.type == 0) && item.type != _this.type_limit) return true; - var mtime = bt.format_data(item.mtime), - type = (item.type == 'dir'?'文件夹':'文件'); - dir_html += '\ + $.each(dir_list,function(index,item){ + if((_this.type == 0) && item.type != _this.type_limit) return true; + var mtime = bt.format_data(item.mtime), + type = (item.type == 'dir'?'文件夹':'文件'); + dir_html += '\ '+ item.filename +'\ '+ mtime +'\ '+ (item.type == 'dir'?'文件夹':'文件') +'\ '; + }); + $('#select_mount_list').html(mount_html); + $('#select_dir_list').html(dir_html); + if(callback) callback(rdata); }); - $('#select_mount_list').html(mount_html); - $('#select_dir_list').html(dir_html); - if(callback) callback(rdata); - }); - }, - /** - * @description 渲染路径列表 - * @param {Function} callback 回调函数 - * @return void - */ + }, + /** + * @description 渲染路径列表 + * @param {Function} callback 回调函数 + * @return void + */ - data_reconstruction:function(data,type,callback){ - if(data.length < 1) return []; - var _array = []; - $.each(data,function(index,item){ - var itemD = item.split(";"),fileMsg ='',fileN = itemD[0].split('.'),extName = fileN[fileN.length - 1]; - switch(itemD[0]) { - case '.user.ini': - fileMsg = 'PS: PHP用户配置文件(防跨站)!'; - break; - case '.htaccess': - fileMsg = 'PS: Apache用户配置文件(伪静态)'; - break; - case 'swap': - fileMsg = 'PS: 宝塔默认设置的SWAP交换分区文件'; - break; - } - if(itemD[0].indexOf('Recycle_bin') != -1) fileMsg = 'PS: 回收站目录,勿动!'; - if(itemD[0].indexOf('.upload.tmp') != -1) fileMsg = 'PS: 宝塔文件上传临时文件,重新上传从断点续传,可删除'; - _array.push({ - caret: itemD[8] == '1'?true:false, //是否收藏 - down_id: itemD[9], //是否分享 分享id - ext: (type == 'DIR'?'':extName), //文件类型 - filename: itemD[0], //文件名称 - mtime: itemD[2], //时间 - ps: fileMsg || itemD[10], //备注 - size: itemD[1], //文件大小 - type: type == 'DIR'?'dir':'file', //文件类型 - user: itemD[3], //用户权限 - root_level:itemD[4] //所有者 - // accept: 666, - //composer: 0, - // link: "", - // shell: false, - }) + data_reconstruction:function(data,type,callback){ + if(data.length < 1) return []; + var _array = []; + $.each(data,function(index,item){ + var itemD = item.split(";"),fileMsg ='',fileN = itemD[0].split('.'),extName = fileN[fileN.length - 1]; + switch(itemD[0]) { + case '.user.ini': + fileMsg = 'PS: PHP用户配置文件(防跨站)!'; + break; + case '.htaccess': + fileMsg = 'PS: Apache用户配置文件(伪静态)'; + break; + case 'swap': + fileMsg = 'PS: 宝塔默认设置的SWAP交换分区文件'; + break; + } + if(itemD[0].indexOf('Recycle_bin') != -1) fileMsg = 'PS: 回收站目录,勿动!'; + if(itemD[0].indexOf('.upload.tmp') != -1) fileMsg = 'PS: 宝塔文件上传临时文件,重新上传从断点续传,可删除'; + _array.push({ + caret: itemD[8] == '1'?true:false, //是否收藏 + down_id: itemD[9], //是否分享 分享id + ext: (type == 'DIR'?'':extName), //文件类型 + filename: itemD[0], //文件名称 + mtime: itemD[2], //时间 + ps: fileMsg || itemD[10], //备注 + size: itemD[1], //文件大小 + type: type == 'DIR'?'dir':'file', //文件类型 + user: itemD[3], //用户权限 + root_level:itemD[4] //所有者 + // accept: 666, + //composer: 0, + // link: "", + // shell: false, + }) - }) - return _array; - }, - render_path_list: function (callback){ - var _this = this,html = '
              ', path_before = '',dir_list = this.file_path.split("/").splice(1),first_dir = this.file_path.split("/")[0]; - if(bt.os === 'Windows'){ - if(dir_list.length == 0) dir_list = []; - dir_list.unshift('本地磁盘('+ first_dir +')'); - }else{ - if(this.file_path == '/') dir_list = []; - dir_list.unshift('根目录'); - } - for(var i = 0; i < dir_list.length; i++){ - path_before += '/' + dir_list[i]; - if (i == 0) path_before = ''; - html += '
              \ + }) + return _array; + }, + render_path_list: function (callback){ + var _this = this,html = '
              ', path_before = '',dir_list = this.file_path.split("/").splice(1),first_dir = this.file_path.split("/")[0]; + if(bt.os === 'Windows'){ + if(dir_list.length == 0) dir_list = []; + dir_list.unshift('本地磁盘('+ first_dir +')'); + }else{ + if(this.file_path == '/') dir_list = []; + dir_list.unshift('根目录'); + } + for(var i = 0; i < dir_list.length; i++){ + path_before += '/' + dir_list[i]; + if (i == 0) path_before = ''; + html += '
              \ ' + dir_list[i] + '\ \ \
              '; - } - $('.path_input').val('').attr('data-path',this.file_path); - var file_dir_view = $('.file_path_input .file_dir_view'); - file_dir_view.html(html); - file_dir_view.attr('data-width',file_dir_view.width()); - _this.set_dir_view_resize(); - }, + } + $('.path_input').val('').attr('data-path',this.file_path); + var file_dir_view = $('.file_path_input .file_dir_view'); + file_dir_view.html(html); + file_dir_view.attr('data-width',file_dir_view.width()); + _this.set_dir_view_resize(); + }, - /** - * @description 设置标题宽度 - * @param {string} th_index 表头序列号 - * @param {string} style class样式 - */ - set_select_width:function(th_index,style){ - var _this = this,className = '.select_dir_list tbody td:nth-child('+ (th_index+1) +')>span,.select_dir_list thead th:nth-child('+ (th_index+1) +')>span',style_index = $('#th-index-'+th_index); - if(style_index.length > 0){ - style_index.html(className +'{'+ style +'}'); - }else{ - $('#select_file_style').append(''); - } - }, - /** - * @description 样式转换文件样式 - * @param {string} style 样式 - */ - cut_style_object:function(style){ - var object = {},arry = style.split(';'); - console.log(arry); - return object; - }, - /** - * @description 获取滚动条宽度 - */ - getScrollbarWidth:function(){ - var odiv = document.createElement('div'),//创建一个div - styles = { - width: '100px', - height: '100px', - overflowY: 'scroll'//让他有滚动条 - }, i, scrollbarWidth; - for (i in styles) odiv.style[i] = styles[i]; - document.body.appendChild(odiv);//把div添加到body中 - scrollbarWidth = odiv.offsetWidth - odiv.clientWidth;//相减 - odiv.remove();//移除创建的div - return scrollbarWidth;//返回滚动条宽度 - }, - set_dir_view_resize:function(){ - var file_path_input = $('.file_path_input'),file_dir_view = $('.file_path_input .file_dir_view'),_path_width = file_dir_view.attr('data-width'),file_item_hide = null; - if(_path_width){ - parseInt(_path_width); - }else{ - _path_width = file_dir_view.width(); - file_dir_view.attr('data-width',_path_width); - } - if(file_dir_view.width() - _path_width < 90){ - var width = 0; - $($('.file_path_input .file_dir_view .file_dir_item').toArray().reverse()).each(function(){ - var item_width = 0; - if(!$(this).attr('data-width')){ - $(this).attr('data-width',$(this).width()); - item_width = $(this).width(); - }else{ - item_width = parseInt($(this).attr('data-width')); - } - width += item_width; - if((file_path_input.width() - width) <= 90){ - $(this).addClass('hide'); - }else{ - $(this).removeClass('hide'); - } - }); - } - var file_item_hide = file_dir_view.children('.file_dir_item.hide').clone(true); - if(file_dir_view.children('.file_dir_item.hide').length == 0){ - file_path_input.removeClass('active').find('.file_dir_omit').addClass('hide'); - }else{ - file_item_hide.each(function(){ - if($(this).find('.glyphicon-hdd').length == 0){ - $(this).find('.file_dir').before(''); - } - }); - file_path_input.addClass('active').find('.file_dir_omit').removeClass('hide'); - file_path_input.find('.file_dir_omit .nav_down_list').empty().append(file_item_hide); - file_path_input.find('.file_dir_omit .nav_down_list .file_dir_item').removeClass('hide'); - } - }, - /** - * @description 渲染文件列表 - * @param {Object} data 参数对象,例如分页、显示数量、排序,不传参数使用默认或继承参数 - * @param {Function} callback 回调函数 - * @return void - */ - reader_file_list:function (data, callback){ - var _this = this,select_page_num = '',next_path = ''; - if(typeof data === "function") callback = data,data = {is_operating:false}; - if(typeof data === "undefined") data = {is_operating:false}; - if(limit){ - layer.msg('只能在该目录下操作',{icon:2}); - return false; - } - this.loadT = bt.load('正在获取文件列表,请稍候...'); - this.file_images_list = []; - _this.get_dir_list(data,function(res){ - _this.loadT.close(); - _this.file_list = $.merge(_this.data_reconstruction(res.DIR,'DIR'), _this.data_reconstruction(res.FILES)); - _this.file_path = res.PATH; - _this.is_recycle = res.FILE_RECYCLE; - _this.file_store_list = res.STORE; - bt.set_cookie('Path',res.PATH); + /** + * @description 设置标题宽度 + * @param {string} th_index 表头序列号 + * @param {string} style class样式 + */ + set_select_width:function(th_index,style){ + var _this = this,className = '.select_dir_list tbody td:nth-child('+ (th_index+1) +')>span,.select_dir_list thead th:nth-child('+ (th_index+1) +')>span',style_index = $('#th-index-'+th_index); + if(style_index.length > 0){ + style_index.html(className +'{'+ style +'}'); + }else{ + $('#select_file_style').append(''); + } + }, + /** + * @description 样式转换文件样式 + * @param {string} style 样式 + */ + cut_style_object:function(style){ + var object = {},arry = style.split(';'); + console.log(arry); + return object; + }, + /** + * @description 获取滚动条宽度 + */ + getScrollbarWidth:function(){ + var odiv = document.createElement('div'),//创建一个div + styles = { + width: '100px', + height: '100px', + overflowY: 'scroll'//让他有滚动条 + }, i, scrollbarWidth; + for (i in styles) odiv.style[i] = styles[i]; + document.body.appendChild(odiv);//把div添加到body中 + scrollbarWidth = odiv.offsetWidth - odiv.clientWidth;//相减 + odiv.remove();//移除创建的div + return scrollbarWidth;//返回滚动条宽度 + }, + set_dir_view_resize:function(){ + var file_path_input = $('.file_path_input'),file_dir_view = $('.file_path_input .file_dir_view'),_path_width = file_dir_view.attr('data-width'),file_item_hide = null; + if(_path_width){ + parseInt(_path_width); + }else{ + _path_width = file_dir_view.width(); + file_dir_view.attr('data-width',_path_width); + } + if(file_dir_view.width() - _path_width < 90){ + var width = 0; + $($('.file_path_input .file_dir_view .file_dir_item').toArray().reverse()).each(function(){ + var item_width = 0; + if(!$(this).attr('data-width')){ + $(this).attr('data-width',$(this).width()); + item_width = $(this).width(); + }else{ + item_width = parseInt($(this).attr('data-width')); + } + width += item_width; + if((file_path_input.width() - width) <= 90){ + $(this).addClass('hide'); + }else{ + $(this).removeClass('hide'); + } + }); + } + var file_item_hide = file_dir_view.children('.file_dir_item.hide').clone(true); + if(file_dir_view.children('.file_dir_item.hide').length == 0){ + file_path_input.removeClass('active').find('.file_dir_omit').addClass('hide'); + }else{ + file_item_hide.each(function(){ + if($(this).find('.glyphicon-hdd').length == 0){ + $(this).find('.file_dir').before(''); + } + }); + file_path_input.addClass('active').find('.file_dir_omit').removeClass('hide'); + file_path_input.find('.file_dir_omit .nav_down_list').empty().append(file_item_hide); + file_path_input.find('.file_dir_omit .nav_down_list .file_dir_item').removeClass('hide'); + } + }, + /** + * @description 渲染文件列表 + * @param {Object} data 参数对象,例如分页、显示数量、排序,不传参数使用默认或继承参数 + * @param {Function} callback 回调函数 + * @return void + */ + reader_file_list:function (data, callback){ + var _this = this,select_page_num = '',next_path = ''; + if(typeof data === "function") callback = data,data = {is_operating:false}; + if(typeof data === "undefined") data = {is_operating:false}; + if(limit){ + layer.msg('只能在该目录下操作',{icon:2}); + return false; + } + this.loadT = bt.load('正在获取文件列表,请稍候...'); + this.file_images_list = []; + _this.get_dir_list(data,function(res){ + _this.loadT.close(); + _this.file_list = $.merge(_this.data_reconstruction(res.DIR,'DIR'), _this.data_reconstruction(res.FILES)); + _this.file_path = res.PATH; + _this.is_recycle = res.FILE_RECYCLE; + _this.file_store_list = res.STORE; + bt.set_cookie('Path',res.PATH); - var mount_html = '',dir_html = '', - disk_list = res.DISK, - dir_list = _this.file_list; - _this.select_list = _this.file_list; - _this.render_path_list(); - $.each(disk_list,function(index,item){ - var name = (item.path == '/'?'根目录':item.path.indexOf(':/') > -1?('本地磁盘('+ item.path.match(/[A-Z]+/)[0])+ ':)':item.path) - mount_html += '
              '+ - ''+ - ''+ name +''+ - '
              '; - }); + var mount_html = '',dir_html = '', + disk_list = res.DISK, + dir_list = _this.file_list; + _this.select_list = _this.file_list; + _this.render_path_list(); + $.each(disk_list,function(index,item){ + var name = (item.path == '/'?'根目录':item.path.indexOf(':/') > -1?('本地磁盘('+ item.path.match(/[A-Z]+/)[0])+ ':)':item.path) + mount_html += '
              '+ + ''+ + ''+ name +''+ + '
              '; + }); - $.each(dir_list,function(index,item){ - if((_this.type == 0) && item.type != _this.type_limit) return true; - var mtime = bt.format_data(item.mtime), - type = (item.type == 'dir'?'文件夹':'文件'); - dir_html += '\ + $.each(dir_list,function(index,item){ + if((_this.type == 0) && item.type != _this.type_limit) return true; + var mtime = bt.format_data(item.mtime), + type = (item.type == 'dir'?'文件夹':'文件'); + dir_html += '\ '+ item.filename +'\ '+ mtime +'\ '+ (item.type == 'dir'?'文件夹':'文件') +'\ '; + }); + $('#select_mount_list').html(mount_html); + $('#select_dir_list').html(dir_html); + var _i = res.PATH.lastIndexOf("\/"), + index_file = res.PATH.substring(_i + 1, res.PATH.length); + //if(_this.type_limit != 'file') $('[name="select_name"].file_directory').val(index_file); + if(callback) callback(rdata); }); - $('#select_mount_list').html(mount_html); - $('#select_dir_list').html(dir_html); - var _i = res.PATH.lastIndexOf("\/"), - index_file = res.PATH.substring(_i + 1, res.PATH.length); - //if(_this.type_limit != 'file') $('[name="select_name"].file_directory').val(index_file); - if(callback) callback(rdata); - }); - }, + }, - /** - * @description 渲染文件列表内容 - * @param {Object} data 文件列表数据 - * @param {Function} callback 回调函数 - * @return void - */ - reader_file_list_content:function(data,callback){ - var _html = '',_this = this,is_dir_num = 0; - $.each(data,function(index,item){ - var _title = item.filename + item.ps; - _this.file_list[index] = item = _this.$file_data_dispose(item); - _this.file_list[index]['only_index'] = index; - if(item.filename.indexOf('Recycle_bin')) _tips = 'PS: 回收站目录,勿动!'; - if(_title.length > 20) _title = _title.substring(0, 20) + '...'; - if(bt.check_chinese(_title) && _title.length > 10) _title = _title.substring(0, 10) + '...' - _html += '
              '+ - '
              '+ - '
              '+ - '
              '+ - ''+ item.filename + item.ps +''+ (item.caret?'':'') + (item.down_id?'':'') + - '
              '+ - '
              '+ item.type_tips +'
              '+ - '
              '+ (item.type == 'dir'?'点击计算':bt.format_size(item.size)) +'
              '+ - '
              ' + bt.format_data(item.mtime) + '
              '+ - '
              '; - if(item.type == 'dir') is_dir_num ++; // 获取目录数量 - if(item.ispreview){ // 获取图片数量 - _this.file_images_list.push(item.path); - if(typeof item.images_id) item.images_id = _this.file_images_list.length - 1; - } + /** + * @description 渲染文件列表内容 + * @param {Object} data 文件列表数据 + * @param {Function} callback 回调函数 + * @return void + */ + reader_file_list_content:function(data,callback){ + var _html = '',_this = this,is_dir_num = 0; + $.each(data,function(index,item){ + var _title = item.filename + item.ps; + _this.file_list[index] = item = _this.$file_data_dispose(item); + _this.file_list[index]['only_index'] = index; + if(item.filename.indexOf('Recycle_bin')) _tips = 'PS: 回收站目录,勿动!'; + if(_title.length > 20) _title = _title.substring(0, 20) + '...'; + if(bt.check_chinese(_title) && _title.length > 10) _title = _title.substring(0, 10) + '...' + _html += '
              '+ + '
              '+ + '
              '+ + '
              '+ + ''+ item.filename + item.ps +''+ (item.caret?'':'') + (item.down_id?'':'') + + '
              '+ + '
              '+ item.type_tips +'
              '+ + '
              '+ (item.type == 'dir'?'点击计算':bt.format_size(item.size)) +'
              '+ + '
              ' + bt.format_data(item.mtime) + '
              '+ + '
              '; + if(item.type == 'dir') is_dir_num ++; // 获取目录数量 + if(item.ispreview){ // 获取图片数量 + _this.file_images_list.push(item.path); + if(typeof item.images_id) item.images_id = _this.file_images_list.length - 1; + } - }); - $('.file_list_content').html(_html); - if(callback) callback({is_dir_num:is_dir_num}) - }, - /** - * @description 文件数据处理 - * @param {Object} data 配置参数 - * @return {Object} 重新生成的文件对象 - */ - $file_data_dispose:function(data){ - var models = {languages:null,model:null}; - //if(data.type !== 'dir') models = this.$get_file_model(data); - return $.extend(data,{ - only_id:bt.get_random(10), // 文件唯一ID - type_tips:data.type === 'dir'?'文件夹':this.ext_type_tips(data.ext), // 文件类型描述 - open_type:this.determine_file_type(data.ext), // 打开类型 - languages:models.languages, // 文件语言 - path:data.path || this.path_resolve(this.file_path,data.filename), // 文件全路径 - model:models.model, // 语言模型 - }); - }, - /** - * @description 文件路径合并 - * @param {String} paths 旧路径 - * @param {String} param 新路径 - * @return {String} 新的路径 - */ - path_resolve:function(paths, param){ - var path = '',split = ''; - if(!Array.isArray(param)) param = [param]; - paths.replace(/([\/|\/]*)$/,function($1){ - split = $1; - return 'www'; - }); - $.each(param,function(index,item){ - path += '/' + item; - }); - return paths + path; - }, - /** - * @description 获取文件语言配置模型 - * @param {Object} data 当前文件的数据对象 - * @return {Object} 当前语言配置模型 - */ - $get_file_model:function(data){ - var config = this.vscode_editor.config; - for(languages in config.supportedModes){ - var item = config.supportedModes[languages]; - for(var j=0;j'+ - ''+ - ''+(item.path == '/'?'根目录':item.path)+' ('+ item.size[2] +')'+ - '
              '; - }); - $('.mount_disk_list').html(html); - }); - }, - /** - * @description 文件类型判断,或返回格式类型(不传入type) - * @param {String} ext - * @param {String} type - * @return {Boolean|Object} 返回类型或类型是否支持 - */ - determine_file_type:function(ext,type){ - var config = { - images:['jpg','jpeg','png','bmp','gif','tiff','ico'], - compress:['zip','rar','gz','war','tgz'], - video:['mp4', 'mpeg', 'mpg', 'mov', 'avi', 'webm', 'mkv'], - ont_text:['iso','xlsx','xsl','doc','docx','tiff','exe','so','7z','bz','dmg','apk'] - },returnVal = false; - if(type != undefined){ - if(type == 'text'){ - $.each(config,function(key,item){ - $.each(item,function(index,items){ - if(items == ext){ - returnVal = true; - return false; - } - }) - }); - returnVal = !returnVal - }else{ - if(typeof config[type] == "undefined") return false; - $.each(config[type],function(key,item){ - if(item == ext){ - returnVal = true; - return false; - } - }); - } - }else{ - $.each(config,function(key,item){ - $.each(item,function(index,items){ - if(items == ext){ - returnVal = key; - return false; - } - }) - }); - if(typeof returnVal == "boolean") returnVal = 'text'; - } - return returnVal; - }, - - /** - * @description 渲染右键鼠标菜单 - * @param {Object} ev 事件event对象 - * @param {Object} el 事件对象DOM - * @return void - */ - render_file_groud_menu: function (ev,el){ - var _this = this,index = $(el).data('index'),data = _this.file_list[index],config_group = [['open','打开'],['split',''],['download','下载'],['share','分享目录/文件'],['cancel_share','取消分享'],['favorites','收藏目录/文件'],['cancel_favorites','取消收藏'],['split',''],['dir_kill','目录查杀'],['authority','权限'],['split',''],['copy','复制'],['shear','剪切'],['rename','重命名'],['del','删除'],['split',''],['killing','创建压缩',[['gzip','tar.gz (推荐)'],['zip','zip (通用格式)'],['rar','rar (中文兼容较好)']]],['unzip','解压',[['local','解压到当前'],['folad','解压到当前']]]],compression = ['zip','rar','gz','war','tgz','bz2'],offsetNum = 0; - if(data.type == 'dir'){ // 判断是否为目录,目录不可下载 - config_group.splice(2,1); - offsetNum ++; - } - if(data.down_id !== 0){ //判断是否分享 - config_group.splice(3-offsetNum,1); - offsetNum ++; - }else{ - config_group.splice(4-offsetNum,1); - config_group[3-offsetNum][1] = (data.type == 'dir'?'分享目录':'分享文件'); - offsetNum ++; - } - if(data.caret !== false){ // 判断是否收藏 - config_group.splice((5-offsetNum),1); - offsetNum ++; - }else{ - config_group.splice((6-offsetNum),1); - config_group[5-offsetNum][1] = (data.type == 'dir'?'收藏目录':'收藏文件'); - offsetNum ++; - } - if(data.ext != 'php' && data.type != 'dir'){ // 判断是否为php,非php文件(排除目录)无法扫描 - config_group.splice((8-offsetNum),1); - offsetNum ++; - } - var num = 0; - $.each(compression,function(index,item){ - if(item == data.ext) num ++; - }); - if(num == 0){ - config_group.splice((17-offsetNum),1); - offsetNum ++; - } - _this.reader_menu_list({el:$('.selection_right_menu'),ev:ev,data:data,list:config_group}); - }, - - /** - * @description 渲染右键全局菜单 - * @param {Object} ev 事件event对象 - * @param {Object} el 事件对象DOM - * @return void - */ - render_file_all_menu:function (ev,el) { - var _this = this,config_group = [['refresh','刷新'],['split',''],['upload','上传'],['create','新建文件夹/文件',[['create_dir','新建文件夹'],['create_files','新建文件']]],['split',''],['paste','粘贴']],offsetNum = 0; - if(!bt.get_storage('session','copy_path')){ - config_group.splice(5,1); - offsetNum ++; - } - _this.reader_menu_list({el:$('.selection_right_menu'),ev:ev,data:{},list:config_group}); - }, - get_dir_list:function(data, callback,is_tips) { - var _this = this; - if(typeof callback === "boolean") is_tips = callback,callback = null; - that.$http('GetDir',$.extend({ - disk:true, - path:_this.file_path, - sort:bt.get_cookie('files_sort') || 'type', - },data),callback,is_tips); - }, - /** - * @description 返回上一层目录地址 - * @param {String} path 当前路径 - * @returns 返回上一层地址 - */ - retrun_prev_path:function(path){ - var dir_list = path.split('/'); - dir_list.splice(dir_list.length - 1); - return dir_list.join('/'); - }, - - /** - * @description 渲染菜单列表 - * @param {Object} config 菜单配置列表和数据 - * @returns void - */ - reader_menu_list:function(config){ - var _this = this,el = config.el.find('ul'),el_height = el.height(),el_width = el.width(),left = config.ev.clientX - ((this.area[0] - config.ev.clientX) < el_width?el_width:0); - el.empty(); - $.each(config.list,function(index,item){ - var $children = null,$children_list = null; - if(item[0] == 'split'){ - el.append('
            • '); - }else{ - if(Array.isArray(item[2])){ - $children = $('
                '); - $children_list = $children.find('.set_group'); - $.each(item[2],function(indexs,items) { - $children_list.append($('
              • '+ items[1] +'
              • ').on('click',{type:items[0],data:config.data},function(ev){ - _this.file_groud_event($.extend(ev.data.data,{ - open:ev.data.type, - index:parseInt($(config.ev.currentTarget).data('index')), - element:config.ev.currentTarget, - type_tips:item.type?'文件夹':'文件' - })); - config.el.removeAttr('style'); - ev.stopPropagation(); - ev.preventDefault(); - })) - }); - } - el.append($('
              • '+ item[1] +'
              • ').append($children).on('click',{type:item[0],data:config.data},function(ev){ - _this.file_groud_event($.extend(ev.data.data,{ - open:ev.data.type, - index:parseInt($(config.ev.currentTarget).data('index')), - element:config.ev.currentTarget, - type_tips:item.type?'文件夹':'文件' - })); - config.el.removeAttr('style'); - ev.stopPropagation(); - ev.preventDefault(); - })); - } - }); - config.el.css({ - left: left, - top: config.ev.clientY - ((this.area[1] - config.ev.clientY) < el_height?el_height:0) - }).removeClass('left_menu right_menu').addClass(this.area[0] - (left + el_width) < 230?'left_menu':'right_menu'); - $(document).one('click',function(e){ - $(config.ev.currentTarget).removeClass('selected'); - config.el.removeAttr('style'); - e.stopPropagation(); - e.preventDefault(); - }); - }, - - - /** - * @description 返回后缀类型说明 - * @param {String} ext 后缀类型 - * @return {String} 文件类型 - */ - ext_type_tips:function(ext){ - var config = {ai:"Adobe Illustrator格式图形",apk:"安卓安装包",asp:"动态网页文件",bat:"批处理文件",bin:"二进制文件",bas:"BASIC源文件",bak:"备份文件",css:'CSS样式表',cad:"备份文件",cxx:"C++源代码文件",crt:"认证文件",cpp:"C++代码文件",conf:"配置文件",dat:"数据文件",der:"认证文件",doc:"Microsoft Office Word 97-2003 文档",docx:"Microsoft Office Word 2007 文档",exe:"程序应用",gif:"图形文件",go:"Go语言源文件",htm:"超文本文档",html:"超文本文档",ico:"图形文件",java:"Java源文件",jsp:"HTML网页",jpe:"图形文件",jpeg:"图形文件",jpg:"图形文件",log:"日志文件",link:"快捷方式文件",js:"Javascript源文件",mdb:"Microsoft Access数据库",mp3:"音频文件",mp4:"视频文件",mng:"多映像网络图形",msi:"Windows Installe安装文件包",png:"图形文件",py:"Python源代码",pyc:"Python字节码文件",pdf:"文档格式文件",ppt:"Microsoft Powerpoint 97-2003 幻灯片演示文稿",pptx:"Microsoft Powerpoint2007 幻灯片演示文稿",psd:"Adobe photoshop位图文件",pl:"Perl脚本语言",rar:"RAR压缩文件",reg:"注册表文件",sys:"系统文件",sql:"数据库文件",sh:"Shell脚本文件",txt:"文本格式",vb:"Visual Basic的一种宏语言",xml:"扩展标记语言",xls:"Microsoft Office Excel 97-2003 工作表",xlsx:"Microsoft Office Excel 2007 工作表",gz:"压缩文件",zip:"ZIP压缩文件",z:"","7z":"7Z压缩文件",json:'JSON文本'}; - return typeof config[ext] != "undefined"?config[ext]:(ext+'文件'); - }, - /** - * @description 事件绑定 - */ - event_bind: function(){ - var _this = this; - //单击选中文件 - $('#select_dir_list').on('click','tr[data-index]',function(e){ - var index = $(this).data('index'), - _type = $(this).attr('data-type'), - select_name_val = (_this.type_limit=='file' && _type == 'dir')?'':_this.select_list[index].filename; - $(this).addClass('active').siblings().removeClass('active'); - $('[name="select_name"]').val(select_name_val); - if (_type == 'file'){ - $('.file_path_views .forward_path span:eq(1)').addClass('active'); - }else{ - $('.file_path_views .forward_path span:eq(1)').removeClass('active'); - } - }); - $('.select_list_body').on('scroll',function(e){ - var top = $(this).scrollTop(),left = $(this).scrollLeft(); - if(top > 0){ - $('.select_list_shadow').show(); + }); + $('.file_list_content').html(_html); + if(callback) callback({is_dir_num:is_dir_num}) + }, + /** + * @description 文件数据处理 + * @param {Object} data 配置参数 + * @return {Object} 重新生成的文件对象 + */ + $file_data_dispose:function(data){ + var models = {languages:null,model:null}; + //if(data.type !== 'dir') models = this.$get_file_model(data); + return $.extend(data,{ + only_id:bt.get_random(10), // 文件唯一ID + type_tips:data.type === 'dir'?'文件夹':this.ext_type_tips(data.ext), // 文件类型描述 + open_type:this.determine_file_type(data.ext), // 打开类型 + languages:models.languages, // 文件语言 + path:data.path || this.path_resolve(this.file_path,data.filename), // 文件全路径 + model:models.model, // 语言模型 + }); + }, + /** + * @description 文件路径合并 + * @param {String} paths 旧路径 + * @param {String} param 新路径 + * @return {String} 新的路径 + */ + path_resolve:function(paths, param){ + var path = '',split = ''; + if(!Array.isArray(param)) param = [param]; + paths.replace(/([\/|\/]*)$/,function($1){ + split = $1; + return 'www'; + }); + $.each(param,function(index,item){ + path += '/' + item; + }); + return paths + path; + }, + /** + * @description 获取文件语言配置模型 + * @param {Object} data 当前文件的数据对象 + * @return {Object} 当前语言配置模型 + */ + $get_file_model:function(data){ + var config = this.vscode_editor.config; + for(languages in config.supportedModes){ + var item = config.supportedModes[languages]; + for(var j=0;j'+ + ''+ + ''+(item.path == '/'?'根目录':item.path)+' ('+ item.size[2] +')'+ + '
                '; + }); + $('.mount_disk_list').html(html); + }); + }, + /** + * @description 文件类型判断,或返回格式类型(不传入type) + * @param {String} ext + * @param {String} type + * @return {Boolean|Object} 返回类型或类型是否支持 + */ + determine_file_type:function(ext,type){ + var config = { + images:['jpg','jpeg','png','bmp','gif','tiff','ico'], + compress:['zip','rar','gz','war','tgz'], + video:['mp4', 'mpeg', 'mpg', 'mov', 'avi', 'webm', 'mkv'], + ont_text:['iso','xlsx','xsl','doc','docx','tiff','exe','so','7z','bz','dmg','apk'] + },returnVal = false; + if(type != undefined){ + if(type == 'text'){ + $.each(config,function(key,item){ + $.each(item,function(index,items){ + if(items == ext){ + returnVal = true; + return false; + } + }) + }); + returnVal = !returnVal + }else{ + if(typeof config[type] == "undefined") return false; + $.each(config[type],function(key,item){ + if(item == ext){ + returnVal = true; + return false; + } + }); + } }else{ - $('.select_list_shadow').hide(); + $.each(config,function(key,item){ + $.each(item,function(index,items){ + if(items == ext){ + returnVal = key; + return false; + } + }) + }); + if(typeof returnVal == "boolean") returnVal = 'text'; } - if(left >= 0){ - $('.select_list_thaed').css('left',(4-left ) +'px'); + return returnVal; + }, + + /** + * @description 渲染右键鼠标菜单 + * @param {Object} ev 事件event对象 + * @param {Object} el 事件对象DOM + * @return void + */ + render_file_groud_menu: function (ev,el){ + var _this = this,index = $(el).data('index'),data = _this.file_list[index],config_group = [['open','打开'],['split',''],['download','下载'],['share','分享目录/文件'],['cancel_share','取消分享'],['favorites','收藏目录/文件'],['cancel_favorites','取消收藏'],['split',''],['dir_kill','目录查杀'],['authority','权限'],['split',''],['copy','复制'],['shear','剪切'],['rename','重命名'],['del','删除'],['split',''],['killing','创建压缩',[['gzip','tar.gz (推荐)'],['zip','zip (通用格式)'],['rar','rar (中文兼容较好)']]],['unzip','解压',[['local','解压到当前'],['folad','解压到当前']]]],compression = ['zip','rar','gz','war','tgz','bz2'],offsetNum = 0; + if(data.type == 'dir'){ // 判断是否为目录,目录不可下载 + config_group.splice(2,1); + offsetNum ++; } - e.stopPropagation(); - e.preventDefault(); - }); - //文件刷新按钮 - $('.file_path_refresh').on('click',function(){ - _this.render_file_list(); - }); - $('.select_dir_list thead th .icon-drag').on('mousedown',function(ev){ - var x = ev.clientX,th = $(this).parent(),th_index = th.index(),th_width = th[0].clientWidth,min_width = parseInt($(this).parent().attr('data-min')),timeOut = null; - if(ev.which === 1){ - var document_mousemove = function(e){ - var move_x = e.clientX,offset_x = move_x - x,_width = th_width + offset_x; - timeOut = setTimeout(function(){ - _this.set_select_width(th_index,'width:'+_width+'px'); - },0); - }, - document_mouseup = function(){ - console.log(document_mouseup); - $(this).unbind(document_mousemove); - $(this).unbind(document_mouseup); - }; - $(document).on('mousemove',document_mousemove).one('mouseup',function(){ - $(this).unbind(document_mousemove); - $(this).unbind(this); - }) - } - ev.stopPropagation(); - }); - $('.select_dir_list thead th>span').on('click',function(ev){ - var th = $(this).parent(),type = th.data('type'),is_active = th.hasClass('active'),is_sort = th.hasClass('sort'); - if(is_active){ - th.addClass('sort').removeClass('active'); - }else if(is_sort){ - th.addClass('active').removeClass('sort'); + if(data.down_id !== 0){ //判断是否分享 + config_group.splice(3-offsetNum,1); + offsetNum ++; }else{ - th.addClass('active'); + config_group.splice(4-offsetNum,1); + config_group[3-offsetNum][1] = (data.type == 'dir'?'分享目录':'分享文件'); + offsetNum ++; } - th.siblings().removeClass('active sort'); - _this.render_file_list({sort:type,reverse:is_active?1:0}); - ev.stopPropagation(); - }); - $('.search_path_views input').on('keyup',function(){ - var val = $(this).val(); - console.log(val); - }); - $('.search_path_views input').focus(function(){ - $(this).next().show(); - }).blur(function(){ - $(this).next().hide(); - }); - //提交选中文件 - $('#select_file_directory .select_file_group').on('click','.select_btn_group .btn-success',function(e){ - var select_val = $('[name="select_name"]').val(), - submit_val = ''; - if (select_val == '') { - layer.msg('只能选择' + _this.type_tips,{icon:2}); - }else{ - submit_val = _this.file_path+'/'+select_val; - console.log(submit_val) - } - }); - //新建文件夹 - $('#select_file_directory .select_file_tootls').on('click','.creat_dir',function(e){ - var a = "   "; - if($("#tbody tr").length == 0) { - $("#select_dir_list").append(a) - } else { - $("#select_dir_list tr:first-child").before(a) - } - $(".newFolderName").focus(); - $("#nameOk").click(function() { - var c = $("#newFolderName").val(), - b = $(".file_path_views .path_input").attr("data-path"); - newTxt = b+"/"+ c; - that.$http('CreateDir', {'path': newTxt},function(e){ - if(e.status == true) { - _this.reader_file_list({path:b,is_operating:false}); - layer.msg(e.msg, {icon: 1}); - } else { - layer.msg(e.msg, {icon: 2}); - } - }); - }); - }); - // 左侧根目录点击跳转 - $('#select_mount_list').on('click','.item',function(){ - _this.reader_file_list({path:$(this).attr('data-menu'),is_operating:true}); - }); + if(data.caret !== false){ // 判断是否收藏 + config_group.splice((5-offsetNum),1); + offsetNum ++; + }else{ + config_group.splice((6-offsetNum),1); + config_group[5-offsetNum][1] = (data.type == 'dir'?'收藏目录':'收藏文件'); + offsetNum ++; + } + if(data.ext != 'php' && data.type != 'dir'){ // 判断是否为php,非php文件(排除目录)无法扫描 + config_group.splice((8-offsetNum),1); + offsetNum ++; + } + var num = 0; + $.each(compression,function(index,item){ + if(item == data.ext) num ++; + }); + if(num == 0){ + config_group.splice((17-offsetNum),1); + offsetNum ++; + } + _this.reader_menu_list({el:$('.selection_right_menu'),ev:ev,data:data,list:config_group}); + }, + + /** + * @description 渲染右键全局菜单 + * @param {Object} ev 事件event对象 + * @param {Object} el 事件对象DOM + * @return void + */ + render_file_all_menu:function (ev,el) { + var _this = this,config_group = [['refresh','刷新'],['split',''],['upload','上传'],['create','新建文件夹/文件',[['create_dir','新建文件夹'],['create_files','新建文件']]],['split',''],['paste','粘贴']],offsetNum = 0; + if(!bt.get_storage('session','copy_path')){ + config_group.splice(5,1); + offsetNum ++; + } + _this.reader_menu_list({el:$('.selection_right_menu'),ev:ev,data:{},list:config_group}); + }, + get_dir_list:function(data, callback,is_tips) { + var _this = this; + if(typeof callback === "boolean") is_tips = callback,callback = null; + that.$http('GetDir',$.extend({ + disk:true, + path:_this.file_path, + sort:bt.get_cookie('files_sort') || 'type', + },data),callback,is_tips); + }, + /** + * @description 返回上一层目录地址 + * @param {String} path 当前路径 + * @returns 返回上一层地址 + */ + retrun_prev_path:function(path){ + var dir_list = path.split('/'); + dir_list.splice(dir_list.length - 1); + return dir_list.join('/'); + }, + + /** + * @description 渲染菜单列表 + * @param {Object} config 菜单配置列表和数据 + * @returns void + */ + reader_menu_list:function(config){ + var _this = this,el = config.el.find('ul'),el_height = el.height(),el_width = el.width(),left = config.ev.clientX - ((this.area[0] - config.ev.clientX) < el_width?el_width:0); + el.empty(); + $.each(config.list,function(index,item){ + var $children = null,$children_list = null; + if(item[0] == 'split'){ + el.append('
              • '); + }else{ + if(Array.isArray(item[2])){ + $children = $('
                  '); + $children_list = $children.find('.set_group'); + $.each(item[2],function(indexs,items) { + $children_list.append($('
                • '+ items[1] +'
                • ').on('click',{type:items[0],data:config.data},function(ev){ + _this.file_groud_event($.extend(ev.data.data,{ + open:ev.data.type, + index:parseInt($(config.ev.currentTarget).data('index')), + element:config.ev.currentTarget, + type_tips:item.type?'文件夹':'文件' + })); + config.el.removeAttr('style'); + ev.stopPropagation(); + ev.preventDefault(); + })) + }); + } + el.append($('
                • '+ item[1] +'
                • ').append($children).on('click',{type:item[0],data:config.data},function(ev){ + _this.file_groud_event($.extend(ev.data.data,{ + open:ev.data.type, + index:parseInt($(config.ev.currentTarget).data('index')), + element:config.ev.currentTarget, + type_tips:item.type?'文件夹':'文件' + })); + config.el.removeAttr('style'); + ev.stopPropagation(); + ev.preventDefault(); + })); + } + }); + config.el.css({ + left: left, + top: config.ev.clientY - ((this.area[1] - config.ev.clientY) < el_height?el_height:0) + }).removeClass('left_menu right_menu').addClass(this.area[0] - (left + el_width) < 230?'left_menu':'right_menu'); + $(document).one('click',function(e){ + $(config.ev.currentTarget).removeClass('selected'); + config.el.removeAttr('style'); + e.stopPropagation(); + e.preventDefault(); + }); + }, - // 窗口大小限制 - $(window).resize(function(ev){ - if($(this)[0].innerHeight != _this.area[1]){ - _this.area[1] = $(this)[0].innerHeight; - _this.set_file_view(); - } - if($(this)[0].innerWidth != _this.area[0]){ - _this.area[0] = $(this)[0].innerWidth; - _this.set_dir_view_resize(); - // _this.set_file_table_width(); - } - if(_this.vscode_editor.view){ - if(_this.vscode_editor.is_full_min > 0){ - layer.style(_this.vscode_editor.view,{ - 'top':0, - 'left':0,'width':_this.area[0], - 'height':_this.area[1] - }); + /** + * @description 返回后缀类型说明 + * @param {String} ext 后缀类型 + * @return {String} 文件类型 + */ + ext_type_tips:function(ext){ + var config = {ai:"Adobe Illustrator格式图形",apk:"安卓安装包",asp:"动态网页文件",bat:"批处理文件",bin:"二进制文件",bas:"BASIC源文件",bak:"备份文件",css:'CSS样式表',cad:"备份文件",cxx:"C++源代码文件",crt:"认证文件",cpp:"C++代码文件",conf:"配置文件",dat:"数据文件",der:"认证文件",doc:"Microsoft Office Word 97-2003 文档",docx:"Microsoft Office Word 2007 文档",exe:"程序应用",gif:"图形文件",go:"Go语言源文件",htm:"超文本文档",html:"超文本文档",ico:"图形文件",java:"Java源文件",jsp:"HTML网页",jpe:"图形文件",jpeg:"图形文件",jpg:"图形文件",log:"日志文件",link:"快捷方式文件",js:"Javascript源文件",mdb:"Microsoft Access数据库",mp3:"音频文件",mp4:"视频文件",mng:"多映像网络图形",msi:"Windows Installe安装文件包",png:"图形文件",py:"Python源代码",pyc:"Python字节码文件",pdf:"文档格式文件",ppt:"Microsoft Powerpoint 97-2003 幻灯片演示文稿",pptx:"Microsoft Powerpoint2007 幻灯片演示文稿",psd:"Adobe photoshop位图文件",pl:"Perl脚本语言",rar:"RAR压缩文件",reg:"注册表文件",sys:"系统文件",sql:"数据库文件",sh:"Shell脚本文件",txt:"文本格式",vb:"Visual Basic的一种宏语言",xml:"扩展标记语言",xls:"Microsoft Office Excel 97-2003 工作表",xlsx:"Microsoft Office Excel 2007 工作表",gz:"压缩文件",zip:"ZIP压缩文件",z:"","7z":"7Z压缩文件",json:'JSON文本'}; + return typeof config[ext] != "undefined"?config[ext]:(ext+'文件'); + }, + /** + * @description 事件绑定 + */ + event_bind: function(){ + var _this = this; + //单击选中文件 + $('#select_dir_list').on('click','tr[data-index]',function(e){ + var index = $(this).data('index'), + _type = $(this).attr('data-type'), + select_name_val = (_this.type_limit=='file' && _type == 'dir')?'':_this.select_list[index].filename; + $(this).addClass('active').siblings().removeClass('active'); + $('[name="select_name"]').val(select_name_val); + if (_type == 'file'){ + $('.file_path_views .forward_path span:eq(1)').addClass('active'); + }else{ + $('.file_path_views .forward_path span:eq(1)').removeClass('active'); + } + }); + $('.select_list_body').on('scroll',function(e){ + var top = $(this).scrollTop(),left = $(this).scrollLeft(); + if(top > 0){ + $('.select_list_shadow').show(); + }else{ + $('.select_list_shadow').hide(); + } + if(left >= 0){ + $('.select_list_thaed').css('left',(4-left ) +'px'); + } + e.stopPropagation(); + e.preventDefault(); + }); + //文件刷新按钮 + $('.file_path_refresh').on('click',function(){ + _this.render_file_list(); + }); + $('.select_dir_list thead th .icon-drag').on('mousedown',function(ev){ + var x = ev.clientX,th = $(this).parent(),th_index = th.index(),th_width = th[0].clientWidth,min_width = parseInt($(this).parent().attr('data-min')),timeOut = null; + if(ev.which === 1){ + var document_mousemove = function(e){ + var move_x = e.clientX,offset_x = move_x - x,_width = th_width + offset_x; + timeOut = setTimeout(function(){ + _this.set_select_width(th_index,'width:'+_width+'px'); + },0); + }, + document_mouseup = function(){ + console.log(document_mouseup); + $(this).unbind(document_mousemove); + $(this).unbind(document_mouseup); + }; + $(document).on('mousemove',document_mousemove).one('mouseup',function(){ + $(this).unbind(document_mousemove); + $(this).unbind(this); + }) + } + ev.stopPropagation(); + }); + $('.select_dir_list thead th>span').on('click',function(ev){ + var th = $(this).parent(),type = th.data('type'),is_active = th.hasClass('active'),is_sort = th.hasClass('sort'); + if(is_active){ + th.addClass('sort').removeClass('active'); + }else if(is_sort){ + th.addClass('active').removeClass('sort'); + }else{ + th.addClass('active'); + } + th.siblings().removeClass('active sort'); + _this.render_file_list({sort:type,reverse:is_active?1:0}); + ev.stopPropagation(); + }); + $('.search_path_views input').on('keyup',function(){ + var val = $(this).val(); + console.log(val); + }); + $('.search_path_views input').focus(function(){ + $(this).next().show(); + }).blur(function(){ + $(this).next().hide(); + }); + //提交选中文件 + $('#select_file_directory .select_file_group').on('click','.select_btn_group .btn-success',function(e){ + var select_val = $('[name="select_name"]').val(), + submit_val = ''; + if (select_val == '') { + layer.msg('只能选择' + _this.type_tips,{icon:2}); + }else{ + submit_val = _this.file_path+'/'+select_val; + console.log(submit_val) + } + }); + //新建文件夹 + $('#select_file_directory .select_file_tootls').on('click','.creat_dir',function(e){ + var a = "   "; + if($("#tbody tr").length == 0) { + $("#select_dir_list").append(a) + } else { + $("#select_dir_list tr:first-child").before(a) + } + $(".newFolderName").focus(); + $("#nameOk").click(function() { + var c = $("#newFolderName").val(), + b = $(".file_path_views .path_input").attr("data-path"); + newTxt = b+"/"+ c; + that.$http('CreateDir', {'path': newTxt},function(e){ + if(e.status == true) { + _this.reader_file_list({path:b,is_operating:false}); + layer.msg(e.msg, {icon: 1}); + } else { + layer.msg(e.msg, {icon: 2}); + } + }); + }); + }); + // 左侧根目录点击跳转 + $('#select_mount_list').on('click','.item',function(){ + _this.reader_file_list({path:$(this).attr('data-menu'),is_operating:true}); + }); + + + // 窗口大小限制 + $(window).resize(function(ev){ + if($(this)[0].innerHeight != _this.area[1]){ + _this.area[1] = $(this)[0].innerHeight; + _this.set_file_view(); + } + if($(this)[0].innerWidth != _this.area[0]){ + _this.area[0] = $(this)[0].innerWidth; + _this.set_dir_view_resize(); + // _this.set_file_table_width(); + } + if(_this.vscode_editor.view){ + if(_this.vscode_editor.is_full_min > 0){ + layer.style(_this.vscode_editor.view,{ + 'top':0, + 'left':0,'width':_this.area[0], + 'height':_this.area[1] + }); + } + } + if(_this.vscode_editor.view && $.isEmptyObject(_this.vscode_editor.list)) _this.vscode.layout(); + // console.log($.isEmptyObject(_this.vscode_editor.list)); + }).keydown(function(e){ // 全局按键事件 + e = window.event || e; + var keyCode = e.keyCode,tagName = e.target.tagName.toLowerCase(); + if(keyCode == 8 && tagName !== 'input' && tagName !== 'textarea'){ //退格键 -> 后退操作 + if(_this.vscode_editor.view == null){ + $('.forward_path span:eq(0)').click(); + } + return false; + } + }); + + // 文件路径事件(获取焦点、失去焦点、回车提交) + $('.file_path_input .path_input').on('focus blur keyup',function(e){ + e = e || window.event; + var path = $(this).attr('data-path'); + switch(e.type){ + case 'focus': + $(this).addClass('focus').val(path).prev().hide(); + break; + case 'blur': + $(this).removeClass('focus').val('').prev().show(); + break; + case 'keyup': + if(e.keyCode != 13 && e.type == 'keyup') return false; + var _val = $(this); + if($(this).data('path') != $(this).val()){ + _this.reader_file_list({path:$(this).val(),is_operating:true},function(res){ + if(res.status === false){ + $(_val).val(path); + }else{ + $(_val).val(res.PATH); + $(_val).blur().prev().show(); + } + }); + } + break; + } + e.stopPropagation(); + }); + + // 文件路径点击跳转 + $('.file_path_input .file_dir_view').on('click','.file_dir',function(){ + _this.reader_file_list({path:$(this).attr('title'),is_operating:true}); + }); + + // 操作前进或后退 + $('.forward_path span').click(function(){ + var index = $(this).index(),path = ''; + if(!$(this).hasClass('active')){ + switch(index){ + case 0: + _this.file_pointer = _this.file_pointer - 1 + path = _this.retrun_prev_path(_this.file_path); + break; + case 1: + _this.file_pointer = _this.file_pointer + 1 + //path = _this.file_operating[_this.file_pointer]; + path = _this.file_path + '/' + $(".select_file_group .file_directory").val(); + break; + case 2: + _this.file_pointer = _this.file_pointer - 1 + path = _this.retrun_prev_path(_this.file_path); + break; + } + _this.reader_file_list({path:path,is_operating:false}); + } + }); + + //展示已隐藏的目录 + $('.file_path_input .file_dir_view').on('click','.file_dir_omit',function(e){ + var _this = this,new_down_list = $(this).children('.nav_down_list'); + $(this).addClass('active'); + new_down_list.addClass('show'); + $(document).one('click',function(){ + $(_this).removeClass('active'); + new_down_list.removeClass('show'); + e.stopPropagation(); + }); + e.stopPropagation(); + }); + + // 打开文件夹和文件 --- 双击 + $('#select_dir_list').on('dblclick','tr',function(e){ + if($(e.target).hasClass('file_check')) return false; + var path = $(this).attr('data-path'),type = $(this).attr('data-type'); + if(type == 'dir'){ + _this.reader_file_list({path:_this.file_path + '/' + path}); + }else{ + + } + e.stopPropagation(); + e.preventDefault(); + }); + + // 文件刷新 + $('.file_path_refresh').click(function(){ + _this.reader_file_list({path:_this.file_path}); + }); + + // 上传 + $('.file_nav_view .upload_or_download').on('click',function(e){ + _this.open_upload_view(); + e.stopPropagation(); + e.preventDefault(); + }); + + // 上传与下载下拉点击 + $('.file_nav_view .upload_or_download li').on('click',function(e){ + var type = $(this).data('type') + if(type === 'uploadFile'){ + _this.open_upload_view(); + }else{ + _this.open_download_view(); + } + e.stopPropagation(); + e.preventDefault(); + }); + + // 打开硬盘挂载的目录 + $('.mount_disk_list').on('click','.nav_btn',function(){ + var path = $(this).data('menu'); + _this.reader_file_list({path:path}); + }); + + // 表头点击事件,触发排序字段和排序方式 + $('.file_list_header').on('click','.file_name,.file_size,.file_mtime,.file_accept,.file_user', function (e) { + var _tid = $(this).attr('data-tid'), + _reverse = $(this).find('.icon_sort').hasClass('active'), + _active = $(this).hasClass('active'); + if (!$(this).find('.icon_sort').hasClass('active') && $(this).hasClass('active')) { + $(this).find('.icon_sort').addClass('active'); + }else{ + $(this).find('.icon_sort').removeClass('active'); + } + $(this).addClass('active').siblings().removeClass('active').find('.icon_sort').removeClass('active').empty(); + $(this).find('.icon_sort').html(''); + if (!_active) _reverse = true + bt.set_cookie('files_sort', _tid); + bt.set_cookie('name_reverse', _reverse ? 1 : 0); + _this.reader_file_list(); + return false; + }); + + // 设置排序显示 + $('.file_list_header .file_th').each(function (index, item) { + var files_sort = bt.get_cookie('files_sort'), + name_reverse = bt.get_cookie('name_reverse'); + if ($(this).attr('data-tid') === files_sort){ + $(this).addClass('active').siblings().removeClass('active').find('.icon_sort').removeClass('active').empty(); + $(this).find('.icon_sort').html(''); + if (name_reverse === 0) $(this).find('.icon_sort').addClass('active'); + } + }); + + // 全选选中文件 + $('.file_list_header .file_check').on('click', function (e){ + var checkbox = parseInt($(this).data('checkbox')); + switch(checkbox){ + case 0: + $(this).addClass('active').removeClass('active_2').data('checkbox',1); + $('.file_list_content .file_tr').addClass('active').removeClass('active_2'); + _this.file_table_arry = _this.file_list; + break; + case 2: + $(this).addClass('active').removeClass('active_2').data('checkbox',1); + $('.file_list_content .file_tr').addClass('active'); + _this.file_table_arry = _this.file_list; + break; + case 1: + $(this).removeClass('active active_2').data('checkbox',0); + $('.file_list_content .file_tr').removeClass('active'); + _this.file_table_arry = []; + break; + } + }); + + // 选中文件 + $('.file_list_content').on('click', '.file_check', function (e) { //列表选择 + var _tr = $(this).parents('.file_tr'),index = _tr.data('index'),header_check = $('.file_list_header .file_check'),filename = _tr.attr('data-filename'); + $('.selection_right_menu').removeAttr('style'); + if(_tr.hasClass('active')){ + _tr.removeClass('active'); + _this.remove_check_file(_this.file_table_arry,'filename',filename); + if(_this.file_table_arry.length > 0){ + header_check.addClass('active_2').removeClass('active').data('checkbox',2); + }else if(_this.file_table_arry.length == 0){ + header_check.removeClass('active active_2').data('checkbox',0); + } + }else{ + _tr.addClass('active'); + _tr.attr('data-filename',_this.file_list[index]['filename']); + if(_this.file_table_arry.length == _this.file_list.length){ + header_check.addClass('active').removeClass('active_2').data('checkbox',1); + }else{ + header_check.addClass('active_2').removeClass('active').data('checkbox',2); + } + _this.file_table_arry.push(_this.file_list[index]); + } + e.stopPropagation(); + }); + + // 文件列表滚动条事件 + $('.file_list_content').scroll(function(e){ + if($(this).scrollTop() == ($(this)[0].scrollHeight - $(this)[0].clientHeight)){ + $(this).prev().css('opacity',1); + $(this).next().css('opacity',0); + }else if($(this).scrollTop() > 0){ + $(this).prev().css('opacity',1); + }else if($(this).scrollTop() == 0){ + $(this).prev().css('opacity',0); + $(this).next().css('opacity',1); + } + }); + + // 选中文件 + $('.file_table_view .file_list_content').on('click','.file_tr',function(e){ + $('.selection_right_menu').removeAttr('style'); + $(this).find('.file_checkbox .file_check').click(); + e.stopPropagation(); + e.preventDefault(); + }); + + // 打开文件夹或文件 --- 文件名单击 + $('.file_table_view .file_list_content').on('click','.file_title i',function(e){ + var file_tr = $(this).parents('.file_tr'),index = file_tr.data('index'),data = _this.file_list[index]; + if(data.type == 'dir'){ + _this.reader_file_list({path:_this.file_path + '/' + data['filename']}); + }else{ + + } + e.stopPropagation(); + }); + + // 打开文件的分享状态 + $('.file_table_view .file_list_content').on('click','.file_name .icon-share1',function(e){ + var file_tr = $(this).parents('.file_tr'),index = file_tr.data('index'),data = _this.file_list[index]; + _this.info_file_share(data,file_tr); + e.stopPropagation(); + }); + + + // 打开文件的收藏夹状态 + $('.file_table_view .file_list_content').on('click','.file_name .icon-favorites',function(e){ + var file_tr = $(this).parents('.file_tr'),index = file_tr.data('index'),data = _this.file_list[index]; + data.typeText = data.type?'文件夹':'文件'; + _this.cancel_file_favorites(data,file_tr); + e.stopPropagation(); + }); + + + // 打开文件夹和文件 --- 双击 + $('.file_table_view .file_list_content').on('dblclick','.file_tr',function(e){ + if($(e.target).hasClass('file_check')) return false; + var index = $(this).data('index'),data = _this.file_list[index]; + if(data.type == 'dir'){ + + _this.reader_file_list({path:_this.file_path + '/' + data['filename']}); + }else{ + + } + e.stopPropagation(); + e.preventDefault(); + }); + + // 文件夹和文件鼠标右键 + $('.file_list_content').on('contextmenu','.file_tr',function(ev){ + var _that = this; + if(ev.which == 3){ + _this.render_file_groud_menu(ev,this); + $('.content_right_menu').removeAttr('style'); + $(this).addClass('selected').siblings().removeClass('selected'); + $(document).one('click',function(e){ + $(_that).removeClass('selected'); + $('.selection_right_menu').removeAttr('style'); + e.stopPropagation(); + e.preventDefault(); + }); + } + ev.stopPropagation(); + ev.preventDefault(); + }); + + // 文件空白区域右键菜单 + $('.file_list_content').on('contextmenu',function(ev){ + var content_right_menu = $('.content_right_menu'),content_menu_width = content_right_menu.width(),content_menu_height = content_right_menu.height(),_that = this; + if(ev.which == 3){ + $('.selection_right_menu').removeAttr('style'); + _this.render_file_all_menu(ev,this) + } + ev.stopPropagation(); + ev.preventDefault(); + }); + + //设置单页显示的数量,默认为100,设置local本地缓存 + $('.filePage').on('change','.showRow',function(){ + var val = $(this).val(); + bt.set_storage('showRow',val); + _this.reader_file_list(); + }); + + // 获取文件夹大小 + $('.file_list_content').on('click','.folder_size',function(e){ + var data = _this.file_list[$(this).parents('.file_tr').data('index')],_this = this; + _this.get_file_size({path:data.path},function(res){ + $(_this).text(bt.format_size(res.size)); + }); + e.stopPropagation(); + e.preventDefault(); + }); + + // 视图调整 + $('.cut_view_model').on('click',function(){ + var type = $(this).data('type'); + $('.file_table_view').addClass(type == 'icon'?'icon_view':'list_view').removeClass(type != 'icon'?'icon_view':'list_view'); + $(this).addClass('active').siblings().removeClass('active'); + }); + + }, + /** + * @description 设置文件前进或后退状态 + * @returns void + */ + set_file_forward:function(){ + var _this = this,forward_path = $('.forward_path span'); + console.log(_this.file_operation) + if(_this.file_operating.length == 1){ + forward_path.addClass('active'); + }else if(_this.file_pointer == _this.file_operating.length -1){ + forward_path.eq(0).removeClass('active'); + forward_path.eq(1).addClass('active'); + }else if(_this.file_pointer == 0){ + forward_path.eq(0).addClass('active'); + forward_path.eq(1).removeClass('active'); + }else{ + forward_path.removeClass('active'); + } + }, + /** + * @description 设置文件视图 + * @returns void + */ + set_file_view:function(){ + var file_list_content = $('.file_list_content'),height = this.area[1] - 170; + $('.file_bodys').height(this.area[1] - 100); + if((this.file_list.length * 50) > height){ + file_list_content.attr('data-height',file_list_content.data('height') || file_list_content.height()).height(height); + $('.file_shadow_bottom').css('opacity',1); + }else{ + file_list_content.height(height); + $('.file_shadow_top,.file_shadow_bottom').css('opacity',0); + } + }, + /** + * @description 清除表格选中数据和样式 + * @returns void + */ + clear_table_active:function(){ + this.file_table_arry = []; + $('.file_list_header .file_check').removeClass('active active_2'); + $('.file_list_content .file_tr').removeClass('active'); + }, } - } - if(_this.vscode_editor.view && $.isEmptyObject(_this.vscode_editor.list)) _this.vscode.layout(); - // console.log($.isEmptyObject(_this.vscode_editor.list)); - }).keydown(function(e){ // 全局按键事件 - e = window.event || e; - var keyCode = e.keyCode,tagName = e.target.tagName.toLowerCase(); - if(keyCode == 8 && tagName !== 'input' && tagName !== 'textarea'){ //退格键 -> 后退操作 - if(_this.vscode_editor.view == null){ - $('.forward_path span:eq(0)').click(); - } - return false; - } - }); - - // 文件路径事件(获取焦点、失去焦点、回车提交) - $('.file_path_input .path_input').on('focus blur keyup',function(e){ - e = e || window.event; - var path = $(this).attr('data-path'); - switch(e.type){ - case 'focus': - $(this).addClass('focus').val(path).prev().hide(); - break; - case 'blur': - $(this).removeClass('focus').val('').prev().show(); - break; - case 'keyup': - if(e.keyCode != 13 && e.type == 'keyup') return false; - var _val = $(this); - if($(this).data('path') != $(this).val()){ - _this.reader_file_list({path:$(this).val(),is_operating:true},function(res){ - if(res.status === false){ - $(_val).val(path); - }else{ - $(_val).val(res.PATH); - $(_val).blur().prev().show(); - } - }); - } - break; - } - e.stopPropagation(); - }); - - // 文件路径点击跳转 - $('.file_path_input .file_dir_view').on('click','.file_dir',function(){ - _this.reader_file_list({path:$(this).attr('title'),is_operating:true}); - }); - - // 操作前进或后退 - $('.forward_path span').click(function(){ - var index = $(this).index(),path = ''; - if(!$(this).hasClass('active')){ - switch(index){ - case 0: - _this.file_pointer = _this.file_pointer - 1 - path = _this.retrun_prev_path(_this.file_path); - break; - case 1: - _this.file_pointer = _this.file_pointer + 1 - //path = _this.file_operating[_this.file_pointer]; - path = _this.file_path + '/' + $(".select_file_group .file_directory").val(); - break; - case 2: - _this.file_pointer = _this.file_pointer - 1 - path = _this.retrun_prev_path(_this.file_path); - break; - } - _this.reader_file_list({path:path,is_operating:false}); - } - }); - - //展示已隐藏的目录 - $('.file_path_input .file_dir_view').on('click','.file_dir_omit',function(e){ - var _this = this,new_down_list = $(this).children('.nav_down_list'); - $(this).addClass('active'); - new_down_list.addClass('show'); - $(document).one('click',function(){ - $(_this).removeClass('active'); - new_down_list.removeClass('show'); - e.stopPropagation(); - }); - e.stopPropagation(); - }); - - // 打开文件夹和文件 --- 双击 - $('#select_dir_list').on('dblclick','tr',function(e){ - if($(e.target).hasClass('file_check')) return false; - var path = $(this).attr('data-path'),type = $(this).attr('data-type'); - if(type == 'dir'){ - _this.reader_file_list({path:_this.file_path + '/' + path}); - }else{ - - } - e.stopPropagation(); - e.preventDefault(); - }); - - // 文件刷新 - $('.file_path_refresh').click(function(){ - _this.reader_file_list({path:_this.file_path}); - }); - - // 上传 - $('.file_nav_view .upload_or_download').on('click',function(e){ - _this.open_upload_view(); - e.stopPropagation(); - e.preventDefault(); - }); - - // 上传与下载下拉点击 - $('.file_nav_view .upload_or_download li').on('click',function(e){ - var type = $(this).data('type') - if(type === 'uploadFile'){ - _this.open_upload_view(); - }else{ - _this.open_download_view(); - } - e.stopPropagation(); - e.preventDefault(); - }); - - // 打开硬盘挂载的目录 - $('.mount_disk_list').on('click','.nav_btn',function(){ - var path = $(this).data('menu'); - _this.reader_file_list({path:path}); - }); - - // 表头点击事件,触发排序字段和排序方式 - $('.file_list_header').on('click','.file_name,.file_size,.file_mtime,.file_accept,.file_user', function (e) { - var _tid = $(this).attr('data-tid'), - _reverse = $(this).find('.icon_sort').hasClass('active'), - _active = $(this).hasClass('active'); - if (!$(this).find('.icon_sort').hasClass('active') && $(this).hasClass('active')) { - $(this).find('.icon_sort').addClass('active'); - }else{ - $(this).find('.icon_sort').removeClass('active'); - } - $(this).addClass('active').siblings().removeClass('active').find('.icon_sort').removeClass('active').empty(); - $(this).find('.icon_sort').html(''); - if (!_active) _reverse = true - bt.set_cookie('files_sort', _tid); - bt.set_cookie('name_reverse', _reverse ? 1 : 0); - _this.reader_file_list(); - return false; - }); - - // 设置排序显示 - $('.file_list_header .file_th').each(function (index, item) { - var files_sort = bt.get_cookie('files_sort'), - name_reverse = bt.get_cookie('name_reverse'); - if ($(this).attr('data-tid') === files_sort){ - $(this).addClass('active').siblings().removeClass('active').find('.icon_sort').removeClass('active').empty(); - $(this).find('.icon_sort').html(''); - if (name_reverse === 0) $(this).find('.icon_sort').addClass('active'); - } - }); - - // 全选选中文件 - $('.file_list_header .file_check').on('click', function (e){ - var checkbox = parseInt($(this).data('checkbox')); - switch(checkbox){ - case 0: - $(this).addClass('active').removeClass('active_2').data('checkbox',1); - $('.file_list_content .file_tr').addClass('active').removeClass('active_2'); - _this.file_table_arry = _this.file_list; - break; - case 2: - $(this).addClass('active').removeClass('active_2').data('checkbox',1); - $('.file_list_content .file_tr').addClass('active'); - _this.file_table_arry = _this.file_list; - break; - case 1: - $(this).removeClass('active active_2').data('checkbox',0); - $('.file_list_content .file_tr').removeClass('active'); - _this.file_table_arry = []; - break; - } - }); - - // 选中文件 - $('.file_list_content').on('click', '.file_check', function (e) { //列表选择 - var _tr = $(this).parents('.file_tr'),index = _tr.data('index'),header_check = $('.file_list_header .file_check'),filename = _tr.attr('data-filename'); - $('.selection_right_menu').removeAttr('style'); - if(_tr.hasClass('active')){ - _tr.removeClass('active'); - _this.remove_check_file(_this.file_table_arry,'filename',filename); - if(_this.file_table_arry.length > 0){ - header_check.addClass('active_2').removeClass('active').data('checkbox',2); - }else if(_this.file_table_arry.length == 0){ - header_check.removeClass('active active_2').data('checkbox',0); - } - }else{ - _tr.addClass('active'); - _tr.attr('data-filename',_this.file_list[index]['filename']); - if(_this.file_table_arry.length == _this.file_list.length){ - header_check.addClass('active').removeClass('active_2').data('checkbox',1); - }else{ - header_check.addClass('active_2').removeClass('active').data('checkbox',2); - } - _this.file_table_arry.push(_this.file_list[index]); - } - e.stopPropagation(); - }); - - // 文件列表滚动条事件 - $('.file_list_content').scroll(function(e){ - if($(this).scrollTop() == ($(this)[0].scrollHeight - $(this)[0].clientHeight)){ - $(this).prev().css('opacity',1); - $(this).next().css('opacity',0); - }else if($(this).scrollTop() > 0){ - $(this).prev().css('opacity',1); - }else if($(this).scrollTop() == 0){ - $(this).prev().css('opacity',0); - $(this).next().css('opacity',1); - } - }); - - // 选中文件 - $('.file_table_view .file_list_content').on('click','.file_tr',function(e){ - $('.selection_right_menu').removeAttr('style'); - $(this).find('.file_checkbox .file_check').click(); - e.stopPropagation(); - e.preventDefault(); - }); - - // 打开文件夹或文件 --- 文件名单击 - $('.file_table_view .file_list_content').on('click','.file_title i',function(e){ - var file_tr = $(this).parents('.file_tr'),index = file_tr.data('index'),data = _this.file_list[index]; - if(data.type == 'dir'){ - _this.reader_file_list({path:_this.file_path + '/' + data['filename']}); - }else{ - - } - e.stopPropagation(); - }); - - // 打开文件的分享状态 - $('.file_table_view .file_list_content').on('click','.file_name .icon-share1',function(e){ - var file_tr = $(this).parents('.file_tr'),index = file_tr.data('index'),data = _this.file_list[index]; - _this.info_file_share(data,file_tr); - e.stopPropagation(); - }); - - - // 打开文件的收藏夹状态 - $('.file_table_view .file_list_content').on('click','.file_name .icon-favorites',function(e){ - var file_tr = $(this).parents('.file_tr'),index = file_tr.data('index'),data = _this.file_list[index]; - data.typeText = data.type?'文件夹':'文件'; - _this.cancel_file_favorites(data,file_tr); - e.stopPropagation(); - }); - - - // 打开文件夹和文件 --- 双击 - $('.file_table_view .file_list_content').on('dblclick','.file_tr',function(e){ - if($(e.target).hasClass('file_check')) return false; - var index = $(this).data('index'),data = _this.file_list[index]; - if(data.type == 'dir'){ - - _this.reader_file_list({path:_this.file_path + '/' + data['filename']}); - }else{ - - } - e.stopPropagation(); - e.preventDefault(); - }); - - // 文件夹和文件鼠标右键 - $('.file_list_content').on('contextmenu','.file_tr',function(ev){ - var _that = this; - if(ev.which == 3){ - _this.render_file_groud_menu(ev,this); - $('.content_right_menu').removeAttr('style'); - $(this).addClass('selected').siblings().removeClass('selected'); - $(document).one('click',function(e){ - $(_that).removeClass('selected'); - $('.selection_right_menu').removeAttr('style'); - e.stopPropagation(); - e.preventDefault(); - }); - } - ev.stopPropagation(); - ev.preventDefault(); - }); - - // 文件空白区域右键菜单 - $('.file_list_content').on('contextmenu',function(ev){ - var content_right_menu = $('.content_right_menu'),content_menu_width = content_right_menu.width(),content_menu_height = content_right_menu.height(),_that = this; - if(ev.which == 3){ - $('.selection_right_menu').removeAttr('style'); - _this.render_file_all_menu(ev,this) - } - ev.stopPropagation(); - ev.preventDefault(); - }); - - //设置单页显示的数量,默认为100,设置local本地缓存 - $('.filePage').on('change','.showRow',function(){ - var val = $(this).val(); - bt.set_storage('showRow',val); - _this.reader_file_list(); - }); - - // 获取文件夹大小 - $('.file_list_content').on('click','.folder_size',function(e){ - var data = _this.file_list[$(this).parents('.file_tr').data('index')],_this = this; - _this.get_file_size({path:data.path},function(res){ - $(_this).text(bt.format_size(res.size)); - }); - e.stopPropagation(); - e.preventDefault(); - }); - - // 视图调整 - $('.cut_view_model').on('click',function(){ - var type = $(this).data('type'); - $('.file_table_view').addClass(type == 'icon'?'icon_view':'list_view').removeClass(type != 'icon'?'icon_view':'list_view'); - $(this).addClass('active').siblings().removeClass('active'); - }); - - }, - /** - * @description 设置文件前进或后退状态 - * @returns void - */ - set_file_forward:function(){ - var _this = this,forward_path = $('.forward_path span'); - console.log(_this.file_operation) - if(_this.file_operating.length == 1){ - forward_path.addClass('active'); - }else if(_this.file_pointer == _this.file_operating.length -1){ - forward_path.eq(0).removeClass('active'); - forward_path.eq(1).addClass('active'); - }else if(_this.file_pointer == 0){ - forward_path.eq(0).addClass('active'); - forward_path.eq(1).removeClass('active'); - }else{ - forward_path.removeClass('active'); - } - }, - /** - * @description 设置文件视图 - * @returns void - */ - set_file_view:function(){ - var file_list_content = $('.file_list_content'),height = this.area[1] - 170; - $('.file_bodys').height(this.area[1] - 100); - if((this.file_list.length * 50) > height){ - file_list_content.attr('data-height',file_list_content.data('height') || file_list_content.height()).height(height); - $('.file_shadow_bottom').css('opacity',1); - }else{ - file_list_content.height(height); - $('.file_shadow_top,.file_shadow_bottom').css('opacity',0); - } - }, - /** - * @description 清除表格选中数据和样式 - * @returns void - */ - clear_table_active:function(){ - this.file_table_arry = []; - $('.file_list_header .file_check').removeClass('active active_2'); - $('.file_list_content .file_tr').removeClass('active'); - }, - } - select_file.reader_view(); + select_file.reader_view(); select_file.event_bind(); - }, + }, /** - * @description 固定表头 - * @param {string} el DOM选择器 - * @return void - */ - $fixed_table_thead:function(el){ - $(el).scroll(function(){ - var scrollTop = this.scrollTop; - this.querySelector('thead').style.transform = 'translateY(' + scrollTop + 'px)'; - }); - }, + * @description 固定表头 + * @param {string} el DOM选择器 + * @return void + */ + $fixed_table_thead:function(el){ + $(el).scroll(function(){ + var scrollTop = this.scrollTop; + this.querySelector('thead').style.transform = 'translateY(' + scrollTop + 'px)'; + }); + }, /** * @description 请求封装 @@ -3034,113 +3036,289 @@ var bt_tools = { * @param {function|object} callback 回调函数/请求参数 * @param {function} callback1 回调函数/可为空 * @returns void 无 - */ + */ send:function(param1,param2,param3,param4,param5,param6){ - var params = {},success = null,error = null,config = [],param_one = ''; - $.each(arguments,function(index,items){ - config.push([items,typeof items]); - }); - function diff_data(i){ - try { - success = config[i][1] == "function"?config[i][0]:null; - error = config[(i+1)][1] == "function"?config[(i+1)][0]:null; - } catch (error){} - } - param_one = config[0]; - switch(param_one[1]){ - case "string": - $.each(config,function(index,items){ - var value = items[0],type = items[1]; - if(index > 1 && (type == "boolean" || type == "string" || type == "object")){ - var arry = param_one[0].split('/'); - params['url'] = '/'+ arry[0] +'?action=' + arry[1]; - params['load'] = value; - if(type == "object"){ - params['load'] = value.load; - params['tips'] = value.tips; - params['verify'] = value.verify; - } - return false; - }else{ - params['url'] = param_one[0]; - } + var params = {},success = null,error = null,config = [],param_one = ''; + $.each(arguments,function(index,items){ + config.push([items,typeof items]); }); - if(config[1][1] === "object"){ - params['data'] = config[1][0]; - diff_data(2); - }else{ - diff_data(1); + function diff_data(i){ + try { + success = config[i][1] == "function"?config[i][0]:null; + error = config[(i+1)][1] == "function"?config[(i+1)][0]:null; + } catch (error){} } - break; - case 'object': - params['url'] = param_one[0].url; - params['data'] = param_one[0].data || {}; - $.each(config,function(index,items){ - var value = items[0],type = items[1]; - if(index > 1 && (type == "boolean" || type == "string" || type == "object")){ - params['load'] = items; - if(type == "object"){ - params['load'] = value.load; - params['tips'] = value.tips; + param_one = config[0]; + switch(param_one[1]){ + case "string": + $.each(config,function(index,items){ + var value = items[0],type = items[1]; + if(index > 1 && (type == "boolean" || type == "string" || type == "object")){ + var arry = param_one[0].split('/'); + params['url'] = '/'+ arry[0] +'?action=' + arry[1]; + params['load'] = value; + if(type == "object"){ + params['load'] = value.load; + params['tips'] = value.tips; + params['verify'] = value.verify; + } + return false; + }else{ + params['url'] = param_one[0]; + } + }); + if(config[1][1] === "object"){ + params['data'] = config[1][0]; + diff_data(2); + }else{ + diff_data(1); + } + break; + case 'object': + params['url'] = param_one[0].url; + params['data'] = param_one[0].data || {}; + $.each(config,function(index,items){ + var value = items[0],type = items[1]; + if(index > 1 && (type == "boolean" || type == "string" || type == "object")){ + params['load'] = items; + if(type == "object"){ + params['load'] = value.load; + params['tips'] = value.tips; + } + return true; + } + }); + if(config[1][1] === "object"){ + params['data'] = config[1][0]; + diff_data(2); + }else{ + diff_data(1); + } + break; + } + if(params.load) params.load = this.load(params.load); + $.ajax({ + type:params.type|| "POST", + url:params.url, + data:params.data || {}, + dataType: params.dataType || "JSON", + complete:function(){ + if(params.load) params.load.close(); + }, + success:function (res){ + if(params.verify){ + if(success) success(res); + return false; + } + if(typeof res === "string"){ + layer.msg(res,{icon:2,time:0,closeBtn:2}); + return false; + } + if(params.bacth){ + if(success) success(res); + return false; + } + if(res.status === false){ + bt_tools.msg(res); + return false; + } + if(params.tips){ + bt_tools.msg(res); + } + if(success) success(res); } - return true; - } + // error:function(er){ + // if(error) error(er); + // layer.closeAll('dialog'); + // layer.closeAll('loading'); + // layer.msg('Service response error:'+ er.status +'
                  error msg:'+er.statusText+'
                  URL:' + params.url+'
                  param:' + JSON.stringify(params.data) ,{icon:2,time:0,closeBtn:2}); + // } }); - if(config[1][1] === "object"){ - params['data'] = config[1][0]; - diff_data(2); - }else{ - diff_data(1); - } - break; - } - if(params.load) params.load = this.load(params.load); - $.ajax({ - type:params.type|| "POST", - url:params.url, - data:params.data || {}, - dataType: params.dataType || "JSON", - complete:function(){ - if(params.load) params.load.close(); - }, - success:function (res){ - if(params.verify){ - if(success) success(res); - return false; - } - if(typeof res === "string"){ - layer.msg(res,{icon:2,time:0,closeBtn:2}); - return false; - } - if(params.bacth){ - if(success) success(res); - return false; - } - if(res.status === false){ - bt_tools.msg(res); - return false; - } - if(params.tips){ - bt_tools.msg(res); - } - if(success) success(res); - }, - error:function(er){ - if(error) error(er); - layer.closeAll('dialog'); - layer.closeAll('loading'); - layer.msg('Service response error:'+ er.status +'
                  error msg:'+er.statusText+'
                  URL:' + params.url+'
                  param:' + JSON.stringify(params.data) ,{icon:2,time:0,closeBtn:2}); - } - }); - }, -}; + }, -$.fn.serializeObject = function(){ + /** + * @description 命令行输入 + */ + command_line_output:function(config){ + var _that = this,uuid = bt.get_random(15); + /** + * @description 渲染 + * @param config + * @return {object} + * @constructor + */ + function ReaderCommand(config) { + var that = this; + for (var key in _that.commandConnectionPool) { + var item = _that.commandConnectionPool[key],element = $(item.config.el) + if(config.shell === item.config.shell && element.length){ + item.el = element + return item + } + } + if(typeof config === "undefined") config = {} + this.config = $.extend({route:'/sock_shell'},config) + this.xterm_config = $.extend(this.xterm_config,this.config.xterm) + this.el = $(this.config.el); + this.open = config.open; + this.close = config.close; + this.message = config.message; + if(!this.config.hasOwnProperty('el')){ + _that.msg({msg:'请输入选择器element,不可为空',status:false}) + return false; + } + if(!this.config.hasOwnProperty('shell')){ + _that.msg({msg:'请输入命令,不可为空',status:false}) + return false; + } + if(this.config.hasOwnProperty('time')){ + setTimeout(function(){ + that.close_connect() + },this.config.time) + } + this.init() + } + ReaderCommand.prototype ={ + socket:null, //websocket 连接保持的对象 + socketToken:null, + timeout:0, // 连接到期时间,为0代表永久有效 + monitor_interval:2000, + element_detection:null, + uuid:uuid, + fragment:[], + error:0, + /** + * @description 程序初始化 + */ + init:function(){ + var oldUUID = bt.get_cookie('commandInputViewUUID'),that = this; + if(!this.el[0]){ + if(this.error > 10) return false; + setTimeout(function(){ + that.init() + this.error ++; + },2000) + return false; + } + this.error = 0 + if(this.el[0].localName !== 'pre'){ + this.el.append('
                  ');
                  +                    this.el = this.el.find('pre');
                  +                    this.config.el = this.config.el +' pre'
                  +                }else{
                  +                    this.el.addClass('command_output_pre');
                  +                }
                  +                if(Array.isArray(this.config.area)){
                  +                    this.el.css({width:this.config.area[0],height:this.config.area[1]})
                  +                }else{
                  +                    this.el.css({width:'100%',height:'100%'})
                  +                }
                  +                if(oldUUID && typeof _that.commandConnectionPool[oldUUID] != "undefined"){
                  +                    _that.commandConnectionPool[oldUUID].close_connect();
                  +                    delete _that.commandConnectionPool[oldUUID];
                  +                }
                  +                bt.set_cookie('commandInputViewUUID',this.uuid);
                  +                this.element_detection = setInterval(function(){
                  +                    if(!$(that.config.el).length){
                  +                        clearInterval(that.element_detection)
                  +                        that.close_connect();
                  +                    }
                  +                },1 * 60 *1000)
                  +                this.set_full_screen()
                  +                this.create_websocket_connect(this.config.route,this.config.shell)
                  +                this.monitor_element()
                  +            },
                  +            /**
                  +             * @description 创建websocket连接
                  +             * @param {string} url websocket连接地址
                  +             * @param {string} shell 需要传递的命令
                  +             */
                  +            create_websocket_connect:function(url,shell){
                  +                var that = this;
                  +                this.socket = new WebSocket((location.protocol === 'http:' ? 'ws://' : 'wss://') + location.host + url)
                  +                this.socket.addEventListener('open',function(ev){
                  +                    if(!this.socketToken){
                  +                        var _token = document.getElementById('request_token_head').getAttribute('token');
                  +                        this.socketToken = {'x-http-token':_token}
                  +                    }
                  +                    this.send(JSON.stringify(this.socketToken))
                  +                    this.send(shell)
                  +                    if(that.open) that.open()
                  +                });
                  +                this.socket.addEventListener('close',function(ev){
                  +                    if(ev.code !== 1000){
                  +                        that.socket = that.create_websocket_connect(that.config.route,that.config.shell)
                  +                    }
                  +                    if(that.close) that.close(ev)
                  +                });
                  +                this.socket.addEventListener('message',function(ws_event){
                  +                    var result = ws_event.data
                  +                    if(!result) return;
                  +                    that.refresh_data(result)
                  +                    if(that.message) that.message(result)
                  +
                  +                })
                  +                return this.socket
                  +            },
                  +
                  +            /**
                  +             * @description 设置全屏视图
                  +             */
                  +            set_full_screen:function(){
                  +// 1
                  +            },
                  +
                  +            /**
                  +             * @description 刷新Pre数据
                  +             * @param {object} data 需要插入的数据
                  +             */
                  +            refresh_data:function(data){
                  +                this.fragment.push(data)
                  +                if(this.fragment.length >= 300){
                  +                    this.fragment.splice(0,150)
                  +                    this.el.html(this.fragment.join(''))
                  +                }else{
                  +                    this.el.append(data)
                  +                }
                  +                this.el.scrollTop(this.el[0].scrollHeight)
                  +            },
                  +
                  +            /**
                  +             * @description 监听元素状态,判断是否移除当前的ws连接
                  +             *
                  +             */
                  +            monitor_element:function(){
                  +                var that = this;
                  +                this.monitor_interval = setInterval(function(){
                  +                    if(!that.el.length){
                  +                        that.close_connect()
                  +                        clearInterval(that.monitor_interval)
                  +                    }
                  +                }, that.config.monitorTime || 2000)
                  +            },
                  +
                  +            /**
                  +             * @description 断开命令响应和websocket连接
                  +             */
                  +            close_connect:function(){
                  +                this.socket.send('')
                  +                this.socket.close()
                  +                delete _that.commandConnectionPool[this.uuid];
                  +            }
                  +        }
                  +        this.commandConnectionPool[uuid] = new ReaderCommand(config)
                  +        return this.commandConnectionPool[uuid]
                  +    }
                  +};
                  +$.fn.serializeObject = function () {
                       var hasOwnProperty = Object.prototype.hasOwnProperty;
                  -    return this.serializeArray().reduce(function(data,pair){
                  -        if(!hasOwnProperty.call(data,pair.name)){
                  -            data[pair.name]=pair.value;
                  +    return this.serializeArray().reduce(function (data, pair) {
                  +        if (!hasOwnProperty.call(data, pair.name)) {
                  +            data[pair.name] = pair.value;
                           }
                           return data;
                  -    },{});
                  +    }, {});
                   };
                  +
                  +
                  +
                  diff --git a/BTPanel/static/js/tools.min.js b/BTPanel/static/js/tools.min.js
                  index 27e0fdf5..00c16db4 100644
                  --- a/BTPanel/static/js/tools.min.js
                  +++ b/BTPanel/static/js/tools.min.js
                  @@ -1,3 +1 @@
                  -var bt_tools={table:function(e){function t(e){this.config=e,this.$load()}return t.prototype={style_list:[],event_list:{},checkbox_list:[],batch_active:{},event_rows_model:{},data:[],page:"",column:[],batch_thread:[],random:bt.get_random(5),init:!1,checked:!1,$load:function(){var e=this,t=$('');this.config.init&&this.config.init(this),$(this.config.el).addClass("bt_table").append(t),t.focus(function(){return e.checked=!0,!1}).blur(function(t){e.checked=!1,e.checked_blur&&e.checked_blur(t)}),this.config.minWidth&&this.style_list.push({className:this.config.el+" table",css:"min-width:"+this.config.minWidth}),this.config.tootls?this.$reader_tootls(this.config.tootls):0===$(e.config.el+".divtable").length&&$(e.config.el).append('
                  '),this.$reader_content(),void 0!==e.config.url?this.$refresh_table_list():void 0!==this.config.data?this.$reader_content(this.config.data):alert(lan.public.miss_data_or_url),this.config.methods&&$.extend(this,this.config.methods)},$refresh_table_list:function(e){var t,i=this;e&&(t=bt.load(lan.database.get_data)),this.$http(function(a,s){e&&t.close(),i.$reader_content(a,s)})},$active_focus:function(e){var t=this;$("#checked_"+t.random).focus(),this.checked_blur=function(i){setTimeout(function(){e&&e(i),delete t.checked_blur},200)}},$reader_content:function(e,t){var i=this,a="",s="",n=0,l=this.config.column,c={},o=$(i.config.el+" .checkbox_"+i.random);e=e||[],this.data=e,o.length&&(o.removeClass("active selected"),i.checkbox_list=[],i.$set_batch_view());do{var r=e[n],d=0;e.length>0&&(s+="");for(var p=0;p"+("checkbox"==h.type?'':""+h.title+"")+(h.sort?'':"")+"",0===n&&(!c[_]&&h.sort&&(c[_]={event:this.config.sortEvent,eventType:"click",type:"sort"}),c[f]||(c[f]={event:h.checked,eventType:"click",type:"checkbox"}))}if(void 0!==r){var v="",b="event-"+h.fid+"-"+this.random;h.template?v=i.$custom_template_render(h,r,p):(v=this.$reader_column_type(h,r),c=$.extend(c,v[1]),v=v[0]),s+=""+v+"",0===n&&!c[b]&&h.event&&(c[b]={event:h.event,eventType:"click",type:"rows"})}}}e.length>0&&(s+=""),0==e.length&&(s+=''+(this.config.default||lan.public.empty)+""),n++}while(n'+a+""+s+"
                  "),this.init=!0,this.config.success&&this.config.success(this)},$custom_template_render:function(e,t,i){var a="event-"+e.fid+"-"+this.random,s=e.template(t,i),n=$(s);return n.length>0?template=n.addClass(a)[0].outerHTML:"text"===e.type?template=''+s+"":template=''+s+"",template},$modify_row_data:function(e){this.event_rows_model.rows=$.extend(this.event_rows_model.rows,e);var t=this.event_rows_model,i=null;i=void 0!==t.model.template?$(this.$custom_template_render(t.model,t.rows,t.index)):$(this.$reader_column_type(t.model,t.rows)[0]),t.el.replaceWith(i),t.el=i},$batch_success_table:function(e){var t=this;bt.open({type:1,title:e.title,area:e.area||["380px","350px"],shadeClose:!1,closeBtn:2,content:e.content||'
                  '+e.title+" "+lan.public.success+'
                  "+e.html+"
                  '+e.th+''+lan.public.result+"
                  ",success:function(){t.$fixed_table_thead(".fiexd_thead")}})},$delete_table_row:function(e){this.data.splice(e,1),this.$reader_content(this.data)},$fixed_table_thead:function(e){$(e).scroll(function(){var e=this.scrollTop;this.querySelector("thead").style.transform="translateY("+e+"px)"})},$set_batch_view:function(){var e=$(this.config.el+" .bt_select_value"),t=$(this.config.el+" .bt_table_select_group").next();if(void 0!==this.config.batch){t=$(this.config.el+" .set_batch_option");if(void 0!==this.config.batch.config)this.checkbox_list.length>0?t.removeClass("bt-disabled btn-default").addClass("btn-success").text(lan.public.please_choose+this.batch_active.title+"("+lan.public.selected+this.checkbox_list.length+")"):t.addClass("bt-disabled btn-default").removeClass("btn-success").text(lan.public.please_choose+this.batch_active.title);else{e=$(this.config.el+" .bt_select_value");this.checkbox_list.length>0?(t.removeClass("bt-disabled btn-default").addClass("btn-success").prev().removeClass("bt-disabled"),e.find("em").html("("+lan.public.selected+this.checkbox_list.length+")")):(t.addClass("bt-disabled btn-default").removeClass("btn-success").prev().addClass("bt-disabled"),e.children().eq(0).html(lan.public.please_choose+""),e.next().find("li").removeClass("active"),this.batch_active={})}}},$reader_column_type:function(e,t){var i=t[e.fid],a={},s="",n=[],l=this;switch(e.type){case"text":n=[i,a];break;case"checkbox":n=['',a];break;case"password":s="ico_"+l.random+"_";var c='**********';e.eye_open&&(c+='',a[s+"eye_open"]||(a[s+"eye_open"]={type:"eye_open_password"})),e.copy&&(c+='',a[s+"copy"]||(a[s+"copy"]={type:"copy_password"})),n=[c,a];break;case"link":s="click_"+e.fid+"_"+this.random,!a[s]&&e.event&&(a[s]={event:e.event,type:"rows"}),n=[''+i+"",a];break;case"input":blurName="blur_"+e.fid+"_"+this.random,keyupName="keyup_"+e.fid+"_"+this.random,!a[blurName]&&e.blur&&(a[blurName]={event:e.blur,eventType:"blur",type:"rows"}),!a[keyupName]&&e.keyup&&(a[keyupName]={event:e.keyup,eventType:"keyup",type:"rows"}),n=['',a];break;case"status":var o="";s="click_"+e.fid+"_"+this.random,$.each(e.config.list,function(e,t){t[0]===i&&(o=t)}),!a[s]&&e.event&&(a[s]={event:e.event,type:"rows"}),n=['-1?"":o[2])+'" style="'+(o[2].indexOf("#")>-1?"color:"+o[2]+";":"")+'" href="javascript:;">'+o[1]+""+(e.config.icon?'':"")+"",a];break;case"switch":break;case"group":var r="";$.each(e.group,function(i,n){if(s=(e.fid?e.fid:"group")+"_"+i+"_"+l.random,n.template){var c=n.template(t,l),o=$(c);o.length>0?r+=o.addClass(s)[0].outerHTML:r+=''+c+""}else r+='"+n.title+"";r+=e.group.length-1!=i?" | ":"",!a[s]&&n.event&&(a[s]={event:n.event,type:"rows"})}),n=[r,a];break;default:n=[i,a]}return n},$reader_tootls:function(e){function t(e,t){var i=bt.load(e.title+lan.site.executing),s={},n=a.$get_data_batch_list(e.paramId,t);e.beforeRequest?s[e.paramName]=e.beforeRequest(t):s[e.paramName]=n.join(","),bt_tools.send({url:e.url||a.config.batch.url,data:$.extend(e.param||{},s)},function(s){if(i.close(),!s.status)return!1;if(void 0===e.tips||e.tips){var n="";$.each(s.error,function(e,t){n+=""+e+'
                  '+t+"
                  "}),$.each(s.success,function(e,t){n+=""+t+'
                  '+lan.public.success+"
                  "}),a.$batch_success_table({title:e.title,th:e.theadName,html:n}),a.$refresh_table_list(!0)}e.success&&e.success(s,t,a)})}function i(e,i,a){e.callback?e.callback({loadT:0,config:{},check_list:i,bacth_status:!0,start_batch:function(t,i){var a=this;e.load&&(this.loadT=layer.msg(lan.public.executeing+e.title+','+lan.public.schedule+":0/"+this.check_list.length+","+lan.public.please_wait+(e.clear?'cancel':""),$.extend({icon:16,skin:"batch_tips",shade:.3,time:0},e.clear?{area:"420px"}:{})),$("#layui-layer"+a.loadT).on("click",".clear_batch",function(){a.clear_bacth()})),this.config={param:t,url:e.url},this.bacth(i)},bacth:function(t,s){var n=this,l={};if("function"==typeof t&&(s=t,t=0),t'+lan.public.executeing+e.title+','+lan.public.schedule+":"+t+"/"+n.check_list.length+","+lan.public.please_wait+(e.clear?'cancel':"")),bt_tools.send({url:this.config.url,data:this.config.param,bacth:!0},function(e){$.extend(n.check_list[t],{request:{status:"boolean"==typeof e.status&&e.status,msg:e.msg||lan.public.request_error}}),t++,n.bacth(t,s)})}else a&&a(),s(this.check_list),layer.close(this.loadT)},clear_bacth:function(){this.bacth_status=!1,layer.close(this.loadT)}}):e.confirm?t(e,i):e.confirmVerify?bt.show_confirm(e.title+lan.public.in_bulk,e.title+lan.public.in_bulk+","+lan.public.risk_prompt,t):bt.confirm({title:e.title+lan.public.in_bulk,msg:e.title+lan.public.in_bulk+","+lan.public.risk_prompt},function(){t&&t(e,i)})}for(var a=this,s={},n=0;n ',c.list&&$.each(c.list,function(e,t){'
                • "}),t.init&&setTimeout(function(){t.init(i)},400)):l+='",s[i]||(s[i]={event:t.event,type:"button"})});break;case"search":this.config.search=c;var o="search_input_"+this.random,r="search_btn_"+this.random;l='',s[o]||(s[o]={eventType:"keyup",type:"search_input"}),s[r]||(s[r]={type:"search_btn"});break;case"batch":this.config.batch=c;var d=[],p="",h=c.config;void 0!==c.config?(a.batch_active=h,$(a.config.el).on("click",".set_batch_option",function(e){for(var s=[],n=0;n'+i.title+""}),delete t.group):(d.push(t),p+='
                • '+t.title+"
                • ")}),$(a.config.el).on("click",".bt_table_select_group .bt_select_value",function(e){var t=$(this).parent(),i=t.find(".bt_selects"),s=t.offset(),n=a.$get_win_area();return t.hasClass("bt-disabled")?(layer.tips(a.config.batch.disabledSelectValue,t,{tips:[1,"red"],time:2e3}),!1):(t.hasClass("active")?t.removeClass("active"):t.addClass("active"),i.height()>n[1]-s.top?i.addClass("top"):i.removeClass("top"),$(document).one("click",function(){return $(a.config.el).find(".bt_table_select_group").removeClass("active"),!1}),!1)}),$(a.config.el).on("click",".bt_table_select_group .item",function(e){var t=$(this).text(),i=$(this).index();$(this).addClass("active").siblings().removeClass("active"),$(a.config.el+" .bt_select_tips").html(t+lan.public.in_bulk+"("+lan.site.have_been_selected+a.checkbox_list.length+")"),a.batch_active=d[i],a.checked||$(".bt_table_select_group").removeClass("active")}),$(a.config.el).on("click",".set_batch_option",function(e){var s=[],n=a.batch_active;if($(this).hasClass("bt-disabled"))return layer.tips(a.config.batch.disabledSelectValue,$(this),{tips:[1,"red"],time:2e3}),!1;for(var l=0;l'+(void 0!==c.config?'":'
                  '+lan.public.select_opt_type+'
                    '+p+'
                  ")+"";break;case"page":this.config.page=c;var _=bt.get_cookie(this.config.cookiePrefix+"_"+this.config.page.numberParam);this.config.cookiePrefix&&_&&(this.config.page.number=_),l=this.$reader_page(this.config.page,'
                  1 '+lan.public_backup.total+"
                  ")}if(l){var f=$(a.config.el+" .tootls_"+c.positon[1]);if(f.length){var u=f.find(".pull-"+c.positon[0]);u.append(l)}else{var v='
                  '+("left"==c.positon[0]?l:"")+'
                  '+("right"==c.positon[0]?l:"")+"
                  ";"top"===c.positon[1]?($(a.config.el).append(v),0===$(a.config.el+" .divtable").length&&$(a.config.el).append('
                  ')):(0===$(a.config.el+" .divtable").length&&$(a.config.el).append('
                  '),$(a.config.el).append(v))}}}this.init||this.$event_bind(s)},$get_data_batch_list:function(e,t){var i=[];return $.each(t||this.data,function(t,a){i.push(a[e])}),i},$reader_page:function(e,t){var i=this,a=$(t),s="",n={};if(a.find("a").addClass("page_link_"+this.random),s+=a.html(),e.numberStatus){var l="page_select_"+this.random;s+='",n[l]={eventType:"change",type:"page_select"}}if(e.jump){var c="page_jump_input-"+this.random,o="page_jump_btn_"+this.random;s+='
                  '+lan.public.jump_to_page+'
                  ",n[c]={eventType:"keyup",type:"page_jump_input"},n[o]={type:"page_jump_btn"}}return n["page_link_"+this.random]={type:"cut_page_number"},i.config.page.total=parseInt(a.find(".Pcount").html().match(/([0-9]*)/g)[1]),i.$event_bind(n),'
                  '+s+"
                  "},$dynamic_merge_style:function(e,t){var i="";return $.each(e,function(e,t){switch(e){case"align":i+="text-align:"+t+";";break;case"width":i+="width:"+("string"==typeof t?t:t+"px")+";";break;case"style":i+=t;break;case"minWidth":i+="min-width:"+("string"==typeof t?t:t+"px")+";";break;case"maxWidth":i+="max-width:"+("string"==typeof t?t:t+"px")+";"}}),{index:t,css:i}},$event_bind:function(e){var t=this;$.each(e,function(e,i){if(t.event_list[e]&&t.event_list[e].eventType===i.eventType)return!0;t.event_list[e]=i,$(t.config.el).on(i.eventType||"click","."+e,function(a){var s=$(this).parents("tr").index(),n=$(this).data(),l=[];switch(i.type){case"rows":t.event_rows_model={el:$(this),model:t.config.column[$(this).parents("td").index()],rows:t.data[s],index:s},l=[t.event_rows_model.rows,t.event_rows_model.index,a,e,t];break;case"sort":var c=t.config.column[n.index];$(this).hasClass("sort-active")&&$(".sort_"+t.random+" .sort-active").data({sort:"desc"}),$(".sort_"+t.random).removeClass("sort-active").find(".glyphicon").removeClass("glyphicon-triangle-top").addClass("glyphicon-triangle-bottom"),$(this).addClass("sort-active"),"asc"==n.sort?($(this).data({sort:"desc"}),$(this).find(".glyphicon").removeClass("glyphicon-triangle-top").addClass("glyphicon-triangle-bottom")):($(this).data({sort:"asc"}),$(this).find(".glyphicon").removeClass("glyphicon-triangle-bottom").addClass("glyphicon-triangle-top")),t.config.sort=t.config.sortParam({name:c.fid,sort:n.sort}),t.$refresh_table_list(!0);break;case"checkbox":var o=$(t.config.el+' [data-checkbox="all"]'),r=$(t.config.el+" tbody .checkbox_"+t.random);null==n.checkbox?$(this).hasClass("active")?($(this).removeClass("active"),t.checkbox_list.splice(t.checkbox_list.indexOf(s),1),t.checkbox_list.length>0?o.addClass("selected").removeClass("active"):o.removeClass("selected active")):($(this).addClass("active"),t.checkbox_list.push(s),t.data.length===t.checkbox_list.length?o.addClass("active").removeClass("selected"):t.checkbox_list.length>0&&o.addClass("selected")):t.checkbox_list.length===t.data.length?(t.checkbox_list=[],r.removeClass("active selected").next().prop("checked","checked"),o.removeClass("active")):(r.each(function(e,i){$(this).hasClass("active")||($(this).addClass("active").next().prop("checked","checked"),t.checkbox_list.push(e))}),o.removeClass("selected").addClass("active")),t.$set_batch_view();break;case"button":l.push(a,t);break;case"search_focus":var d=$(t.config.el+" .bt_search_tips");$(t.config.el+" .bt_search_tips").length>0&&d.remove();break;case"search_input":if(13==a.keyCode)return $(t.config.el+" .search_btn_"+t.random).click(),!1;break;case"search_btn":var p=$(t.config.el+" .search_input"),h=$(t.config.el+" .search_input").val();t.config.search.value=h,p.append('
                  '+h+'
                  '),t.$refresh_table_list(!0);break;case"page_select":var _=parseInt($(this).val());return t.config.page.number=_,t.config.page.page=1,t.$refresh_table_list(!0),!1;case"page_jump_input":return 13==a.keyCode&&($(t.config.el+" .page_jump_btn_"+t.random).click(),$(this).focus()),!1;case"page_jump_btn":var f=parseInt($(t.config.el+" .page_jump_input-"+t.random).val()),u=Math.ceil(t.config.page.total/t.config.page.number);f>u&&(f=t.config.page.page),t.config.page.page=f,t.$refresh_table_list(!0);break;case"cut_page_number":var v=parseInt($(this).attr("href").match(/([0-9]*)$/)[0]);return t.config.page.page=v,t.$refresh_table_list(!0),!1;case"eye_open_password":return $(this).hasClass("glyphicon-eye-open")?($(this).addClass("glyphicon-eye-close").removeClass("glyphicon-eye-open"),$(this).prev().text(t.data[s].password)):($(this).addClass("glyphicon-eye-open").removeClass("glyphicon-eye-close"),$(this).prev().html("**********")),!1;case"copy_password":return bt.pub.copy_pass(t.data[s].password),!1}i.event&&i.event.apply(this,l)})})},$style_bind:function(e,t){var i="",a=this;$.each(e,function(e,t){""!=t.css&&(t.className?i+=t.className+"{"+t.css+"}":i+=a.config.el+" thead th:nth-child("+(t.index+1)+"),"+a.config.el+" tbody tr td:nth-child"+(t.span?" span":"")+"("+(t.index+1)+"){"+t.css+"}")}),0==$("#bt_table_"+a.random).length&&$(a.config.el).append('")},$get_win_area:function(){return[window.innerWidth,window.innerHeight]},$http:function(e){var t={},i=this.config,a=i.page,s=i.search,n=i.sort||{};a&&(t[a.numberParam]=a.number,t[a.pageParam]=a.page,this.config.cookiePrefix&&bt.set_cookie(this.config.cookiePrefix+"_"+a.numberParam,a.number)),s&&(t[s.searchParam]=s.value),this.config.beforeRequest&&(i.param=this.config.beforeRequest(i.param)),bt_tools.send({url:i.url,data:$.extend(i.param,t,n)},function(t){if(i.dataFilter){var a=i.dataFilter(t);e&&e(a.data,a.page)}else e&&e(t.data,t.page)})}},new t(e)},select_file:function(e,t){"string"==typeof e&&(e={path:e,type:2,title:lan.public.select_fileordir,ext:[],limit:""}),"function"==typeof e&&(type=t,t=e,e={path:bt.get_cookie("Path")}),"number"!=typeof type&&(type=0);var i=this,a={type:type,type_tips:0==type?lan.public.dir:1==type?lan.site.file:lan.public.fileordir,select_list:[],select_path:bt.get_cookie("Path")||("Windows"==bt.os?setup_path:"/www/wwwroot"),select_config:{},scroll_width:0,reader_view:function(){var t=this;this.scroll_width=a.getScrollbarWidth(),layer.open({type:1,title:e.title||lan.public.select+t.type_tips,shadeClose:!1,closeBtn:1,area:["650px","550px"],content:'
                  '+lan.public.name+''+lan.public.modify_time+''+lan.site.redirect_type+'
                  文件修改时间类型
                  '+t.type_tips+'名:
                  ',success:function(){t.evnet_bind(),t.render_file_list(function(){t.set_path_width()}),$(".select_list_thaed").css("right",t.scroll_width+"px")}})},evnet_bind:function(){var e=this;$("#select_dir_list").on("click","tr",function(){var t=$(this).data("index");$(this).addClass("active").siblings().removeClass("active"),$('[name="select_name"]').val(e.select_list[t].filename)}),$(".select_list_body").on("scroll",function(e){var t=$(this).scrollTop(),i=$(this).scrollLeft();t>0?$(".select_list_shadow").show():$(".select_list_shadow").hide(),i>=0&&$(".select_list_thaed").css("left",4-i+"px"),e.stopPropagation(),e.preventDefault()}),$(".file_path_refresh").on("click",function(){e.render_file_list()}),$(".select_dir_list thead th .icon-drag").on("mousedown",function(t){var i=t.clientX,a=$(this).parent(),s=a.index(),n=a[0].clientWidth;parseInt($(this).parent().attr("data-min"));if(1===t.which){var l=function(t){var a=t.clientX,l=a-i,c=n+l;setTimeout(function(){e.set_select_width(s,"width:"+c+"px")},0)};$(document).on("mousemove",l).one("mouseup",function(){$(this).unbind(l),$(this).unbind(this)})}t.stopPropagation()}),$(".select_dir_list thead th>span").on("click",function(t){var i=$(this).parent(),a=i.data("type"),s=i.hasClass("active"),n=i.hasClass("sort");s?i.addClass("sort").removeClass("active"):n?i.addClass("active").removeClass("sort"):i.addClass("active"),i.siblings().removeClass("active sort"),e.render_file_list({sort:a,reverse:s?1:0}),t.stopPropagation()}),$(".search_path_views input").on("keyup",function(){$(this).val()})},set_path_width:function(e){var t=0,i=$(".file_dir_view")[0].offsetWidth,a=($(".file_dir_view .file_dir_item"),[]);t=0;$(".file_dir_view .file_dir_item").each(function(){a.push($(this)[0].offsetWidth)});for(var s=a.reverse(),n=0;n-1?"本地磁盘("+t.path.match(/[A-Z]+/)[0]+":)":t.path;a+='
                  '+i+"
                  "}),$.each(o,function(e,t){var i=bt.format_data(t.mtime),a="dir"==t.type?"文件夹":"文件";s+=' '+t.filename+" "+i+" "+("dir"==t.type?"文件夹":"文件")+" "}),$("#select_mount_list").html(a),$("#select_dir_list").html(s),t&&t(e)})},render_path_list:function(e,t){var i='
                  ',a="",s=e.split("/").splice(1),n=e.split("/")[0];"Windows"===bt.os?(0==s.length&&(s=[]),s.unshift('本地磁盘('+n+")")):("/"==e&&(s=[]),s.unshift("根目录"));for(var l=0;l '+s[l]+' ';$(".path_input").val("").attr("data-path",e);var c=$("#select_file_directory .file_path_input .file_dir_view");c.html(i),t&&t(e)},set_select_width:function(e,t){var i=".select_dir_list tbody td:nth-child("+(e+1)+")>span,.select_dir_list thead th:nth-child("+(e+1)+")>span",a=$("#th-index-"+e);a.length>0?a.html(i+"{"+t+"}"):$("#select_file_style").append('")},cut_style_object:function(e){var t={};e.split(";");return t},getScrollbarWidth:function(){var e,t,i=document.createElement("div"),a={width:"100px",height:"100px",overflowY:"scroll"};for(e in a)i.style[e]=a[e];return document.body.appendChild(i),t=i.offsetWidth-i.clientWidth,i.remove(),t}};a.reader_view()},form:function(e){function t(e){this.config=e,this.data=e.data||{},this.$load()}var i=this;return t.prototype={element:null,style_list:[],event_list:{},event_type:["click","event","focus","keyup","blur","change"],hide_list:[],form_element:{},form_config:{},random:bt.get_random(5),$load:function(){var e=this;e.el&&this.$reader_content(function(){e.$event_bind()})},$reader_content:function(e){var t=this,a="",s="";return $.each(t.config.form,function(e,i){a+=t.$reader_content_row(e,i)}),t.element=$('
                  '+a+"
                  "),s=$('
                  '),s.append(t.element),e&&e(),s[0].outerHTML},$reader_content_row:function(e,t){var a=this,s=t.help,n=this.config.formLabelWidth||t.formLabelWidth;return'
                  "+(t.label?'"+t.label+"":"")+'
                  "+a.$reader_form_element(t.group,e)+(s?'
                  "+s.list.join("
                  ")+"
                  ":"")+"
                  "},$reader_form_element:function(e,t){var i=this,a="";return Array.isArray(e)||(e=[e]),$.each(e,function(e,s){s.find_index=t,a+=i.$reader_form_find(s),i.form_config[s.name]=s}),a},$reader_form_element:function(e,t){var a=this,s="",n={};return Array.isArray(e)||(e=[e]),$.each(e,function(e,l){var c=a.$reader_style(l.style)+i.$verify(l.width,"width","style"),o=a.$verify_group(l,["name","value","placeholder","disabled","readonly","autofocus","autocomplete","min","max"]),r=a.$create_event_config(l),d="";switch(s+=l.label?''+l.label+"":"",void 0!==l.name&&(n[l.name]=r),l.type){case"text":case"checkbox":case"password":case"radio":case"number":var p="event_"+l.name+"_"+a.random,h="checkbox"===l.type;"radio"===l.type?$.each(l.label_tips,function(e,t){l.block&&(s+='
                  '),s+='',s+='",l.block&&(s+="
                  ")}):(l.block&&(s+='
                  '),s+='","checkbox"==l.type&&(s+='"),l.block&&(s+="
                  "),a.event_list[p]={click:{event:l.event}}),l.icon&&(s+='",n[l.name+"_icon"]={click:{type:"select_path",config:l}});break;case"textarea":if(s+='",$.each(["blur","focus","input"],function(e,t){if(l.tips){var i=null;switch(t){case"blur":i=function(e,t){""===$(this).val()&&$(this).next().show(),layer.close(t.tips.loadT)};break;case"focus":i=function(e,t){$(this).next().hide(),t.tips.loadT=layer.tips(_,$(this),{tips:[1,"#20a53a"],time:0,area:$(this).width()})}}}n[l.name][t]?n[l.name][t].added=i:n[l.name][t]={type:l.type,cust:!1,event:l[t],added:i}}),l.tips){var _="";_=void 0===l.tips.list?l.tips.text:l.tips.list.join("
                  "),s+='
                  "+_+"
                  ",n[l.name+"_tips"]={click:{type:"textarea_tips",config:l}}}break;case"select":s+=a.$reader_select(l,c,o,t),a.event_list.custom_select={click:{type:"custom_select",children:".bt_select_value"}},a.event_list.custom_select_item={click:{type:"custom_select_item",children:"li.item"}};break;case"link":d="event_"+bt.get_random(6),s+='
                  "+l.title+"",a.event_list[d]={click:{type:"link_event",event:l.event}};break;case"help":var f="";$.each(l.list,function(e,t){f+="
                • "+t+"
                • "}),s+='
                    "+f+"
                  "}a.form_config[l.name]=l}),$.extend(a.event_list,n),s},$create_event_config:function(e){var t={};return void 0===e.name?{}:($.each(this.event_type,function(i,a){e[a]&&(t["event"===a?"click":a]={type:e.type,event:e[a],cust:["select","checkbox","radio"].indexOf(e.type)>-1,config:e})}),t)},$reader_style:function(e){var t="";return"string"==typeof e?e:void 0===e?"":($.each(e,function(e,i){t+=e+":"+i+";"}),t)},$local_refresh:function(e,t){this.element.find("[data-name="+e+"]").replaceWith(this.$reader_form_find(t))},$reader_select:function(e,t,a,s){var n=this,l="",c="",o={};if(!Array.isArray(e.list)){var r=e.list;bt_tools.send({url:r.url,data:r.param||{}},function(t){!1!==t.status?(e.list=e.list.dataFilter?e.list.dataFilter(t):t,n.$replace_render_content(s)):bt.msg(t)})}return $.each(e.list,function(t,a){try{o=a.value===e.value?a:e.list[0]}catch(e){}l+='
                • '+a.title+"
                • ",c+='"}),!o.title&&Array.isArray(e.list)&&(o=e.list[0]),'
                  '+(o.title||"Getting data...")+'
                    '+(l||"")+"
                  "+(c||"")+"
                  "},$replace_render_content:function(e){var t=this,i=this.config.form[e];$("[data-form="+t.random+"]").find(".line:eq("+e+")").replaceWith(t.$reader_content_row(e,i))},$event_bind:function(e,t){var i=this,a={};i.element=$("object"==typeof e?i.element:"[data-form="+i.random+"]"),void 0===e&&(a=i.event_list),$.each(a,function(e,t){if($.isEmptyObject(t))return!0;$.each(t,function(t,a){var s="";s="boolean"==typeof a.cust?"["+(a.cust?"data-":"")+"name="+e+"]":"."+e,function(e,a){if(!1===e.onEvent){switch(e.type){case"input_checked":$(s).on("event"!=t?t:"click",function(t){e.event.apply(this,[t,i])})}return!0}i.element.on("event"!=t?t:"click",e.children?e.children:s,function(t){var s=i.$get_form_element(!0),n=i.$get_form_value(),l=i.form_config[a];switch(e.type){case"textarea_tips":$(this).hide().prev().focus();break;case"custom_select":if($(this).parent().hasClass("bt-disabled"))return!1;var c=$(this).next();return c.hasClass("show")?c.removeClass("show"):($(".bt_select_list").removeClass("show"),c.addClass("show")),$(document).click(function(){return i.element.find(".bt_select_list").removeClass("show"),$(this).unbind("click"),!1}),!1;case"custom_select_item":if(l=i.form_config[$(this).parents(".bt_select_updown").attr("data-name")],item_config=l.list[$(this).index()],$(this).hasClass("disabled"))return $(this).parent().removeClass("show"),item_config.tips&&layer.msg(item_config.tips,{icon:2}),!0;$(this).hasClass("active")||$(this).hasClass("disabled")||($(this).parent().prev().find(".bt_select_content").text($(this).text()),$(this).addClass("active").siblings().removeClass("active"),$(this).parent().next().val(item_config.value.toString()),$(this).parent().removeClass("show"),$(this).parent().next().trigger("change"));break;case"select_path":bt.select_path("event_"+$(this).prev().attr("name")+"_"+i.random,e.config.icon.select||"");break;case"checkbox":var o=$(this).is(":checked");o?$(this).prev().addClass("active"):$(this).prev().removeClass("active")}e.event&&e.event.apply(this,[n,s,i,l,t]),e.added&&e.added.apply(this,[t,l,s])})}(a,e)})}),t&&t()},$get_form_value:function(){return this.element.serializeObject()},$set_find_value:function(e,t){var i={},a=this;"string"!=typeof e?i=e:i[e]=t,$.each(i,function(e,t){a.form_element[e].val(t)})},$get_form_element:function(e){var t={},i=this;return e||$.isEmptyObject(i.form_element)?(this.element.find(":input").each(function(e){t[$(this).attr("name")]=$(this)}),i.form_element=t,t):i.form_element},$verify_group:function(e,t){var i="";return $.each(t,function(t,a){if(void 0===e[a])return!0;["disabled","readonly"].indexOf(a)>-1?i+=" "+(e[a]?a+'="'+a+'"':""):i+=" "+a+'="'+e[a]+'"'}),i},$verify_bind_event:function(e,t,i){var a={};return $.each(i,function(i,s){var n=t[s];n&&("object"==typeof a[e]?(Array.isArray(a[e])||(a[e]=[a[e]]),a[e].push({event:n,eventType:s})):a[e]={event:n,eventType:s})}),a},$verify:function(e,t,i){return e?!0===i?e?" "+t:"":"style"===i?t?t+":"+e+";":e:t?" "+t+'="'+e+'"':" "+e:""},$verify_form:function(){for(var e={},t=this.config.form,i=this.$get_form_value(),a=this.$get_form_element(!0),s=0;s'+i.title+"",s+='
                  '+(l?i.content:"")+"
                  "}),e.element=$('
                  '+a+'
                  '+s+"
                  "),e.element[0].outerHTML},$reader_find:function(){},$event_bind:function(){var e=this,t=e.theme,i=t.active||"active";e.el||(e.element=$("#tab_"+e.random)),e.element.on("click","."+t.nav.replace(/\s+/g,".")+" span",function(){var a=$(this).index(),s=e.config.list[a];$(this).addClass(i).siblings().removeClass(i),$("."+t.body+">div:eq("+a+")").addClass(i).siblings().removeClass(i),e.active=a,s.init||($("."+t.body+">div:eq("+a+")").html(s.content),s.success&&s.success(),s.init=!0)})}},new t(e)},load:function(e){var t=layer.msg(e+",please wait...",{icon:16,time:0,shade:.3});return!0===e&&(t=layer.load()),{close:function(){layer.close(t)}}},open:function(e){var t={},i=null,a=null;if(t=$.extend({type:1,area:"640px",closeBtn:2,btn:["Yes","No"]},e),"object"==typeof t.content){var s=t.content;a=bt_tools.form(s),t.success=function(e,i){a.$event_bind(),void 0!==t.init&&t.init(e,i)},t.yes=function(t,i){var s=a.$verify_form();if(!s)return!1;if(void 0!==e.yes){var n=e.yes.apply(a,[s,t,i]);if(!n)return!1}},t.content=a.$reader_content()}return i=layer.open(t),{close:function(){layer.close(i)},form:a}},msg:function(e,t){var i=null,a="",s={};return"object"==typeof e&&"boolean"==typeof e.status&&(a=e.msg,s={icon:e.status?1:2}),"string"==typeof e&&(a=e,s={icon:void 0!==t?t:1}),i=layer.msg(a,s),{close:function(){layer.close(i)}}},$verify:function(e,t,i){return e?!0===i?e?" "+t:"":"style"===i?t?t+":"+e+";":e:t?" "+t+'="'+e+'"':" "+e:""},select_path:function(e,t,i,a){"number"!=typeof i&&(i=1),"number"!=typeof a&&(a=!1),bt.set_cookie("Path","/www/server/panel/BTPanel/static");var s=this,n={type:i,type_tips:0==i?"目录":1==i?"文件":"目录或文件",type_limit:0==i?"dir":1==i?"file":"all",select_list:[],select_path:bt.get_cookie("Path")||("Windows"==bt.os?setup_path:"/www/wwwroot"),select_config:{},scroll_width:0,file_path:bt.get_cookie("Path"),file_operating:[],area:[window.innerWidth,window.innerHeight],reader_view:function(){var t=this;this.scroll_width=n.getScrollbarWidth(),layer.open({type:1,title:e.title||"选择"+t.type_tips,shadeClose:!1,closeBtn:2,area:["650px","555px"],content:'
                  名称修改时间类型
                  文件修改时间类型
                  '+t.type_tips+'名:
                  ',success:function(){t.render_file_list(),$(".select_list_thaed").css("right",t.scroll_width+"px")}})},render_file_list:function(e,t){var i="",a="",n=this,l={path:this.select_path,sort:"type",disk:!0};void 0===e&&(e=l),"function"==typeof e&&(t=e,e=l),n.select_config=$.extend(l,e),s.$http("GetDir",n.select_config,function(e){var s=e.DISK,l=$.merge(n.data_reconstruction(e.DIR,"DIR"),n.data_reconstruction(e.FILES));n.select_list=l,n.render_path_list(),$.each(s,function(e,t){var a="/"==t.path?"根目录":t.path.indexOf(":/")>-1?"本地磁盘("+t.path.match(/[A-Z]+/)[0]+":)":t.path;i+='
                  '+a+"
                  "}),$.each(l,function(e,t){if(0==n.type&&t.type!=n.type_limit)return!0;var i=bt.format_data(t.mtime),s="dir"==t.type?"文件夹":"文件";a+=' '+t.filename+" "+i+" "+("dir"==t.type?"文件夹":"文件")+" "}),$("#select_mount_list").html(i),$("#select_dir_list").html(a),t&&t(e)})},data_reconstruction:function(e,t,i){if(e.length<1)return[];var a=[];return $.each(e,function(e,i){var s=i.split(";"),n="",l=s[0].split("."),c=l[l.length-1];switch(s[0]){case".user.ini":n="PS: PHP用户配置文件(防跨站)!";break;case".htaccess":n="PS: Apache用户配置文件(伪静态)";break;case"swap":n="PS: 宝塔默认设置的SWAP交换分区文件"}-1!=s[0].indexOf("Recycle_bin")&&(n="PS: 回收站目录,勿动!"),-1!=s[0].indexOf(".upload.tmp")&&(n="PS: 宝塔文件上传临时文件,重新上传从断点续传,可删除"),a.push({caret:"1"==s[8],down_id:s[9],ext:"DIR"==t?"":c,filename:s[0],mtime:s[2],ps:n||s[10],size:s[1],type:"DIR"==t?"dir":"file",user:s[3],root_level:s[4]})}),a},render_path_list:function(e){var t=this,i='
                  ',a="",s=this.file_path.split("/").splice(1),n=this.file_path.split("/")[0];"Windows"===bt.os?(0==s.length&&(s=[]),s.unshift('本地磁盘('+n+")")):("/"==this.file_path&&(s=[]),s.unshift("根目录"));for(var l=0;l '+s[l]+' ';$(".path_input").val("").attr("data-path",this.file_path);var c=$(".file_path_input .file_dir_view");c.html(i),c.attr("data-width",c.width()),t.set_dir_view_resize()},set_select_width:function(e,t){var i=".select_dir_list tbody td:nth-child("+(e+1)+")>span,.select_dir_list thead th:nth-child("+(e+1)+")>span",a=$("#th-index-"+e);a.length>0?a.html(i+"{"+t+"}"):$("#select_file_style").append('")},cut_style_object:function(e){var t={};e.split(";");return t},getScrollbarWidth:function(){var e,t,i=document.createElement("div"),a={width:"100px",height:"100px",overflowY:"scroll"};for(e in a)i.style[e]=a[e];return document.body.appendChild(i),t=i.offsetWidth-i.clientWidth,i.remove(),t},set_dir_view_resize:function(){var e=$(".file_path_input"),t=$(".file_path_input .file_dir_view"),i=t.attr("data-width"),a=null;if(i?parseInt(i):(i=t.width(),t.attr("data-width",i)),t.width()-i<90){var s=0;$($(".file_path_input .file_dir_view .file_dir_item").toArray().reverse()).each(function(){var t=0;$(this).attr("data-width")?t=parseInt($(this).attr("data-width")):($(this).attr("data-width",$(this).width()),t=$(this).width()),s+=t,e.width()-s<=90?$(this).addClass("hide"):$(this).removeClass("hide")})}a=t.children(".file_dir_item.hide").clone(!0);0==t.children(".file_dir_item.hide").length?e.removeClass("active").find(".file_dir_omit").addClass("hide"):(a.each(function(){0==$(this).find(".glyphicon-hdd").length&&$(this).find(".file_dir").before('')}),e.addClass("active").find(".file_dir_omit").removeClass("hide"),e.find(".file_dir_omit .nav_down_list").empty().append(a),e.find(".file_dir_omit .nav_down_list .file_dir_item").removeClass("hide"))},reader_file_list:function(e,t){var i=this;if("function"==typeof e&&(t=e,e={is_operating:!1}),void 0===e&&(e={is_operating:!1}),a)return layer.msg("只能在该目录下操作",{icon:2}),!1;this.loadT=bt.load("正在获取文件列表,请稍候..."),this.file_images_list=[],i.get_dir_list(e,function(e){i.loadT.close(),i.file_list=$.merge(i.data_reconstruction(e.DIR,"DIR"),i.data_reconstruction(e.FILES)),i.file_path=e.PATH,i.is_recycle=e.FILE_RECYCLE,i.file_store_list=e.STORE,bt.set_cookie("Path",e.PATH);var a="",s="",n=e.DISK,l=i.file_list;i.select_list=i.file_list,i.render_path_list(),$.each(n,function(e,t){var i="/"==t.path?"根目录":t.path.indexOf(":/")>-1?"本地磁盘("+t.path.match(/[A-Z]+/)[0]+":)":t.path;a+='
                  '+i+"
                  "}),$.each(l,function(e,t){if(0==i.type&&t.type!=i.type_limit)return!0;var a=bt.format_data(t.mtime),n="dir"==t.type?"文件夹":"文件";s+=' '+t.filename+" "+a+" "+("dir"==t.type?"文件夹":"文件")+" "}),$("#select_mount_list").html(a),$("#select_dir_list").html(s);var c=e.PATH.lastIndexOf("/");e.PATH.substring(c+1,e.PATH.length);t&&t(rdata)})},reader_file_list_content:function(e,t){var i="",a=this,s=0;$.each(e,function(e,t){var n=t.filename+t.ps;a.file_list[e]=t=a.$file_data_dispose(t),a.file_list[e].only_index=e,t.filename.indexOf("Recycle_bin")&&(_tips="PS: 回收站目录,勿动!"),n.length>20&&(n=n.substring(0,20)+"..."),bt.check_chinese(n)&&n.length>10&&(n=n.substring(0,10)+"..."),i+='
                  '+t.filename+t.ps+""+(t.caret?'':"")+(t.down_id?'':"")+'
                  '+t.type_tips+'
                  '+("dir"==t.type?'点击计算':bt.format_size(t.size))+'
                  '+bt.format_data(t.mtime)+"
                  ","dir"==t.type&&s++,t.ispreview&&(a.file_images_list.push(t.path),t.images_id,t.images_id=a.file_images_list.length-1)}),$(".file_list_content").html(i),t&&t({is_dir_num:s})},$file_data_dispose:function(e){var t={languages:null,model:null};return $.extend(e,{only_id:bt.get_random(10),type_tips:"dir"===e.type?"文件夹":this.ext_type_tips(e.ext),open_type:this.determine_file_type(e.ext),languages:t.languages,path:e.path||this.path_resolve(this.file_path,e.filename),model:t.model})},path_resolve:function(e,t){var i="";return Array.isArray(t)||(t=[t]),e.replace(/([\/|\/]*)$/,function(e){return e,"www"}),$.each(t,function(e,t){i+="/"+t}),e+i},$get_file_model:function(e){var t=this.vscode_editor.config;for(languages in t.supportedModes)for(var i=t.supportedModes[languages],a=0;a'+("/"==i.path?"根目录":i.path)+" ("+i.size[2]+")"}),$(".mount_disk_list").html(t)})},determine_file_type:function(e,t){var i={images:["jpg","jpeg","png","bmp","gif","tiff","ico"],compress:["zip","rar","gz","war","tgz"],video:["mp4","mpeg","mpg","mov","avi","webm","mkv"],ont_text:["iso","xlsx","xsl","doc","docx","tiff","exe","so","7z","bz","dmg","apk"]},a=!1;if(null!=t)if("text"==t)$.each(i,function(t,i){$.each(i,function(t,i){if(i==e)return a=!0,!1})}),a=!a;else{if(void 0===i[t])return!1;$.each(i[t],function(t,i){if(i==e)return a=!0,!1})}else $.each(i,function(t,i){$.each(i,function(i,s){if(s==e)return a=t,!1})}),"boolean"==typeof a&&(a="text");return a},render_file_groud_menu:function(e,t){var i=this,a=$(t).data("index"),s=i.file_list[a],n=[["open","打开"],["split",""],["download","下载"],["share","分享目录/文件"],["cancel_share","取消分享"],["favorites","收藏目录/文件"],["cancel_favorites","取消收藏"],["split",""],["dir_kill","目录查杀"],["authority","权限"],["split",""],["copy","复制"],["shear","剪切"],["rename","重命名"],["del","删除"],["split",""],["killing","创建压缩",[["gzip","tar.gz (推荐)"],["zip","zip (通用格式)"],["rar","rar (中文兼容较好)"]]],["unzip","解压",[["local","解压到当前"],["folad","解压到当前"]]]],l=["zip","rar","gz","war","tgz","bz2"],c=0;"dir"==s.type&&(n.splice(2,1),c++),0!==s.down_id?(n.splice(3-c,1),c++):(n.splice(4-c,1),n[3-c][1]="dir"==s.type?"分享目录":"分享文件",c++),!1!==s.caret?(n.splice(5-c,1),c++):(n.splice(6-c,1),n[5-c][1]="dir"==s.type?"收藏目录":"收藏文件",c++),"php"!=s.ext&&"dir"!=s.type&&(n.splice(8-c,1),c++);var o=0;$.each(l,function(e,t){t==s.ext&&o++}),0==o&&(n.splice(17-c,1),c++),i.reader_menu_list({el:$(".selection_right_menu"),ev:e,data:s,list:n})},render_file_all_menu:function(e,t){var i=this,a=[["refresh","刷新"],["split",""],["upload","上传"],["create","新建文件夹/文件",[["create_dir","新建文件夹"],["create_files","新建文件"]]],["split",""],["paste","粘贴"]];bt.get_storage("session","copy_path")||a.splice(5,1),i.reader_menu_list({el:$(".selection_right_menu"),ev:e,data:{},list:a})},get_dir_list:function(e,t,i){var a=this;"boolean"==typeof t&&(i=t,t=null),s.$http("GetDir",$.extend({disk:!0,path:a.file_path,sort:bt.get_cookie("files_sort")||"type"},e),t,i)},retrun_prev_path:function(e){var t=e.split("/");return t.splice(t.length-1),t.join("/")},reader_menu_list:function(e){var t=this,i=e.el.find("ul"),a=i.height(),s=i.width(),n=e.ev.clientX-(this.area[0]-e.ev.clientX'):(Array.isArray(s[2])&&(n=$('
                    '),l=n.find(".set_group"),$.each(s[2],function(i,a){l.append($('
                  • '+a[1]+"
                  • ").on("click",{type:a[0],data:e.data},function(i){t.file_groud_event($.extend(i.data.data,{open:i.data.type,index:parseInt($(e.ev.currentTarget).data("index")),element:e.ev.currentTarget,type_tips:s.type?"文件夹":"文件"})),e.el.removeAttr("style"),i.stopPropagation(),i.preventDefault()}))})),i.append($('
                  • '+s[1]+"
                  • ").append(n).on("click",{type:s[0],data:e.data},function(i){t.file_groud_event($.extend(i.data.data,{open:i.data.type,index:parseInt($(e.ev.currentTarget).data("index")),element:e.ev.currentTarget,type_tips:s.type?"文件夹":"文件"})),e.el.removeAttr("style"),i.stopPropagation(),i.preventDefault()})))}),e.el.css({left:n,top:e.ev.clientY-(this.area[1]-e.ev.clientY0?$(".select_list_shadow").show():$(".select_list_shadow").hide(),i>=0&&$(".select_list_thaed").css("left",4-i+"px"),e.stopPropagation(),e.preventDefault()}),$(".file_path_refresh").on("click",function(){e.render_file_list()}),$(".select_dir_list thead th .icon-drag").on("mousedown",function(t){var i=t.clientX,a=$(this).parent(),s=a.index(),n=a[0].clientWidth;parseInt($(this).parent().attr("data-min"));if(1===t.which){var l=function(t){var a=t.clientX,l=a-i,c=n+l;setTimeout(function(){e.set_select_width(s,"width:"+c+"px")},0)};$(document).on("mousemove",l).one("mouseup",function(){$(this).unbind(l),$(this).unbind(this)})}t.stopPropagation()}),$(".select_dir_list thead th>span").on("click",function(t){var i=$(this).parent(),a=i.data("type"),s=i.hasClass("active"),n=i.hasClass("sort");s?i.addClass("sort").removeClass("active"):n?i.addClass("active").removeClass("sort"):i.addClass("active"),i.siblings().removeClass("active sort"),e.render_file_list({sort:a,reverse:s?1:0}),t.stopPropagation()}),$(".search_path_views input").on("keyup",function(){$(this).val()}),$(".search_path_views input").focus(function(){$(this).next().show()}).blur(function(){$(this).next().hide()}),$("#select_file_directory .select_file_group").on("click",".select_btn_group .btn-success",function(t){var i=$('[name="select_name"]').val();""==i?layer.msg("只能选择"+e.type_tips,{icon:2}):e.file_path}),$("#select_file_directory .select_file_tootls").on("click",".creat_dir",function(t){ -var i="   ";0==$("#tbody tr").length?$("#select_dir_list").append(i):$("#select_dir_list tr:first-child").before(i),$(".newFolderName").focus(),$("#nameOk").click(function(){var t=$("#newFolderName").val(),i=$(".file_path_views .path_input").attr("data-path");newTxt=i+"/"+t,s.$http("CreateDir",{path:newTxt},function(t){1==t.status?(e.reader_file_list({path:i,is_operating:!1}),layer.msg(t.msg,{icon:1})):layer.msg(t.msg,{icon:2})})})}),$("#select_mount_list").on("click",".item",function(){e.reader_file_list({path:$(this).attr("data-menu"),is_operating:!0})}),$(window).resize(function(t){$(this)[0].innerHeight!=e.area[1]&&(e.area[1]=$(this)[0].innerHeight,e.set_file_view()),$(this)[0].innerWidth!=e.area[0]&&(e.area[0]=$(this)[0].innerWidth,e.set_dir_view_resize()),e.vscode_editor.view&&e.vscode_editor.is_full_min>0&&layer.style(e.vscode_editor.view,{top:0,left:0,width:e.area[0],height:e.area[1]}),e.vscode_editor.view&&$.isEmptyObject(e.vscode_editor.list)&&e.vscode.layout()}).keydown(function(t){t=window.event||t;var i=t.keyCode,a=t.target.tagName.toLowerCase();if(8==i&&"input"!==a&&"textarea"!==a)return null==e.vscode_editor.view&&$(".forward_path span:eq(0)").click(),!1}),$(".file_path_input .path_input").on("focus blur keyup",function(t){t=t||window.event;var i=$(this).attr("data-path");switch(t.type){case"focus":$(this).addClass("focus").val(i).prev().hide();break;case"blur":$(this).removeClass("focus").val("").prev().show();break;case"keyup":if(13!=t.keyCode&&"keyup"==t.type)return!1;var a=$(this);$(this).data("path")!=$(this).val()&&e.reader_file_list({path:$(this).val(),is_operating:!0},function(e){!1===e.status?$(a).val(i):($(a).val(e.PATH),$(a).blur().prev().show())})}t.stopPropagation()}),$(".file_path_input .file_dir_view").on("click",".file_dir",function(){e.reader_file_list({path:$(this).attr("title"),is_operating:!0})}),$(".forward_path span").click(function(){var t=$(this).index(),i="";if(!$(this).hasClass("active")){switch(t){case 0:e.file_pointer=e.file_pointer-1,i=e.retrun_prev_path(e.file_path);break;case 1:e.file_pointer=e.file_pointer+1,i=e.file_path+"/"+$(".select_file_group .file_directory").val();break;case 2:e.file_pointer=e.file_pointer-1,i=e.retrun_prev_path(e.file_path)}e.reader_file_list({path:i,is_operating:!1})}}),$(".file_path_input .file_dir_view").on("click",".file_dir_omit",function(e){var t=this,i=$(this).children(".nav_down_list");$(this).addClass("active"),i.addClass("show"),$(document).one("click",function(){$(t).removeClass("active"),i.removeClass("show"),e.stopPropagation()}),e.stopPropagation()}),$("#select_dir_list").on("dblclick","tr",function(t){if($(t.target).hasClass("file_check"))return!1;var i=$(this).attr("data-path"),a=$(this).attr("data-type");"dir"==a&&e.reader_file_list({path:e.file_path+"/"+i}),t.stopPropagation(),t.preventDefault()}),$(".file_path_refresh").click(function(){e.reader_file_list({path:e.file_path})}),$(".file_nav_view .upload_or_download").on("click",function(t){e.open_upload_view(),t.stopPropagation(),t.preventDefault()}),$(".file_nav_view .upload_or_download li").on("click",function(t){var i=$(this).data("type");"uploadFile"===i?e.open_upload_view():e.open_download_view(),t.stopPropagation(),t.preventDefault()}),$(".mount_disk_list").on("click",".nav_btn",function(){var t=$(this).data("menu");e.reader_file_list({path:t})}),$(".file_list_header").on("click",".file_name,.file_size,.file_mtime,.file_accept,.file_user",function(t){var i=$(this).attr("data-tid"),a=$(this).find(".icon_sort").hasClass("active"),s=$(this).hasClass("active");return!$(this).find(".icon_sort").hasClass("active")&&$(this).hasClass("active")?$(this).find(".icon_sort").addClass("active"):$(this).find(".icon_sort").removeClass("active"),$(this).addClass("active").siblings().removeClass("active").find(".icon_sort").removeClass("active").empty(),$(this).find(".icon_sort").html(''),s||(a=!0),bt.set_cookie("files_sort",i),bt.set_cookie("name_reverse",a?1:0),e.reader_file_list(),!1}),$(".file_list_header .file_th").each(function(e,t){var i=bt.get_cookie("files_sort"),a=bt.get_cookie("name_reverse");$(this).attr("data-tid")===i&&($(this).addClass("active").siblings().removeClass("active").find(".icon_sort").removeClass("active").empty(),$(this).find(".icon_sort").html(''),0===a&&$(this).find(".icon_sort").addClass("active"))}),$(".file_list_header .file_check").on("click",function(t){var i=parseInt($(this).data("checkbox"));switch(i){case 0:$(this).addClass("active").removeClass("active_2").data("checkbox",1),$(".file_list_content .file_tr").addClass("active").removeClass("active_2"),e.file_table_arry=e.file_list;break;case 2:$(this).addClass("active").removeClass("active_2").data("checkbox",1),$(".file_list_content .file_tr").addClass("active"),e.file_table_arry=e.file_list;break;case 1:$(this).removeClass("active active_2").data("checkbox",0),$(".file_list_content .file_tr").removeClass("active"),e.file_table_arry=[]}}),$(".file_list_content").on("click",".file_check",function(t){var i=$(this).parents(".file_tr"),a=i.data("index"),s=$(".file_list_header .file_check"),n=i.attr("data-filename");$(".selection_right_menu").removeAttr("style"),i.hasClass("active")?(i.removeClass("active"),e.remove_check_file(e.file_table_arry,"filename",n),e.file_table_arry.length>0?s.addClass("active_2").removeClass("active").data("checkbox",2):0==e.file_table_arry.length&&s.removeClass("active active_2").data("checkbox",0)):(i.addClass("active"),i.attr("data-filename",e.file_list[a].filename),e.file_table_arry.length==e.file_list.length?s.addClass("active").removeClass("active_2").data("checkbox",1):s.addClass("active_2").removeClass("active").data("checkbox",2),e.file_table_arry.push(e.file_list[a])),t.stopPropagation()}),$(".file_list_content").scroll(function(e){$(this).scrollTop()==$(this)[0].scrollHeight-$(this)[0].clientHeight?($(this).prev().css("opacity",1),$(this).next().css("opacity",0)):$(this).scrollTop()>0?$(this).prev().css("opacity",1):0==$(this).scrollTop()&&($(this).prev().css("opacity",0),$(this).next().css("opacity",1))}),$(".file_table_view .file_list_content").on("click",".file_tr",function(e){$(".selection_right_menu").removeAttr("style"),$(this).find(".file_checkbox .file_check").click(),e.stopPropagation(),e.preventDefault()}),$(".file_table_view .file_list_content").on("click",".file_title i",function(t){var i=$(this).parents(".file_tr"),a=i.data("index"),s=e.file_list[a];"dir"==s.type&&e.reader_file_list({path:e.file_path+"/"+s.filename}),t.stopPropagation()}),$(".file_table_view .file_list_content").on("click",".file_name .icon-share1",function(t){var i=$(this).parents(".file_tr"),a=i.data("index"),s=e.file_list[a];e.info_file_share(s,i),t.stopPropagation()}),$(".file_table_view .file_list_content").on("click",".file_name .icon-favorites",function(t){var i=$(this).parents(".file_tr"),a=i.data("index"),s=e.file_list[a];s.typeText=s.type?"文件夹":"文件",e.cancel_file_favorites(s,i),t.stopPropagation()}),$(".file_table_view .file_list_content").on("dblclick",".file_tr",function(t){if($(t.target).hasClass("file_check"))return!1;var i=$(this).data("index"),a=e.file_list[i];"dir"==a.type&&e.reader_file_list({path:e.file_path+"/"+a.filename}),t.stopPropagation(),t.preventDefault()}),$(".file_list_content").on("contextmenu",".file_tr",function(t){var i=this;3==t.which&&(e.render_file_groud_menu(t,this),$(".content_right_menu").removeAttr("style"),$(this).addClass("selected").siblings().removeClass("selected"),$(document).one("click",function(e){$(i).removeClass("selected"),$(".selection_right_menu").removeAttr("style"),e.stopPropagation(),e.preventDefault()})),t.stopPropagation(),t.preventDefault()}),$(".file_list_content").on("contextmenu",function(t){var i=$(".content_right_menu");i.width(),i.height();3==t.which&&($(".selection_right_menu").removeAttr("style"),e.render_file_all_menu(t,this)),t.stopPropagation(),t.preventDefault()}),$(".filePage").on("change",".showRow",function(){var t=$(this).val();bt.set_storage("showRow",t),e.reader_file_list()}),$(".file_list_content").on("click",".folder_size",function(e){var t=i.file_list[$(this).parents(".file_tr").data("index")],i=this;i.get_file_size({path:t.path},function(e){$(i).text(bt.format_size(e.size))}),e.stopPropagation(),e.preventDefault()}),$(".cut_view_model").on("click",function(){var e=$(this).data("type");$(".file_table_view").addClass("icon"==e?"icon_view":"list_view").removeClass("icon"!=e?"icon_view":"list_view"),$(this).addClass("active").siblings().removeClass("active")})},set_file_forward:function(){var e=this,t=$(".forward_path span");1==e.file_operating.length?t.addClass("active"):e.file_pointer==e.file_operating.length-1?(t.eq(0).removeClass("active"),t.eq(1).addClass("active")):0==e.file_pointer?(t.eq(0).addClass("active"),t.eq(1).removeClass("active")):t.removeClass("active")},set_file_view:function(){var e=$(".file_list_content"),t=this.area[1]-170;$(".file_bodys").height(this.area[1]-100),50*this.file_list.length>t?(e.attr("data-height",e.data("height")||e.height()).height(t),$(".file_shadow_bottom").css("opacity",1)):(e.height(t),$(".file_shadow_top,.file_shadow_bottom").css("opacity",0))},clear_table_active:function(){this.file_table_arry=[],$(".file_list_header .file_check").removeClass("active active_2"),$(".file_list_content .file_tr").removeClass("active")}};n.reader_view(),n.event_bind()},$fixed_table_thead:function(e){$(e).scroll(function(){var e=this.scrollTop;this.querySelector("thead").style.transform="translateY("+e+"px)"})},send:function(e,t,i,a,s,n){function l(e){try{o="function"==d[e][1]?d[e][0]:null,r="function"==d[e+1][1]?d[e+1][0]:null}catch(e){}}var c={},o=null,r=null,d=[],p="";switch($.each(arguments,function(e,t){d.push([t,typeof t])}),p=d[0],p[1]){case"string":$.each(d,function(e,t){var i=t[0],a=t[1];if(e>1&&("boolean"==a||"string"==a||"object"==a)){var s=p[0].split("/");return c.url="/"+s[0]+"?action="+s[1],c.load=i,"object"==a&&(c.load=i.load,c.tips=i.tips,c.verify=i.verify),!1}c.url=p[0]}),"object"===d[1][1]?(c.data=d[1][0],l(2)):l(1);break;case"object":c.url=p[0].url,c.data=p[0].data||{},$.each(d,function(e,t){var i=t[0],a=t[1];if(e>1&&("boolean"==a||"string"==a||"object"==a))return c.load=t,"object"==a&&(c.load=i.load,c.tips=i.tips),!0}),"object"===d[1][1]?(c.data=d[1][0],l(2)):l(1)}c.load&&(c.load=this.load(c.load)),$.ajax({type:c.type||"POST",url:c.url,data:c.data||{},dataType:c.dataType||"JSON",complete:function(){c.load&&c.load.close()},success:function(e){return c.verify?(o&&o(e),!1):"string"==typeof e?(layer.msg(e,{icon:2,time:0,closeBtn:2}),!1):c.bacth?(o&&o(e),!1):!1===e.status&&e.msg?(bt_tools.msg(e),!1):(c.tips&&bt_tools.msg(e),void(o&&o(e)))},error:function(e){r&&r(e),layer.closeAll("dialog"),layer.closeAll("loading"),layer.msg("Service response error:"+e.status+"
                    error msg:"+e.statusText+"
                    URL:"+c.url+"
                    param:"+JSON.stringify(c.data),{icon:2,time:0,closeBtn:2})}})}};$.fn.serializeObject=function(){var e=Object.prototype.hasOwnProperty;return this.serializeArray().reduce(function(t,i){return e.call(t,i.name)||(t[i.name]=i.value),t},{})}; \ No newline at end of file +var bt_tools={commandConnectionPool:{},table:function(a){function b(c){this.config=c;this.$load()}b.prototype={style_list:[],event_list:{},checkbox_list:[],batch_active:{},event_rows_model:{},data:[],page:"",column:[],batch_thread:[],random:bt.get_random(5),init:false,checked:false,$load:function(){var d=this,c=$('');if(this.config.init){this.config.init(this)}$(this.config.el).addClass("bt_table").append(c);c.focus(function(){d.checked=true;return false}).blur(function(e){d.checked=false;if(d.checked_blur){d.checked_blur(e)}});if(this.config.minWidth){this.style_list.push({className:this.config.el+" table",css:("min-width:"+this.config.minWidth)})}if(this.config.tootls){this.$reader_tootls(this.config.tootls)}else{console.log(this.config.height);if($(d.config.el+".divtable").length===0){$(d.config.el).append('
                    ')}}this.$reader_content();if(d.config.url!==undefined){this.$refresh_table_list()}else{if(this.config.data!==undefined){this.$reader_content(this.config.data)}else{alert(lan["public"].miss_data_or_url)}}if(this.config.methods){$.extend(this,this.config.methods)}},$refresh_table_list:function(d){var c=this,e;if(d){e=bt.load(lan.database.get_data)}this.$http(function(g,f){if(d){e.close()}c.$reader_content(g,f)})},$active_focus:function(d){var c=this;$("#checked_"+c.random).focus();this.checked_blur=function(e){setTimeout(function(){if(d){d(e)}delete c.checked_blur},200)}},$reader_content:function(u,h){var v=this,r="",c="",q=0,g=this.config.column,f={},n=$(v.config.el+" .checkbox_"+v.random);u=u||[];this.data=u;if(n.length){n.removeClass("active selected");v.checkbox_list=[];v.$set_batch_view()}do{var k=u[q],m=0;if(u.length>0){c+=""}for(var p=0;p"+(s.type=="checkbox"?'':""+s.title+"")+(s.sort?'':"")+"";if(q===0){if(!f[d]&&s.sort){f[d]={event:this.config.sortEvent,eventType:"click",type:"sort"}}if(!f[l]){f[l]={event:s.checked,eventType:"click",type:"checkbox"}}}}if(k!==undefined){var t="",e="event-"+s.fid+"-"+this.random;if(s.template){t=v.$custom_template_render(s,k,p)}else{t=this.$reader_column_type(s,k);f=$.extend(f,t[1]);t=t[0]}c+=""+t+"";if(q===0){if(!f[e]&&s.event){f[e]={event:s.event,eventType:"click",type:"rows"}}}}}if(u.length>0){c+=""}if(u.length==0){c+=''+(this.config["default"]||lan["public"].empty)+""}q++}while(q'+r+""+c+"")}else{$(this.config.el+" .divtable tbody").html(c);if(this.config.page&&h){$(this.config.el+" .page").replaceWith(this.$reader_page(this.config.page,h))}}this.init=true;if(this.config.success){this.config.success(this)}},$custom_template_render:function(g,h,d){var e="event-"+g.fid+"-"+this.random,f=g.template(h,d),c=$(f);if(c.length>0){template=c.addClass(e)[0].outerHTML}else{if(g.type==="text"){template=''+f+""}else{template=''+f+""}}return template},$modify_row_data:function(e){this.event_rows_model.rows=$.extend(this.event_rows_model.rows,e);var d=this.event_rows_model,c=null;if(typeof d.model.template!="undefined"){c=$(this.$custom_template_render(d.model,d.rows,d.index))}else{c=$(this.$reader_column_type(d.model,d.rows)[0])}d.el.replaceWith(c);d.el=c},$batch_success_table:function(c){var d=this;bt.open({type:1,title:c.title,area:c.area||["380px","350px"],shadeClose:false,closeBtn:2,content:c.content||'
                    '+c.title+" "+lan["public"].success+'
                    "+c.html+"
                    '+c.th+''+lan["public"].result+"
                    ",success:function(){d.$fixed_table_thead(".fiexd_thead")}})},$delete_table_row:function(c){this.data.splice(c,1);this.$reader_content(this.data)},$fixed_table_thead:function(c){$(c).scroll(function(){var d=this.scrollTop;this.querySelector("thead").style.transform="translateY("+d+"px)"})},$set_batch_view:function(){var c=$(this.config.el+" .bt_select_value"),d=$(this.config.el+" .bt_table_select_group").next();if(typeof this.config.batch!="undefined"){var d=$(this.config.el+" .set_batch_option");if(typeof this.config.batch.config!="undefined"){if(this.checkbox_list.length>0){d.removeClass("bt-disabled btn-default").addClass("btn-success").text(lan["public"].please_choose+this.batch_active.title+"("+lan["public"].selected+this.checkbox_list.length+")")}else{d.addClass("bt-disabled btn-default").removeClass("btn-success").text(lan["public"].please_choose+this.batch_active.title)}}else{var c=$(this.config.el+" .bt_select_value");if(this.checkbox_list.length>0){d.removeClass("bt-disabled btn-default").addClass("btn-success").prev().removeClass("bt-disabled");c.find("em").html("("+lan["public"].selected+this.checkbox_list.length+")")}else{d.addClass("bt-disabled btn-default").removeClass("btn-success").prev().addClass("bt-disabled");c.children().eq(0).html(lan["public"].please_choose+"");c.next().find("li").removeClass("active");this.batch_active={}}}}},$reader_column_type:function(m,n){var l=n[m.fid],c={},i="",e=[],g=this;switch(m.type){case"text":e=[l,c];break;case"checkbox":e=['',c];break;case"password":var k="",j="",i="ico_"+g.random+"_",h='**********';if(m.eye_open){h+='';if(!c[i+"eye_open"]){c[i+"eye_open"]={type:"eye_open_password"}}}if(m.copy){h+='';if(!c[i+"copy"]){c[i+"copy"]={type:"copy_password"}}}e=[h,c];break;case"link":i="click_"+m.fid+"_"+this.random;if(!c[i]&&m.event){c[i]={event:m.event,type:"rows"}}e=[''+l+"",c];break;case"input":blurName="blur_"+m.fid+"_"+this.random;keyupName="keyup_"+m.fid+"_"+this.random;if(!c[blurName]&&m.blur){c[blurName]={event:m.blur,eventType:"blur",type:"rows"}}if(!c[keyupName]&&m.keyup){c[keyupName]={event:m.keyup,eventType:"keyup",type:"rows"}}e=['',c];break;case"status":var f="";i="click_"+m.fid+"_"+this.random;$.each(m.config.list,function(p,o){if(o[0]===l){f=o}});if(!c[i]&&m.event){c[i]={event:m.event,type:"rows"}}e=['-1?"":f[2])+'" style="'+(f[2].indexOf("#")>-1?("color:"+f[2]+";"):"")+'" href="javascript:;">'+f[1]+""+(m.config.icon?'':"")+"",c];break;case"switch":break;case"group":var d="";$.each(m.group,function(q,o){i=(m.fid?m.fid:"group")+"_"+q+"_"+g.random;if(o.template){var r=o.template(n,g),p=$(r);if(p.length>0){d+=p.addClass(i)[0].outerHTML}else{d+=''+r+""}}else{d+='"+o.title+""}d+=((m.group.length-1!=q)?" | ":"");if(!c[i]&&o.event){c[i]={event:o.event,type:"rows"}}});e=[d,c];break;default:e=[l,c];break}return e},$reader_tootls:function(f){var k=this,c={};function o(w,v){var x=bt.load(w.title+lan.site.executing),i={},u=k.$get_data_batch_list(w.paramId,v);if(!w.beforeRequest){i[w.paramName]=u.join(",")}else{i[w.paramName]=w.beforeRequest(v)}bt_tools.send({url:w.url||k.config.batch.url,data:$.extend(w.param||{},i)},function(z){x.close();if(!z.status){return false}if(typeof w.tips==="undefined"||w.tips){var y="";$.each(z.error,function(A,B){y+=""+A+'
                    '+B+"
                    "});$.each(z.success,function(A,B){y+=""+B+'
                    '+lan["public"].success+"
                    "});k.$batch_success_table({title:w.title,th:w.theadName,html:y});k.$refresh_table_list(true)}if(w.success){w.success(z,v,k)}})}function l(u,i,v){if(u.callback){u.callback({loadT:0,config:{},check_list:i,bacth_status:true,start_batch:function(w,y){var x=this;if(u.load){this.loadT=layer.msg(lan["public"].executeing+u.title+','+lan["public"].schedule+":0/"+this.check_list.length+","+lan["public"].please_wait+(u.clear?'cancel':""),$.extend({icon:16,skin:"batch_tips",shade:0.3,time:0},u.clear?{area:"420px"}:{}));$("#layui-layer"+x.loadT).on("click",".clear_batch",function(){x.clear_bacth()})}this.config={param:w,url:u.url};this.bacth(y)},bacth:function(w,z){var y=this,x={};if(typeof w==="function"){z=w,w=0}if(w'+lan["public"].executeing+u.title+','+lan["public"].schedule+":"+w+"/"+y.check_list.length+","+lan["public"].please_wait+(u.clear?'cancel':""))}bt_tools.send({url:this.config.url,data:this.config.param,bacth:true},function(A){$.extend(y.check_list[w],{request:{status:typeof A.status==="boolean"?A.status:false,msg:A.msg||lan["public"].request_error}});w++;y.bacth(w,z)})}else{if(v){v()}z(this.check_list);layer.close(this.loadT)}},clear_bacth:function(){this.bacth_status=false;layer.close(this.loadT)}})}else{if(!u.confirm){if(u.confirmVerify){bt.show_confirm(u.title+lan["public"].in_bulk,u.title+lan["public"].in_bulk+","+lan["public"].risk_prompt,o)}else{bt.confirm({title:u.title+lan["public"].in_bulk,msg:u.title+lan["public"].in_bulk+","+lan["public"].risk_prompt},function(){if(o){o(u,i)}})}}else{o(u,i)}}}for(var p=0;p'+i.title+""}else{r+='
                    ';if(t.list){$.each(t.list,function(y,x){v+='
                  • "+x[t.key]+"
                  • "})}if(i.init){setTimeout(function(){i.init(w)},400)}}if(!c[w]){c[w]={event:i.event,type:"button"}}});break;case"search":this.config.search=t;var s="search_input_"+this.random,n="search_btn_"+this.random;r='';if(!c[s]){c[s]={eventType:"keyup",type:"search_input"}}if(!c[n]){c[n]={type:"search_btn"}}break;case"batch":this.config.batch=t;var h=[],e="",j=t.config;if(typeof t.config!="undefined"){k.batch_active=j;$(k.config.el).on("click",".set_batch_option",function(x){var w=[];for(var v=0;v'+v.title+""});delete i.group}else{h.push(i);e+='
                  • '+i.title+"
                  • "}});$(k.config.el).on("click",".bt_table_select_group .bt_select_value",function(x){var y=this,w=$(this).parent(),i=w.find(".bt_selects"),v=w.offset(),u=k.$get_win_area();if(w.hasClass("bt-disabled")){layer.tips(k.config.batch.disabledSelectValue,w,{tips:[1,"red"],time:2000});return false}if(w.hasClass("active")){w.removeClass("active")}else{w.addClass("active")}if(i.height()>(u[1]-v.top)){i.addClass("top")}else{i.removeClass("top")}$(document).one("click",function(){$(k.config.el).find(".bt_table_select_group").removeClass("active");return false});return false});$(k.config.el).on("click",".bt_table_select_group .item",function(u){var i=$(this).text(),v=$(this).index();$(this).addClass("active").siblings().removeClass("active");$(k.config.el+" .bt_select_tips").html(i+lan["public"].in_bulk+"("+lan.site.have_been_selected+k.checkbox_list.length+")");k.batch_active=h[v];if(!k.checked){$(".bt_table_select_group").removeClass("active")}});$(k.config.el).on("click",".set_batch_option",function(z){var y=[],x=k.batch_active;if($(this).hasClass("bt-disabled")){layer.tips(k.config.batch.disabledSelectValue,$(this),{tips:[1,"red"],time:2000});return false}for(var w=0;w'+(typeof t.config!="undefined"?'":'
                    '+lan["public"].select_opt_type+'
                      '+e+'
                    ")+"";break;case"page":this.config.page=t;var q=bt.get_cookie(this.config.cookiePrefix+"_"+this.config.page.numberParam);if(this.config.cookiePrefix&&q){this.config.page.number=q}r=this.$reader_page(this.config.page,'
                    1 '+lan.public_backup.total+"
                    ");break}if(r){var d=$(k.config.el+" .tootls_"+t.positon[1]);if(d.length){var m=d.find(".pull-"+t.positon[0]);m.append(r)}else{var g='
                    '+(t.positon[0]=="left"?r:"")+'
                    '+(t.positon[0]=="right"?r:"")+"
                    ";if(t.positon[1]==="top"){$(k.config.el).append(g);if($(k.config.el+" .divtable").length===0){$(k.config.el).append('
                    ')}}else{if($(k.config.el+" .divtable").length===0){$(k.config.el).append('
                    ')}$(k.config.el).append(g)}}}}if(!this.init){this.$event_bind(c)}},$get_data_batch_list:function(e,c){var d=[];$.each(c||this.data,function(f,g){d.push(g[e])});return d},$reader_page:function(d,h){var e=this,f=$(h),k="",c={};f.find("a").addClass("page_link_"+this.random);k+=f.html();if(d.numberStatus){var i="page_select_"+this.random;k+='";c[i]={eventType:"change",type:"page_select"}}if(d.jump){var g="page_jump_input-"+this.random;var j="page_jump_btn_"+this.random;k+='
                    '+lan["public"].jump_to_page+'
                    ";c[g]={eventType:"keyup",type:"page_jump_input"};c[j]={type:"page_jump_btn"}}c["page_link_"+this.random]={type:"cut_page_number"};e.config.page.total=parseInt(f.find(".Pcount").html().match(/([0-9]*)/g)[1]);e.$event_bind(c);return'
                    '+k+"
                    "},$dynamic_merge_style:function(d,c){var e="";$.each(d,function(f,g){switch(f){case"align":e+="text-align:"+g+";";break;case"width":e+="width:"+(typeof g=="string"?g:g+"px")+";";break;case"style":e+=g;break;case"minWidth":e+="min-width:"+(typeof g=="string"?g:g+"px")+";";break;case"maxWidth":e+="max-width:"+(typeof g=="string"?g:g+"px")+";";break}});return{index:c,css:e}},$event_bind:function(d){var c=this;$.each(d,function(e,f){if(c.event_list[e]&&c.event_list[e].eventType===f.eventType){return true}c.event_list[e]=f;$(c.config.el).on(f.eventType||"click","."+e,function(q){var o=$(this).parents("tr").index(),k=$(this).data(),n=[];switch(f.type){case"rows":c.event_rows_model={el:$(this),model:c.config.column[$(this).parents("td").index()],rows:c.data[o],index:o};n=[c.event_rows_model.rows,c.event_rows_model.index,q,e,c];break;case"sort":var m=c.config.column[k.index];if($(this).hasClass("sort-active")){$(".sort_"+c.random+" .sort-active").data({sort:"desc"})}$(".sort_"+c.random).removeClass("sort-active").find(".glyphicon").removeClass("glyphicon-triangle-top").addClass("glyphicon-triangle-bottom");$(this).addClass("sort-active");if(k.sort=="asc"){$(this).data({sort:"desc"});$(this).find(".glyphicon").removeClass("glyphicon-triangle-top").addClass("glyphicon-triangle-bottom")}else{$(this).data({sort:"asc"});$(this).find(".glyphicon").removeClass("glyphicon-triangle-bottom").addClass("glyphicon-triangle-top")}c.config.sort=c.config.sortParam({name:m.fid,sort:k.sort});c.$refresh_table_list(true);break;case"checkbox":var t=$(c.config.el+' [data-checkbox="all"]'),i=$(c.config.el+" tbody .checkbox_"+c.random);if(k.checkbox==undefined){if(!$(this).hasClass("active")){$(this).addClass("active");c.checkbox_list.push(o);if(c.data.length===c.checkbox_list.length){t.addClass("active").removeClass("selected")}else{if(c.checkbox_list.length>0){t.addClass("selected")}}}else{$(this).removeClass("active");c.checkbox_list.splice(c.checkbox_list.indexOf(o),1);if(c.checkbox_list.length>0){t.addClass("selected").removeClass("active")}else{t.removeClass("selected active")}}}else{if(c.checkbox_list.length===c.data.length){c.checkbox_list=[];i.removeClass("active selected").next().prop("checked","checked");t.removeClass("active")}else{i.each(function(u,v){if(!$(this).hasClass("active")){$(this).addClass("active").next().prop("checked","checked");c.checkbox_list.push(u)}});t.removeClass("selected").addClass("active")}}c.$set_batch_view();break;case"button":n.push(q,c);break;case"search_focus":var s=$(c.config.el+" .bt_search_tips");if($(c.config.el+" .bt_search_tips").length>0){s.remove()}break;case"search_input":if(q.keyCode==13){$(c.config.el+" .search_btn_"+c.random).click();return false}break;case"search_btn":var l=$(c.config.el+" .search_input"),h=$(c.config.el+" .search_input").val();c.config.search.value=h;l.append('
                    '+h+'
                    ');c.$refresh_table_list(true);break;case"page_select":var j=parseInt($(this).val());c.config.page.number=j;c.config.page.page=1;c.$refresh_table_list(true);return false;break;case"page_jump_input":if(q.keyCode==13){$(c.config.el+" .page_jump_btn_"+c.random).click();$(this).focus()}return false;break;case"page_jump_btn":var r=parseInt($(c.config.el+" .page_jump_input-"+c.random).val()),g=Math.ceil(c.config.page.total/c.config.page.number);if(r>g){r=c.config.page.page}c.config.page.page=r;c.$refresh_table_list(true);break;case"cut_page_number":var p=parseInt($(this).attr("href").match(/([0-9]*)$/)[0]);c.config.page.page=p;c.$refresh_table_list(true);return false;break;case"eye_open_password":if($(this).hasClass("glyphicon-eye-open")){$(this).addClass("glyphicon-eye-close").removeClass("glyphicon-eye-open");$(this).prev().text(c.data[o].password)}else{$(this).addClass("glyphicon-eye-open").removeClass("glyphicon-eye-close");$(this).prev().html("**********")}return false;break;case"copy_password":bt.pub.copy_pass(c.data[o].password);return false;break}if(f.event){f.event.apply(this,n)}})})},$style_bind:function(e,c){var f="",d=this;$.each(e,function(g,h){if(h.css!=""){if(!h.className){f+=d.config.el+" thead th:nth-child("+(h.index+1)+"),"+d.config.el+" tbody tr td:nth-child"+(h.span?" span":"")+"("+(h.index+1)+"){"+h.css+"}"}else{f+=h.className+"{"+h.css+"}"}}});if($("#bt_table_"+d.random).length==0){$(d.config.el).append('")}},$get_win_area:function(){return[window.innerWidth,window.innerHeight]},$http:function(h){var g={},d=this.config,e=d.page,f=d.search,c=d.sort||{};if(e){g[e.numberParam]=e.number,g[e.pageParam]=e.page;if(this.config.cookiePrefix){bt.set_cookie(this.config.cookiePrefix+"_"+e.numberParam,e.number)}}if(f){g[f.searchParam]=f.value}if(this.config.beforeRequest){d.param=this.config.beforeRequest(d.param)}bt_tools.send({url:d.url,data:$.extend(d.param,g,c)},function(i){if(d.dataFilter){var j=d.dataFilter(i);if(h){h(j.data,j.page)}}else{if(h){h(i.data,i.page)}}})}};return new b(a)},select_file:function(c,d){if(typeof c==="string"){c={path:c,type:2,title:lan["public"].select_fileordir,ext:[],limit:""}}if(typeof c==="function"){type=d,d=c,c={path:bt.get_cookie("Path")}}if(typeof type!=="number"){type=0}var b=this,a={type:type,type_tips:type==0?lan["public"].dir:(type==1?lan.site.file:lan["public"].fileordir),select_list:[],select_path:bt.get_cookie("Path")||(bt.os=="Windows"?setup_path:"/www/wwwroot"),select_config:{},scroll_width:0,reader_view:function(){var e=this;this.scroll_width=a.getScrollbarWidth();layer.open({type:1,title:c.title||(lan["public"].select+e.type_tips),shadeClose:false,closeBtn:1,area:["650px","550px"],content:'
                    '+lan["public"].name+''+lan["public"].modify_time+''+lan.site.redirect_type+'
                    文件修改时间类型
                    '+e.type_tips+'名:
                    ',success:function(){e.evnet_bind();e.render_file_list(function(){e.set_path_width()});$(".select_list_thaed").css("right",e.scroll_width+"px")}})},evnet_bind:function(){var e=this;$("#select_dir_list").on("click","tr",function(){var f=$(this).data("index");$(this).addClass("active").siblings().removeClass("active");$('[name="select_name"]').val(e.select_list[f].filename)});$(".select_list_body").on("scroll",function(h){var g=$(this).scrollTop(),f=$(this).scrollLeft();if(g>0){$(".select_list_shadow").show()}else{$(".select_list_shadow").hide()}if(f>=0){$(".select_list_thaed").css("left",(4-f)+"px")}h.stopPropagation();h.preventDefault()});$(".file_path_refresh").on("click",function(){e.render_file_list()});$(".select_dir_list thead th .icon-drag").on("mousedown",function(k){var m=k.clientX,f=$(this).parent(),h=f.index(),n=f[0].clientWidth,g=parseInt($(this).parent().attr("data-min")),l=null;if(k.which===1){var j=function(r){var p=r.clientX,q=p-m,o=n+q;l=setTimeout(function(){e.set_select_width(h,"width:"+o+"px")},0)},i=function(){$(this).unbind(j);$(this).unbind(i)};$(document).on("mousemove",j).one("mouseup",function(){$(this).unbind(j);$(this).unbind(this)})}k.stopPropagation()});$(".select_dir_list thead th>span").on("click",function(h){var g=$(this).parent(),f=g.data("type"),i=g.hasClass("active"),j=g.hasClass("sort");if(i){g.addClass("sort").removeClass("active")}else{if(j){g.addClass("active").removeClass("sort")}else{g.addClass("active")}}g.siblings().removeClass("active sort");e.render_file_list({sort:f,reverse:i?1:0});h.stopPropagation()});$(".search_path_views input").on("keyup",function(){var f=$(this).val()})},set_path_width:function(j){var e=0,h=$(".file_dir_view")[0].offsetWidth,g=$(".file_dir_view .file_dir_item"),k=[],e=0;$(".file_dir_view .file_dir_item").each(function(){k.push($(this)[0].offsetWidth)});var l=k.reverse();for(var f=0;f-1?("本地磁盘("+r.path.match(/[A-Z]+/)[0])+":)":r.path);f+='
                    '+p+"
                    "});$.each(l,function(q,s){var p=bt.format_data(s.mtime),r=(s.type=="dir"?"文件夹":"文件");g+=' '+s.filename+" "+p+" "+(s.type=="dir"?"文件夹":"文件")+" "});$("#select_mount_list").html(f);$("#select_dir_list").html(g);if(j){j(n)}})},render_path_list:function(j,m){var h='
                    ',f="",l=j.split("/").splice(1),k=j.split("/")[0];if(bt.os==="Windows"){if(l.length==0){l=[]}l.unshift('本地磁盘('+k+")")}else{if(j=="/"){l=[]}l.unshift("根目录")}for(var g=0;g '+l[g]+' '}$(".path_input").val("").attr("data-path",j);var e=$("#select_file_directory .file_path_input .file_dir_view");e.html(h);if(m){m(j)}},set_select_width:function(h,g){var i=this,f=".select_dir_list tbody td:nth-child("+(h+1)+")>span,.select_dir_list thead th:nth-child("+(h+1)+")>span",e=$("#th-index-"+h);if(e.length>0){e.html(f+"{"+g+"}")}else{$("#select_file_style").append('")}},cut_style_object:function(f){var e={},g=f.split(";");return e},getScrollbarWidth:function(){var h=document.createElement("div"),g={width:"100px",height:"100px",overflowY:"scroll"},e,f;for(e in g){h.style[e]=g[e]}document.body.appendChild(h);f=h.offsetWidth-h.clientWidth;h.remove();return f}};a.reader_view()},form:function(a){var b=this;function c(d){this.config=d;this.data=d.data||{};this.$load()}c.prototype={element:null,style_list:[],event_list:{},event_type:["click","event","focus","keyup","blur","change"],hide_list:[],form_element:{},form_config:{},random:bt.get_random(5),$load:function(){var d=this;if(d.el){this.$reader_content(function(){d.$event_bind()})}},$reader_content:function(h){var g=this,f="",e="",d={};$.each(g.config.form,function(i,j){f+=g.$reader_content_row(i,j)});g.element=$('
                    '+f+"
                    ");e=$('
                    ');e.append(g.element);if(h){h()}return e[0].outerHTML},$reader_content_row:function(f,h){var g=this,e=h.help,d=this.config.formLabelWidth||h.formLabelWidth;return'
                    "+(h.label?'"+h.label+"":"")+'
                    "+g.$reader_form_element(h.group,f)+(e?('
                    "+e.list.join("
                    ")+"
                    "):"")+"
                    "},$reader_form_element:function(g,d){var f=this,e="";if(!Array.isArray(g)){g=[g]}$.each(g,function(h,i){i.find_index=d;e+=f.$reader_form_find(i);f.form_config[i.name]=i});return e},$reader_form_element:function(i,f){var h=this,e=[],g="",d={};if(!Array.isArray(i)){i=[i]}$.each(i,function(q,r){var j=h.$reader_style(r.style)+b.$verify(r.width,"width","style"),k=h.$verify_group(r,["name","value","placeholder","disabled","readonly","autofocus","autocomplete","min","max"]),s=h.$create_event_config(r),o="";g+=r.label?''+r.label+"":"";if(typeof r.name!=="undefined"){d[r.name]=s}switch(r.type){case"text":case"checkbox":case"password":case"radio":case"number":var m="event_"+r.name+"_"+h.random,n=r.type==="checkbox"?true:false;if(r.type==="radio"){$.each(r.label_tips,function(u,t){if(r.block){g+='
                    '}g+='';g+='";if(r.block){g+="
                    "}})}else{if(r.block){g+='
                    '}g+='";if(r.type=="checkbox"){g+='"}if(r.block){g+="
                    "}h.event_list[m]={click:{event:r.event}}}if(r.icon){g+='";d[r.name+"_icon"]={click:{type:"select_path",config:r}}}break;case"textarea":g+='";$.each(["blur","focus","input"],function(u,t){if(r.tips){var v=null;switch(t){case"blur":v=function(x,w){if($(this).val()===""){$(this).next().show()}layer.close(w.tips.loadT)};break;case"focus":v=function(x,w){$(this).next().hide();w.tips.loadT=layer.tips(p,$(this),{tips:[1,"#20a53a"],time:0,area:$(this).width()})};break}}d[r.name][t]?(d[r.name][t]["added"]=v):(d[r.name][t]={type:r.type,cust:false,event:r[t],added:v})});if(r.tips){var p="";if(typeof r.tips.list==="undefined"){p=r.tips.text}else{p=r.tips.list.join("
                    ")}g+='
                    "+p+"
                    ";d[r.name+"_tips"]={click:{type:"textarea_tips",config:r}}}break;case"select":g+=h.$reader_select(r,j,k,f);h.event_list.custom_select={click:{type:"custom_select",children:".bt_select_value"}};h.event_list.custom_select_item={click:{type:"custom_select_item",children:"li.item"}};break;case"link":o="event_"+bt.get_random(6);g+='"+r.title+"";h.event_list[o]={click:{type:"link_event",event:r.event}};break;case"help":var l="";$.each(r.list,function(u,t){l+="
                  • "+t+"
                  • "});g+='
                      "+l+"
                    ";break}h.form_config[r.name]=r});$.extend(h.event_list,d);return g},$create_event_config:function(e){var d={};if(typeof e.name==="undefined"){return{}}$.each(this.event_type,function(g,f){if(e[f]){d[(f==="event"?"click":f)]={type:e.type,event:e[f],cust:(["select","checkbox","radio"].indexOf(e.type)>-1?true:false),config:e}}});return d},$reader_style:function(e){var d="";if(typeof e==="string"){return e}if(typeof e==="undefined"){return""}$.each(e,function(f,g){d+=f+":"+g+";"});return d},$local_refresh:function(e,d){this.element.find("[data-name="+e+"]").replaceWith(this.$reader_form_find(d))},$reader_select:function(l,d,e,j){var i=this,k="",h="",g={};if(!Array.isArray(l.list)){var f=l.list;bt_tools.send({url:f.url,data:f.param||{}},function(m){if(m.status!==false){l.list=l.list.dataFilter?l.list.dataFilter(m):m;i.$replace_render_content(j)}else{bt.msg(m)}})}$.each(l.list,function(n,m){try{if(m.value===l.value){g=m}else{g=l.list[0]}}catch(o){}k+='
                  • '+m.title+"
                  • ";h+='"});if(!g.title&&Array.isArray(l.list)){g=l.list[0]}return'
                    '+(g.title||"Getting data...")+'
                      '+(k||"")+"
                    "+(h||"")+"
                    "},$replace_render_content:function(e){var f=this,d=this.config.form[e];$("[data-form="+f.random+"]").find(".line:eq("+e+")").replaceWith(f.$reader_content_row(e,d))},$event_bind:function(f,g){var e=this,d={};e.element=$(typeof f==="object"?e.element:("[data-form="+e.random+"]"));if(typeof f==="undefined"){d=e.event_list}console.log(d);$.each(d,function(h,i){if($.isEmptyObject(i)){return true}$.each(i,function(l,j){var k="";if(typeof j.cust==="boolean"){k="["+(j.cust?"data-":"")+"name="+h+"]"}else{k="."+h}(function(m,n){if(m.onEvent===false){switch(m.type){case"input_checked":$(k).on(l!="event"?l:"click",function(o){m.event.apply(this,[o,e])});break}return true}else{e.element.on(l!="event"?l:"click",m.children?m.children:k,function(s){var r=e.$get_form_element(true),t=e.$get_form_value(),p=e.form_config[n];switch(m.type){case"textarea_tips":$(this).hide().prev().focus();break;case"custom_select":if($(this).parent().hasClass("bt-disabled")){return false}var o=$(this).next();if(!o.hasClass("show")){$(".bt_select_list").removeClass("show");o.addClass("show")}else{o.removeClass("show")}$(document).click(function(){e.element.find(".bt_select_list").removeClass("show");$(this).unbind("click");return false});return false;break;case"custom_select_item":p=e.form_config[$(this).parents(".bt_select_updown").attr("data-name")],item_config=p.list[$(this).index()];if($(this).hasClass("disabled")){$(this).parent().removeClass("show");if(item_config.tips){layer.msg(item_config.tips,{icon:2})}return true}if(!$(this).hasClass("active")&&!$(this).hasClass("disabled")){$(this).parent().prev().find(".bt_select_content").text($(this).text());$(this).addClass("active").siblings().removeClass("active");$(this).parent().next().val(item_config.value.toString());$(this).parent().removeClass("show");$(this).parent().next().trigger("change")}break;case"select_path":bt.select_path("event_"+$(this).prev().attr("name")+"_"+e.random,m.config.icon.select||"");break;case"checkbox":var q=$(this).is(":checked");if(q){$(this).prev().addClass("active")}else{$(this).prev().removeClass("active")}break}if(m.event){m.event.apply(this,[t,r,e,p,s])}if(m.added){m.added.apply(this,[s,p,r])}})}}(j,h))})});if(g){g()}},$get_form_value:function(){return this.element.serializeObject()},$set_find_value:function(e,g){var d={},f=this;typeof e!="string"?d=e:d[e]=g;$.each(d,function(h,i){f.form_element[h].val(i)})},$get_form_element:function(f){var e={},d=this;if(f||$.isEmptyObject(d.form_element)){this.element.find(":input").each(function(g){e[$(this).attr("name")]=$(this)});d.form_element=e;return e}else{return d.form_element}},$verify_group:function(d,f){var e=this,g="";$.each(f,function(h,i){if(typeof d[i]==="undefined"){return true}if(["disabled","readonly"].indexOf(i)>-1){g+=" "+(d[i]?(i+'="'+i+'"'):"")}else{g+=" "+i+'="'+d[i]+'"'}});return g},$verify_bind_event:function(e,g,f){var d={};$.each(f,function(i,h){var j=g[h];if(j){if(typeof d[e]==="object"){if(!Array.isArray(d[e])){d[e]=[d[e]]}d[e].push({event:j,eventType:h})}else{d[e]={event:j,eventType:h}}}});return d},$verify:function(f,d,e){if(!f){return""}if(e===true){return f?" "+d:""}if(e==="style"){return d?d+":"+f+";":f}return d?" "+d+'="'+f+'"':" "+f},$verify_form:function(){var k={},e=this.config.form,j=this.$get_form_value(),g=this.$get_form_element(true);for(var m=0;m'+l.title+"";g+='
                    '+(m?l.content:"")+"
                    "});i.element=$('
                    '+h+'
                    '+g+"
                    ");return i.element[0].outerHTML},$reader_find:function(){},$event_bind:function(){var e=this,d=e.theme,f=d.active||"active";if(!e.el){e.element=$("#tab_"+e.random)}e.element.on("click",("."+d.nav.replace(/\s+/g,".")+" span"),function(){var h=$(this).index(),g=e.config.list[h];$(this).addClass(f).siblings().removeClass(f);$("."+d.body+">div:eq("+h+")").addClass(f).siblings().removeClass(f);e.active=h;if(!g.init){$("."+d.body+">div:eq("+h+")").html(g.content);if(g.success){g.success()}g.init=true}})}};return new c(a)},load:function(b){var a=layer.msg(b+",please wait...",{icon:16,time:0,shade:0.3});if(b===true){a=layer.load()}return{close:function(){layer.close(a)}}},open:function(a){var d={},c=null,b=null;d=$.extend({type:1,area:"640px",closeBtn:2,btn:["Yes","No"]},a);if(typeof d.content=="object"){var e=d.content;b=bt_tools.form(e);d.success=function(f,g){b.$event_bind();if(typeof d.init!="undefined"){d.init(f,g)}};d.yes=function(i,f){var g=b.$verify_form();if(!g){return false}if(typeof a.yes!="undefined"){var h=a.yes.apply(b,[g,i,f]);if(!h){return false}}};d.content=b.$reader_content()}c=layer.open(d);return{close:function(){layer.close(c)},form:b}},msg:function(e,c){var b=null,d="",a={};if(typeof e==="object"){if(typeof e.status==="boolean"){d=e.msg,a={icon:e.status?1:2}}}if(typeof e==="string"){d=e,a={icon:typeof c!=="undefined"?c:1}}b=layer.msg(d,a);return{close:function(){layer.close(b)}}},$verify:function(c,a,b){if(!c){return""}if(b===true){return c?" "+a:""}if(b==="style"){return a?a+":"+c+";":c}return a?" "+a+'="'+c+'"':" "+c},select_path:function(a,f,d,b){if(typeof d!=="number"){d=1}if(typeof b!=="number"){b=false}bt.set_cookie("Path","/www/server/panel/BTPanel/static");var e=this,c={type:d,type_tips:d==0?"目录":(d==1?"文件":"目录或文件"),type_limit:d==0?"dir":(d==1?"file":"all"),select_list:[],select_path:bt.get_cookie("Path")||(bt.os=="Windows"?setup_path:"/www/wwwroot"),select_config:{},scroll_width:0,file_path:bt.get_cookie("Path"),file_operating:[],area:[window.innerWidth,window.innerHeight],reader_view:function(){var g=this;this.scroll_width=c.getScrollbarWidth();layer.open({type:1,title:a.title||("选择"+g.type_tips),shadeClose:false,closeBtn:2,area:["650px","555px"],content:'
                    名称修改时间类型
                    文件修改时间类型
                    '+g.type_tips+'名:
                    ',success:function(){g.render_file_list();$(".select_list_thaed").css("right",g.scroll_width+"px")}})},render_file_list:function(j,l){var h="",i="",k=this,g={path:this.select_path,sort:"type",disk:true};if(typeof j=="undefined"){j=g}if(typeof j=="function"){l=j,j=g}k.select_config=$.extend(g,j);e.$http("GetDir",k.select_config,function(n){var m=n.DISK,o=$.merge(k.data_reconstruction(n.DIR,"DIR"),k.data_reconstruction(n.FILES));k.select_list=o;k.render_path_list();$.each(m,function(q,r){var p=(r.path=="/"?"根目录":r.path.indexOf(":/")>-1?("本地磁盘("+r.path.match(/[A-Z]+/)[0])+":)":r.path);h+='
                    '+p+"
                    "});$.each(o,function(q,s){if((k.type==0)&&s.type!=k.type_limit){return true}var p=bt.format_data(s.mtime),r=(s.type=="dir"?"文件夹":"文件");i+=' '+s.filename+" "+p+" "+(s.type=="dir"?"文件夹":"文件")+" "});$("#select_mount_list").html(h);$("#select_dir_list").html(i);if(l){l(n)}})},data_reconstruction:function(i,h,j){if(i.length<1){return[]}var g=[];$.each(i,function(k,n){var l=n.split(";"),o="",p=l[0].split("."),m=p[p.length-1];switch(l[0]){case".user.ini":o="PS: PHP用户配置文件(防跨站)!";break;case".htaccess":o="PS: Apache用户配置文件(伪静态)";break;case"swap":o="PS: 宝塔默认设置的SWAP交换分区文件";break}if(l[0].indexOf("Recycle_bin")!=-1){o="PS: 回收站目录,勿动!"}if(l[0].indexOf(".upload.tmp")!=-1){o="PS: 宝塔文件上传临时文件,重新上传从断点续传,可删除"}g.push({caret:l[8]=="1"?true:false,down_id:l[9],ext:(h=="DIR"?"":m),filename:l[0],mtime:l[2],ps:o||l[10],size:l[1],type:h=="DIR"?"dir":"file",user:l[3],root_level:l[4]})});return g},render_path_list:function(o){var n=this,k='
                    ',h="",m=this.file_path.split("/").splice(1),l=this.file_path.split("/")[0];if(bt.os==="Windows"){if(m.length==0){m=[]}m.unshift('本地磁盘('+l+")")}else{if(this.file_path=="/"){m=[]}m.unshift("根目录")}for(var j=0;j '+m[j]+' '}$(".path_input").val("").attr("data-path",this.file_path);var g=$(".file_path_input .file_dir_view");g.html(k);g.attr("data-width",g.width());n.set_dir_view_resize()},set_select_width:function(j,i){var k=this,h=".select_dir_list tbody td:nth-child("+(j+1)+")>span,.select_dir_list thead th:nth-child("+(j+1)+")>span",g=$("#th-index-"+j);if(g.length>0){g.html(h+"{"+i+"}")}else{$("#select_file_style").append('")}},cut_style_object:function(h){var g={},i=h.split(";");console.log(i);return g},getScrollbarWidth:function(){var k=document.createElement("div"),j={width:"100px",height:"100px",overflowY:"scroll"},g,h;for(g in j){k.style[g]=j[g]}document.body.appendChild(k);h=k.offsetWidth-k.clientWidth;k.remove();return h},set_dir_view_resize:function(){var i=$(".file_path_input"),g=$(".file_path_input .file_dir_view"),k=g.attr("data-width"),j=null;if(k){parseInt(k)}else{k=g.width();g.attr("data-width",k)}if(g.width()-k<90){var h=0;$($(".file_path_input .file_dir_view .file_dir_item").toArray().reverse()).each(function(){var l=0;if(!$(this).attr("data-width")){$(this).attr("data-width",$(this).width());l=$(this).width()}else{l=parseInt($(this).attr("data-width"))}h+=l;if((i.width()-h)<=90){$(this).addClass("hide")}else{$(this).removeClass("hide")}})}var j=g.children(".file_dir_item.hide").clone(true);if(g.children(".file_dir_item.hide").length==0){i.removeClass("active").find(".file_dir_omit").addClass("hide")}else{j.each(function(){if($(this).find(".glyphicon-hdd").length==0){$(this).find(".file_dir").before('')}});i.addClass("active").find(".file_dir_omit").removeClass("hide");i.find(".file_dir_omit .nav_down_list").empty().append(j);i.find(".file_dir_omit .nav_down_list .file_dir_item").removeClass("hide")}},reader_file_list:function(h,k){var j=this,g="",i="";if(typeof h==="function"){k=h,h={is_operating:false}}if(typeof h==="undefined"){h={is_operating:false}}if(b){layer.msg("只能在该目录下操作",{icon:2});return false}this.loadT=bt.load("正在获取文件列表,请稍候...");this.file_images_list=[];j.get_dir_list(h,function(n){j.loadT.close();j.file_list=$.merge(j.data_reconstruction(n.DIR,"DIR"),j.data_reconstruction(n.FILES));j.file_path=n.PATH;j.is_recycle=n.FILE_RECYCLE;j.file_store_list=n.STORE;bt.set_cookie("Path",n.PATH);var m="",p="",q=n.DISK,r=j.file_list;j.select_list=j.file_list;j.render_path_list();$.each(q,function(t,u){var s=(u.path=="/"?"根目录":u.path.indexOf(":/")>-1?("本地磁盘("+u.path.match(/[A-Z]+/)[0])+":)":u.path);m+='
                    '+s+"
                    "});$.each(r,function(t,v){if((j.type==0)&&v.type!=j.type_limit){return true}var s=bt.format_data(v.mtime),u=(v.type=="dir"?"文件夹":"文件");p+=' '+v.filename+" "+s+" "+(v.type=="dir"?"文件夹":"文件")+" "});$("#select_mount_list").html(m);$("#select_dir_list").html(p);var o=n.PATH.lastIndexOf("/"),l=n.PATH.substring(o+1,n.PATH.length);if(k){k(rdata)}})},reader_file_list_content:function(i,k){var g="",j=this,h=0;$.each(i,function(l,n){var m=n.filename+n.ps;j.file_list[l]=n=j.$file_data_dispose(n);j.file_list[l]["only_index"]=l;if(n.filename.indexOf("Recycle_bin")){_tips="PS: 回收站目录,勿动!"}if(m.length>20){m=m.substring(0,20)+"..."}if(bt.check_chinese(m)&&m.length>10){m=m.substring(0,10)+"..."}g+='
                    '+n.filename+n.ps+""+(n.caret?'':"")+(n.down_id?'':"")+'
                    '+n.type_tips+'
                    '+(n.type=="dir"?'点击计算':bt.format_size(n.size))+'
                    '+bt.format_data(n.mtime)+"
                    ";if(n.type=="dir"){h++}if(n.ispreview){j.file_images_list.push(n.path);if(typeof n.images_id){n.images_id=j.file_images_list.length-1}}});$(".file_list_content").html(g);if(k){k({is_dir_num:h})}},$file_data_dispose:function(g){var h={languages:null,model:null};return $.extend(g,{only_id:bt.get_random(10),type_tips:g.type==="dir"?"文件夹":this.ext_type_tips(g.ext),open_type:this.determine_file_type(g.ext),languages:h.languages,path:g.path||this.path_resolve(this.file_path,g.filename),model:h.model})},path_resolve:function(j,i){var h="",g="";if(!Array.isArray(i)){i=[i]}j.replace(/([\/|\/]*)$/,function(k){g=k;return"www"});$.each(i,function(k,l){h+="/"+l});return j+h},$get_file_model:function(k){var h=this.vscode_editor.config;for(languages in h.supportedModes){var i=h.supportedModes[languages];for(var g=0;g'+(k.path=="/"?"根目录":k.path)+" ("+k.size[2]+")"});$(".mount_disk_list").html(g)})},determine_file_type:function(j,i){var g={images:["jpg","jpeg","png","bmp","gif","tiff","ico"],compress:["zip","rar","gz","war","tgz"],video:["mp4","mpeg","mpg","mov","avi","webm","mkv"],ont_text:["iso","xlsx","xsl","doc","docx","tiff","exe","so","7z","bz","dmg","apk"]},h=false;if(i!=undefined){if(i=="text"){$.each(g,function(k,l){$.each(l,function(n,m){if(m==j){h=true;return false}})});h=!h}else{if(typeof g[i]=="undefined"){return false}$.each(g[i],function(k,l){if(l==j){h=true;return false}})}}else{$.each(g,function(k,l){$.each(l,function(n,m){if(m==j){h=k;return false}})});if(typeof h=="boolean"){h="text"}}return h},render_file_groud_menu:function(l,g){var j=this,k=$(g).data("index"),h=j.file_list[k],o=[["open","打开"],["split",""],["download","下载"],["share","分享目录/文件"],["cancel_share","取消分享"],["favorites","收藏目录/文件"],["cancel_favorites","取消收藏"],["split",""],["dir_kill","目录查杀"],["authority","权限"],["split",""],["copy","复制"],["shear","剪切"],["rename","重命名"],["del","删除"],["split",""],["killing","创建压缩",[["gzip","tar.gz (推荐)"],["zip","zip (通用格式)"],["rar","rar (中文兼容较好)"]]],["unzip","解压",[["local","解压到当前"],["folad","解压到当前"]]]],n=["zip","rar","gz","war","tgz","bz2"],m=0;if(h.type=="dir"){o.splice(2,1);m++}if(h.down_id!==0){o.splice(3-m,1);m++}else{o.splice(4-m,1);o[3-m][1]=(h.type=="dir"?"分享目录":"分享文件");m++}if(h.caret!==false){o.splice((5-m),1);m++}else{o.splice((6-m),1);o[5-m][1]=(h.type=="dir"?"收藏目录":"收藏文件");m++}if(h.ext!="php"&&h.type!="dir"){o.splice((8-m),1);m++}var i=0;$.each(n,function(p,q){if(q==h.ext){i++}});if(i==0){o.splice((17-m),1);m++}j.reader_menu_list({el:$(".selection_right_menu"),ev:l,data:h,list:o})},render_file_all_menu:function(i,h){var k=this,j=[["refresh","刷新"],["split",""],["upload","上传"],["create","新建文件夹/文件",[["create_dir","新建文件夹"],["create_files","新建文件"]]],["split",""],["paste","粘贴"]],g=0;if(!bt.get_storage("session","copy_path")){j.splice(5,1);g++}k.reader_menu_list({el:$(".selection_right_menu"),ev:i,data:{},list:j})},get_dir_list:function(h,j,g){var i=this;if(typeof j==="boolean"){g=j,j=null}e.$http("GetDir",$.extend({disk:true,path:i.file_path,sort:bt.get_cookie("files_sort")||"type"},h),j,g)},retrun_prev_path:function(g){var h=g.split("/");h.splice(h.length-1);return h.join("/")},reader_menu_list:function(h){var l=this,j=h.el.find("ul"),i=j.height(),g=j.width(),k=h.ev.clientX-((this.area[0]-h.ev.clientX)')}else{if(Array.isArray(p[2])){m=$('
                      ');n=m.find(".set_group");$.each(p[2],function(r,q){n.append($('
                    • '+q[1]+"
                    • ").on("click",{type:q[0],data:h.data},function(s){l.file_groud_event($.extend(s.data.data,{open:s.data.type,index:parseInt($(h.ev.currentTarget).data("index")),element:h.ev.currentTarget,type_tips:p.type?"文件夹":"文件"}));h.el.removeAttr("style");s.stopPropagation();s.preventDefault()}))})}j.append($('
                    • '+p[1]+"
                    • ").append(m).on("click",{type:p[0],data:h.data},function(q){l.file_groud_event($.extend(q.data.data,{open:q.data.type,index:parseInt($(h.ev.currentTarget).data("index")),element:h.ev.currentTarget,type_tips:p.type?"文件夹":"文件"}));h.el.removeAttr("style");q.stopPropagation();q.preventDefault()}))}});h.el.css({left:k,top:h.ev.clientY-((this.area[1]-h.ev.clientY)0){$(".select_list_shadow").show()}else{$(".select_list_shadow").hide()}if(h>=0){$(".select_list_thaed").css("left",(4-h)+"px")}j.stopPropagation();j.preventDefault()});$(".file_path_refresh").on("click",function(){g.render_file_list()});$(".select_dir_list thead th .icon-drag").on("mousedown",function(m){var o=m.clientX,h=$(this).parent(),j=h.index(),p=h[0].clientWidth,i=parseInt($(this).parent().attr("data-min")),n=null;if(m.which===1){var l=function(t){var r=t.clientX,s=r-o,q=p+s;n=setTimeout(function(){g.set_select_width(j,"width:"+q+"px")},0)},k=function(){console.log(k);$(this).unbind(l);$(this).unbind(k)};$(document).on("mousemove",l).one("mouseup",function(){$(this).unbind(l);$(this).unbind(this)})}m.stopPropagation()});$(".select_dir_list thead th>span").on("click",function(j){var i=$(this).parent(),h=i.data("type"),k=i.hasClass("active"),l=i.hasClass("sort");if(k){i.addClass("sort").removeClass("active")}else{if(l){i.addClass("active").removeClass("sort")}else{i.addClass("active")}}i.siblings().removeClass("active sort");g.render_file_list({sort:h,reverse:k?1:0});j.stopPropagation()});$(".search_path_views input").on("keyup",function(){var h=$(this).val();console.log(h)});$(".search_path_views input").focus(function(){$(this).next().show()}).blur(function(){$(this).next().hide()});$("#select_file_directory .select_file_group").on("click",".select_btn_group .btn-success",function(h){var j=$('[name="select_name"]').val(),i="";if(j==""){layer.msg("只能选择"+g.type_tips,{icon:2})}else{i=g.file_path+"/"+j;console.log(i)}});$("#select_file_directory .select_file_tootls").on("click",".creat_dir",function(i){var h="   ";if($("#tbody tr").length==0){$("#select_dir_list").append(h)}else{$("#select_dir_list tr:first-child").before(h)}$(".newFolderName").focus();$("#nameOk").click(function(){var k=$("#newFolderName").val(),j=$(".file_path_views .path_input").attr("data-path");newTxt=j+"/"+k;e.$http("CreateDir",{path:newTxt},function(l){if(l.status==true){g.reader_file_list({path:j,is_operating:false});layer.msg(l.msg,{icon:1})}else{layer.msg(l.msg,{icon:2})}})})});$("#select_mount_list").on("click",".item",function(){g.reader_file_list({path:$(this).attr("data-menu"),is_operating:true})});$(window).resize(function(h){if($(this)[0].innerHeight!=g.area[1]){g.area[1]=$(this)[0].innerHeight;g.set_file_view()}if($(this)[0].innerWidth!=g.area[0]){g.area[0]=$(this)[0].innerWidth;g.set_dir_view_resize()}if(g.vscode_editor.view){if(g.vscode_editor.is_full_min>0){layer.style(g.vscode_editor.view,{top:0,left:0,width:g.area[0],height:g.area[1]})}}if(g.vscode_editor.view&&$.isEmptyObject(g.vscode_editor.list)){g.vscode.layout()}}).keydown(function(j){j=window.event||j;var i=j.keyCode,h=j.target.tagName.toLowerCase();if(i==8&&h!=="input"&&h!=="textarea"){if(g.vscode_editor.view==null){$(".forward_path span:eq(0)").click()}return false}});$(".file_path_input .path_input").on("focus blur keyup",function(i){i=i||window.event;var h=$(this).attr("data-path");switch(i.type){case"focus":$(this).addClass("focus").val(h).prev().hide();break;case"blur":$(this).removeClass("focus").val("").prev().show();break;case"keyup":if(i.keyCode!=13&&i.type=="keyup"){return false}var j=$(this);if($(this).data("path")!=$(this).val()){g.reader_file_list({path:$(this).val(),is_operating:true},function(k){if(k.status===false){$(j).val(h)}else{$(j).val(k.PATH);$(j).blur().prev().show()}})}break}i.stopPropagation()});$(".file_path_input .file_dir_view").on("click",".file_dir",function(){g.reader_file_list({path:$(this).attr("title"),is_operating:true})});$(".forward_path span").click(function(){var h=$(this).index(),i="";if(!$(this).hasClass("active")){switch(h){case 0:g.file_pointer=g.file_pointer-1;i=g.retrun_prev_path(g.file_path);break;case 1:g.file_pointer=g.file_pointer+1;i=g.file_path+"/"+$(".select_file_group .file_directory").val();break;case 2:g.file_pointer=g.file_pointer-1;i=g.retrun_prev_path(g.file_path);break}g.reader_file_list({path:i,is_operating:false})}});$(".file_path_input .file_dir_view").on("click",".file_dir_omit",function(i){var j=this,h=$(this).children(".nav_down_list");$(this).addClass("active");h.addClass("show");$(document).one("click",function(){$(j).removeClass("active");h.removeClass("show");i.stopPropagation()});i.stopPropagation()});$("#select_dir_list").on("dblclick","tr",function(j){if($(j.target).hasClass("file_check")){return false}var i=$(this).attr("data-path"),h=$(this).attr("data-type");if(h=="dir"){g.reader_file_list({path:g.file_path+"/"+i})}else{}j.stopPropagation();j.preventDefault()});$(".file_path_refresh").click(function(){g.reader_file_list({path:g.file_path})});$(".file_nav_view .upload_or_download").on("click",function(h){g.open_upload_view();h.stopPropagation();h.preventDefault()});$(".file_nav_view .upload_or_download li").on("click",function(i){var h=$(this).data("type");if(h==="uploadFile"){g.open_upload_view()}else{g.open_download_view()}i.stopPropagation();i.preventDefault()});$(".mount_disk_list").on("click",".nav_btn",function(){var h=$(this).data("menu");g.reader_file_list({path:h})});$(".file_list_header").on("click",".file_name,.file_size,.file_mtime,.file_accept,.file_user",function(j){var k=$(this).attr("data-tid"),h=$(this).find(".icon_sort").hasClass("active"),i=$(this).hasClass("active");if(!$(this).find(".icon_sort").hasClass("active")&&$(this).hasClass("active")){$(this).find(".icon_sort").addClass("active")}else{$(this).find(".icon_sort").removeClass("active")}$(this).addClass("active").siblings().removeClass("active").find(".icon_sort").removeClass("active").empty();$(this).find(".icon_sort").html('');if(!i){h=true}bt.set_cookie("files_sort",k);bt.set_cookie("name_reverse",h?1:0);g.reader_file_list();return false});$(".file_list_header .file_th").each(function(i,k){var h=bt.get_cookie("files_sort"),j=bt.get_cookie("name_reverse");if($(this).attr("data-tid")===h){$(this).addClass("active").siblings().removeClass("active").find(".icon_sort").removeClass("active").empty();$(this).find(".icon_sort").html('');if(j===0){$(this).find(".icon_sort").addClass("active")}}});$(".file_list_header .file_check").on("click",function(i){var h=parseInt($(this).data("checkbox"));switch(h){case 0:$(this).addClass("active").removeClass("active_2").data("checkbox",1);$(".file_list_content .file_tr").addClass("active").removeClass("active_2");g.file_table_arry=g.file_list;break;case 2:$(this).addClass("active").removeClass("active_2").data("checkbox",1);$(".file_list_content .file_tr").addClass("active");g.file_table_arry=g.file_list;break;case 1:$(this).removeClass("active active_2").data("checkbox",0);$(".file_list_content .file_tr").removeClass("active");g.file_table_arry=[];break}});$(".file_list_content").on("click",".file_check",function(l){var i=$(this).parents(".file_tr"),k=i.data("index"),h=$(".file_list_header .file_check"),j=i.attr("data-filename");$(".selection_right_menu").removeAttr("style");if(i.hasClass("active")){i.removeClass("active");g.remove_check_file(g.file_table_arry,"filename",j);if(g.file_table_arry.length>0){h.addClass("active_2").removeClass("active").data("checkbox",2)}else{if(g.file_table_arry.length==0){h.removeClass("active active_2").data("checkbox",0)}}}else{i.addClass("active");i.attr("data-filename",g.file_list[k]["filename"]);if(g.file_table_arry.length==g.file_list.length){h.addClass("active").removeClass("active_2").data("checkbox",1)}else{h.addClass("active_2").removeClass("active").data("checkbox",2)}g.file_table_arry.push(g.file_list[k])}l.stopPropagation()});$(".file_list_content").scroll(function(h){if($(this).scrollTop()==($(this)[0].scrollHeight-$(this)[0].clientHeight)){$(this).prev().css("opacity",1);$(this).next().css("opacity",0)}else{if($(this).scrollTop()>0){$(this).prev().css("opacity",1)}else{if($(this).scrollTop()==0){$(this).prev().css("opacity",0);$(this).next().css("opacity",1)}}}});$(".file_table_view .file_list_content").on("click",".file_tr",function(h){$(".selection_right_menu").removeAttr("style");$(this).find(".file_checkbox .file_check").click();h.stopPropagation();h.preventDefault()});$(".file_table_view .file_list_content").on("click",".file_title i",function(k){var i=$(this).parents(".file_tr"),h=i.data("index"),j=g.file_list[h];if(j.type=="dir"){g.reader_file_list({path:g.file_path+"/"+j.filename})}else{}k.stopPropagation()});$(".file_table_view .file_list_content").on("click",".file_name .icon-share1",function(k){var i=$(this).parents(".file_tr"),h=i.data("index"),j=g.file_list[h];g.info_file_share(j,i);k.stopPropagation()});$(".file_table_view .file_list_content").on("click",".file_name .icon-favorites",function(k){var i=$(this).parents(".file_tr"),h=i.data("index"),j=g.file_list[h];j.typeText=j.type?"文件夹":"文件";g.cancel_file_favorites(j,i);k.stopPropagation()});$(".file_table_view .file_list_content").on("dblclick",".file_tr",function(j){if($(j.target).hasClass("file_check")){return false}var h=$(this).data("index"),i=g.file_list[h];if(i.type=="dir"){g.reader_file_list({path:g.file_path+"/"+i.filename})}else{}j.stopPropagation();j.preventDefault()});$(".file_list_content").on("contextmenu",".file_tr",function(i){var h=this;if(i.which==3){g.render_file_groud_menu(i,this);$(".content_right_menu").removeAttr("style");$(this).addClass("selected").siblings().removeClass("selected");$(document).one("click",function(j){$(h).removeClass("selected");$(".selection_right_menu").removeAttr("style");j.stopPropagation();j.preventDefault()})}i.stopPropagation();i.preventDefault()});$(".file_list_content").on("contextmenu",function(l){var h=$(".content_right_menu"),k=h.width(),j=h.height(),i=this;if(l.which==3){$(".selection_right_menu").removeAttr("style");g.render_file_all_menu(l,this)}l.stopPropagation();l.preventDefault()});$(".filePage").on("change",".showRow",function(){var h=$(this).val();bt.set_storage("showRow",h);g.reader_file_list()});$(".file_list_content").on("click",".folder_size",function(i){var h=j.file_list[$(this).parents(".file_tr").data("index")],j=this;j.get_file_size({path:h.path},function(k){$(j).text(bt.format_size(k.size))});i.stopPropagation();i.preventDefault()});$(".cut_view_model").on("click",function(){var h=$(this).data("type");$(".file_table_view").addClass(h=="icon"?"icon_view":"list_view").removeClass(h!="icon"?"icon_view":"list_view");$(this).addClass("active").siblings().removeClass("active")})},set_file_forward:function(){var h=this,g=$(".forward_path span");console.log(h.file_operation);if(h.file_operating.length==1){g.addClass("active")}else{if(h.file_pointer==h.file_operating.length-1){g.eq(0).removeClass("active");g.eq(1).addClass("active")}else{if(h.file_pointer==0){g.eq(0).addClass("active");g.eq(1).removeClass("active")}else{g.removeClass("active")}}}},set_file_view:function(){var h=$(".file_list_content"),g=this.area[1]-170;$(".file_bodys").height(this.area[1]-100);if((this.file_list.length*50)>g){h.attr("data-height",h.data("height")||h.height()).height(g);$(".file_shadow_bottom").css("opacity",1)}else{h.height(g);$(".file_shadow_top,.file_shadow_bottom").css("opacity",0)}},clear_table_active:function(){this.file_table_arry=[];$(".file_list_header .file_check").removeClass("active active_2");$(".file_list_content .file_tr").removeClass("active")}};c.reader_view();c.event_bind()},$fixed_table_thead:function(a){$(a).scroll(function(){var b=this.scrollTop;this.querySelector("thead").style.transform="translateY("+b+"px)"})},send:function(g,e,c,b,a,l){var h={},k=null,i=null,f=[],j="";$.each(arguments,function(n,m){f.push([m,typeof m])});function d(n){try{k=f[n][1]=="function"?f[n][0]:null;m=f[(n+1)][1]=="function"?f[(n+1)][0]:null}catch(m){}}j=f[0];switch(j[1]){case"string":$.each(f,function(n,m){var p=m[0],o=m[1];if(n>1&&(o=="boolean"||o=="string"||o=="object")){var q=j[0].split("/");h.url="/"+q[0]+"?action="+q[1];h.load=p;if(o=="object"){h.load=p.load;h.tips=p.tips;h.verify=p.verify}return false}else{h.url=j[0]}});if(f[1][1]==="object"){h.data=f[1][0];d(2)}else{d(1)}break;case"object":h.url=j[0].url;h.data=j[0].data||{};$.each(f,function(n,m){var p=m[0],o=m[1];if(n>1&&(o=="boolean"||o=="string"||o=="object")){h.load=m;if(o=="object"){h.load=p.load;h.tips=p.tips}return true}});if(f[1][1]==="object"){h.data=f[1][0];d(2)}else{d(1)}break}if(h.load){h.load=this.load(h.load)}$.ajax({type:h.type||"POST",url:h.url,data:h.data||{},dataType:h.dataType||"JSON",complete:function(){if(h.load){h.load.close()}},success:function(m){if(h.verify){if(k){k(m)}return false}if(typeof m==="string"){layer.msg(m,{icon:2,time:0,closeBtn:2});return false}if(h.bacth){if(k){k(m)}return false}if(m.status===false){bt_tools.msg(m);return false}if(h.tips){bt_tools.msg(m)}if(k){k(m)}}})},command_line_output:function(b){var c=this,d=bt.get_random(15);function a(e){var i=this;for(var g in c.commandConnectionPool){var h=c.commandConnectionPool[g],f=$(h.config.el);if(e.shell===h.config.shell&&f.length){h.el=f;return h}}if(typeof e==="undefined"){e={}}this.config=$.extend({route:"/sock_shell"},e);this.xterm_config=$.extend(this.xterm_config,this.config.xterm);this.el=$(this.config.el);this.open=e.open;this.close=e.close;this.message=e.message;if(!this.config.hasOwnProperty("el")){c.msg({msg:"请输入选择器element,不可为空",status:false});return false}if(!this.config.hasOwnProperty("shell")){c.msg({msg:"请输入命令,不可为空",status:false});return false}if(this.config.hasOwnProperty("time")){setTimeout(function(){i.close_connect()},this.config.time)}this.init()}a.prototype={socket:null,socketToken:null,timeout:0,monitor_interval:2000,element_detection:null,uuid:d,fragment:[],error:0,init:function(){var e=bt.get_cookie("commandInputViewUUID"),f=this;if(!this.el[0]){if(this.error>10){return false}setTimeout(function(){f.init();this.error++},2000);return false}this.error=0;if(this.el[0].localName!=="pre"){this.el.append('
                      ');this.el=this.el.find("pre");this.config.el=this.config.el+" pre"}else{this.el.addClass("command_output_pre")}if(Array.isArray(this.config.area)){this.el.css({width:this.config.area[0],height:this.config.area[1]})}else{this.el.css({width:"100%",height:"100%"})}if(e&&typeof c.commandConnectionPool[e]!="undefined"){c.commandConnectionPool[e].close_connect();delete c.commandConnectionPool[e]}bt.set_cookie("commandInputViewUUID",this.uuid);this.element_detection=setInterval(function(){if(!$(f.config.el).length){clearInterval(f.element_detection);f.close_connect()}},1*60*1000);this.set_full_screen();this.create_websocket_connect(this.config.route,this.config.shell);this.monitor_element()},create_websocket_connect:function(e,f){var g=this;this.socket=new WebSocket((location.protocol==="http:"?"ws://":"wss://")+location.host+e);this.socket.addEventListener("open",function(h){if(!this.socketToken){var i=document.getElementById("request_token_head").getAttribute("token");this.socketToken={"x-http-token":i}}this.send(JSON.stringify(this.socketToken));this.send(f);if(g.open){g.open()}});this.socket.addEventListener("close",function(h){if(h.code!==1000){g.socket=g.create_websocket_connect(g.config.route,g.config.shell)}if(g.close){g.close(h)}});this.socket.addEventListener("message",function(i){var h=i.data;if(!h){return}g.refresh_data(h);if(g.message){g.message(h)}});return this.socket},set_full_screen:function(){},refresh_data:function(e){this.fragment.push(e);if(this.fragment.length>=300){this.fragment.splice(0,150);this.el.html(this.fragment.join(""))}else{this.el.append(e)}this.el.scrollTop(this.el[0].scrollHeight)},monitor_element:function(){var e=this;this.monitor_interval=setInterval(function(){if(!e.el.length){e.close_connect();clearInterval(e.monitor_interval)}},e.config.monitorTime||2000)},close_connect:function(){this.socket.send("");this.socket.close();delete c.commandConnectionPool[this.uuid]}};this.commandConnectionPool[d]=new a(b);return this.commandConnectionPool[d]}};$.fn.serializeObject=function(){var a=Object.prototype.hasOwnProperty;return this.serializeArray().reduce(function(b,c){if(!a.call(b,c.name)){b[c.name]=c.value}return b},{})};
                      \ No newline at end of file
                      diff --git a/BTPanel/static/language/English/lan.js b/BTPanel/static/language/English/lan.js
                      index 2f19e0a1..b4084aae 100644
                      --- a/BTPanel/static/language/English/lan.js
                      +++ b/BTPanel/static/language/English/lan.js
                      @@ -1006,7 +1006,7 @@ var lan = {
                       		"mysql_status_ps4":"If too low, increase innodb_buffer_pool_size",
                       		"mysql_status_ps5":"If too low, increase query_cache_size",
                       		"mysql_status_ps6":"If too high, increase tmp_table_size",
                      -		"mysql_status_ps7":"If too high, increase table_cache_size",
                      +		"mysql_status_ps7":"If too high, increase table_open_cache",
                       		"mysql_status_ps8":"If not 0, please check index of database table",
                       		"mysql_status_ps9":"If not 0, please check index of database table",
                       		"mysql_status_ps10":"If too high, increase sort_buffer_size",
                      diff --git a/BTPanel/static/language/Simplified_Chinese/lan.js b/BTPanel/static/language/Simplified_Chinese/lan.js
                      index d9005579..bb5215b6 100644
                      --- a/BTPanel/static/language/Simplified_Chinese/lan.js
                      +++ b/BTPanel/static/language/Simplified_Chinese/lan.js
                      @@ -947,7 +947,7 @@ var lan = {
                       		"mysql_status_ps4": "If too low, increase innodb_buffer_pool_size",
                       		"mysql_status_ps5": "If too low, increase query_cache_size",
                       		"mysql_status_ps6": "If too high, increase tmp_table_size",
                      -		"mysql_status_ps7": "If too high, increase table_cache_size",
                      +		"mysql_status_ps7": "If too high, increase table_open_cache",
                       		"mysql_status_ps8": "If not 0, please check index of DB table",
                       		"mysql_status_ps9": "If not 0, please check index of DB table",
                       		"mysql_status_ps10": "If too high, increase sort_buffer_size",
                      diff --git a/BTPanel/templates/default/files.html b/BTPanel/templates/default/files.html
                      index a05dadd3..986e1f9b 100644
                      --- a/BTPanel/templates/default/files.html
                      +++ b/BTPanel/templates/default/files.html
                      @@ -113,7 +113,7 @@
                                           
                                       
                                       
                       				
                      -            		
                      +
                      Search
                      -
                      +
                      New
                        -
                      • 新建文件夹
                      • -
                      • 新建文件
                      • +
                      • Folder
                      • +
                      • File
                      -
                      +
                      Refresh
                      diff --git a/BTPanel/templates/default/panel_error.html b/BTPanel/templates/default/panel_error.html new file mode 100644 index 00000000..4e67afc3 --- /dev/null +++ b/BTPanel/templates/default/panel_error.html @@ -0,0 +1,13 @@ +
                      +

                      An error occurred while the panel was running!

                      +
                      +

                      {error_title}

                      +
                      +
                      {request_info}
                      +
                      {error_msg}
                      +
                        +
                      • Sorry, an unexpected error occurred while the panel was running. Please try to resolve this error in the following order:
                      • +
                      • 1. Click the Fix button in the upper right corner of [Home], and log out of the panel and log in again.
                      • +
                      • 2. Still unresolved, please take a screenshot of this window and post on the forum for help, address:https://forum.aapanel.com/
                      • +
                      +
                      \ No newline at end of file diff --git a/BTPanel/templates/default/plugin_error.html b/BTPanel/templates/default/plugin_error.html new file mode 100644 index 00000000..117a6e8d --- /dev/null +++ b/BTPanel/templates/default/plugin_error.html @@ -0,0 +1,15 @@ +
                      +

                      Something went wrong, an error occurred while running [{plugin name}]!

                      +
                      +

                      {error_title}

                      +
                      +
                      {request_info}
                      +
                      {error_msg}
                      +
                        +
                      • Sorry, an unexpected error occurred while accessing the [{plugin name}] plugin. Please try to resolve this error in the following order:
                      • +
                      • 1. Click the Fix button in the upper right corner of [Home], and log out of the panel and log in again.
                      • +
                      • 2. If the plugin is not the latest version, try to update to the latest version, if it is the latest version, please try to reinstall the plugin, if it is a beta version, please try to switch to the official version
                      • +
                      • 3. If this plug-in is a third-party plug-in, try to contact the author for help
                      • +
                      • 4. If the above attempt fails to resolve this error, please take a screenshot of this window and post on the Pagoda Forum for helphttps://forum.aapanel.com
                      • +
                      +
                      \ No newline at end of file diff --git a/BTPanel/templates/default/soft.html b/BTPanel/templates/default/soft.html index f4b69753..3acbc8fe 100644 --- a/BTPanel/templates/default/soft.html +++ b/BTPanel/templates/default/soft.html @@ -31,6 +31,7 @@
                      {{data['lan']['PS']}}
                      +
                      Recently visited plugin:
                      @@ -51,6 +52,7 @@ bt.set_cookie('distribution', "{{session['config']['distribution']}}"); $(document).ready(function () { soft.get_list(); + soft.render_soft_recommend() setTimeout(function () { soft_td_width_auto(); }, 500); diff --git a/README.md b/README.md index 5f93dbdb..22cc8256 100644 --- a/README.md +++ b/README.md @@ -114,9 +114,9 @@ _convenient and efficient file manager integration , Support uploading, download #### Installation command: ##### Centos ```bash -yum install -y wget && wget -O install.sh http://www.aapanel.com/script/install_6.0_en.sh && bash install.sh +yum install -y wget && wget -O install.sh http://www.aapanel.com/script/install_6.0_en.sh && bash install.sh 66959f96 ``` ##### Ubuntu/Debian ```bash -wget -O install.sh http://www.aapanel.com/script/install-ubuntu_6.0_en.sh && sudo bash install.sh +wget -O install.sh http://www.aapanel.com/script/install-ubuntu_6.0_en.sh && sudo bash install.sh 66959f96 ``` diff --git a/class/apache.py b/class/apache.py index 426dae4e..7336f76a 100644 --- a/class/apache.py +++ b/class/apache.py @@ -117,6 +117,9 @@ class apache: def GetApacheValue(self): apachedefaultcontent = public.readFile(self.apachedefaultfile) apachempmcontent = public.readFile(self.apachempmfile) + if not "mpm_event_module" in apachempmcontent: + return public.returnMsg(False,"mpm_event_module conf not found or /www/server/apache/conf/extra/httpd-mpm.conf is empty") + apachempmcontent = re.search("\(\n|.)+?\",apachempmcontent).group() ps = ["%s,%s" % (public.GetMsg("SECOND"),public.GetMsg("REQUEST_TIMEOUT_TIME")), public.GetMsg("KEEP_ALIVE"), "%s,%s" % (public.GetMsg("SECOND"),public.GetMsg("CONNECT_TIMEOUT_TIME")), @@ -143,10 +146,12 @@ class apache: n += 1 ps = [public.GetMsg("DEFUALT_PROCESSES"), - public.GetMsg("MAX_SPARE_SERVERS"), - "%s,%s" % (public.GetMsg("MAX_CONNECTIONS"),public.GetMsg("NOT_LIMITED_BY_0")), - public.GetMsg("MAX_PROCESSES")] - gets = ["StartServers","MaxSpareServers","MaxConnectionsPerChild","MaxRequestWorkers"] + public.GetMsg("MAX_SPARE_THREADS"), + public.GetMsg("MIN_SPARE_THREADS"), + public.GetMsg("THREADS_PER_CHILD"), + public.GetMsg("MAX_REQUEST_WORKERS"), + public.GetMsg("MaxConnectionsPerChild")] + gets = ["StartServers","MaxSpareThreads","MinSpareThreads","ThreadsPerChild","MaxRequestWorkers","MaxConnectionsPerChild"] n = 0 for i in gets: rep = "(%s)\s+(\w+)" % i @@ -167,6 +172,8 @@ class apache: def SetApacheValue(self,get): apachedefaultcontent = public.readFile(self.apachedefaultfile) apachempmcontent = public.readFile(self.apachempmfile) + if not "mpm_event_module" in apachempmcontent: + return public.returnMsg(False,"mpm_event_module conf not found or /www/server/apache/conf/extra/httpd-mpm.conf is empty") conflist = [] getdict = get.__dict__ for i in getdict.keys(): @@ -176,7 +183,6 @@ class apache: "value": str(getdict[i]) } conflist.append(getpost) - public.writeFile("/tmp/list",str(conflist)) for c in conflist: if c["name"] == "KeepAlive": if not re.search("on|off", c["value"]): @@ -193,7 +199,7 @@ class apache: apachedefaultcontent = re.sub(rep,newconf,apachedefaultcontent) elif re.search(rep,apachempmcontent): newconf = "%s\t\t\t%s" % (c["name"], c["value"]) - apachempmcontent = re.sub(rep, newconf , apachempmcontent,count = 1) + apachempmcontent = re.sub(rep, newconf , apachempmcontent) public.writeFile(self.apachedefaultfile,apachedefaultcontent) public.writeFile(self.apachempmfile, apachempmcontent) isError = public.checkWebConfig() diff --git a/class/common.py b/class/common.py index a7a5943d..dfc8270d 100644 --- a/class/common.py +++ b/class/common.py @@ -18,12 +18,15 @@ import time class panelSetup: def init(self): - ua = request.headers.get('User-Agent','') - if ua: - ua = ua.lower() - if ua.find('spider') != -1 or ua.find('bot') != -1: + panel_path = public.get_panel_path() + if os.getcwd() != panel_path: os.chdir(panel_path) + + g.ua = request.headers.get('User-Agent','') + if g.ua: + ua = g.ua.lower() + if ua.find('spider') != -1 or g.ua.find('bot') != -1: return redirect('https://www.google.com') - g.version = '6.8.12' + g.version = '6.8.14' g.title = public.GetConfigValue('title') g.uri = request.path g.debug = os.path.exists('data/debug.pl') @@ -97,7 +100,7 @@ class panelAdmin(panelSetup): session['brand'] = public.GetConfigValue('brand') session['product'] = public.GetConfigValue('product') session['rootPath'] = '/www' - session['download_url'] = 'http://download.bt.cn' + session['download_url'] = 'https://node.aapanel.com' session['setupPath'] = session['rootPath'] + '/server' session['logsPath'] = '/www/wwwlogs' session['yaer'] = datetime.now().year @@ -147,50 +150,50 @@ class panelAdmin(panelSetup): g.api_request = True else: if session['login'] == False: + public.WriteLog('Login auth', 'The current session has been logged out') session.clear() return redirect('/login') if 'tmp_login_expire' in session: s_file = 'data/session/{}'.format(session['tmp_login_id']) if session['tmp_login_expire'] < time.time(): + public.WriteLog('Login auth', 'Temporary authorization has expired {}'.format(public.get_client_ip())) session.clear() if os.path.exists(s_file): os.remove(s_file) return redirect('/login') if not os.path.exists(s_file): + public.WriteLog('Login auth', 'Forced withdrawal due to cancellation of temporary authorization {}'.format(public.get_client_ip())) session.clear() return redirect('/login') + ua_md5 = public.md5(g.ua) + if ua_md5 != session.get('login_user_agent',ua_md5): + public.WriteLog('Login auth', 'UA verification failed {}'.format(public.get_client_ip())) + session.clear() + return redirect('/login') if api_check: - try: - sess_out_path = 'data/session_timeout.pl' - sess_input_path = 'data/session_last.pl' - if not os.path.exists(sess_out_path): public.writeFile(sess_out_path,'86400') - if not os.path.exists(sess_input_path): public.writeFile(sess_input_path,str(int(time.time()))) - session_timeout = int(public.readFile(sess_out_path)) - session_last = int(public.readFile(sess_input_path)) - if time.time() - session_last > session_timeout: - os.remove(sess_input_path) - session['login'] = False - cache.set('dologin', True) - session.clear() - return redirect('/login') - public.writeFile(sess_input_path, str(int(time.time()))) - except: - pass + session_timeout = session.get('session_timeout',0) + if session_timeout < time.time() and session_timeout != 0: + public.WriteLog('Login auth', 'The session has expired {}'.format(public.get_client_ip())) + session.clear() + return redirect('/login?dologin=True&go=0') + + + login_token = session.get('login_token','') + if login_token: + if login_token != public.get_login_token_auth(): + public.WriteLog('Login auth', 'Session ID does not match {}'.format(public.get_client_ip())) + session.clear() + return redirect('/login?dologin=True&go=1') - filename = '/www/server/panel/data/login_token.pl' - if os.path.exists(filename): - token = public.readFile(filename).strip() - if 'login_token' in session: - if session['login_token'] != token: - session.clear() - return redirect('/login?dologin=True&go=1') if api_check: filename = 'data/sess_files/' + public.get_sess_key() if not os.path.exists(filename): + public.WriteLog('Login auth', 'Trigger CSRF defense {}'.format(public.get_client_ip())) session.clear() return redirect('/login?dologin=True&go=2') except: + public.WriteLog('Login auth',public.get_error_info()) session.clear() return redirect('/login') diff --git a/class/config.py b/class/config.py index 08abe07e..723c617a 100644 --- a/class/config.py +++ b/class/config.py @@ -12,7 +12,7 @@ try: except: public.ExecShell("pip install pyotp &") try: - from BTPanel import session,admin_path_checks,g,request + from BTPanel import session,admin_path_checks,g,request,cache import send_mail except:pass class config: @@ -91,6 +91,18 @@ class config: if not 'port' in qq_mail_info:qq_mail_info['port']=465 return public.returnMsg(True, qq_mail_info) + #清空数据 + def set_empty(self,get): + type=get.type.strip() + if type=='dingding': + ret = [] + public.writeFile(self.__dingding_config, json.dumps(ret)) + return public.returnMsg(True, 'Empty successfully') + else: + ret = [] + public.writeFile(self.__mail_config, json.dumps(ret)) + return public.returnMsg(True, 'Empty successfully') + # 用户自定义邮件发送 def user_stmp_mail_send(self, get): @@ -127,12 +139,11 @@ class config: ret['user_mail'] = {"user_name": user_mail, "mail_list": self.__mail_list,"info":self.get_user_mail(get)} ret['dingding'] = {"dingding": dingding,"info":self.get_dingding(get)} return ret - # 设置钉钉报警 def set_dingding(self, get): if not (hasattr(get, 'url') or hasattr(get, 'atall')): return public.returnMsg(False, 'COMPLETE_INFO') - if get.atall: + if get.atall=='True' or get.atall=='1': get.atall = 'True' else: get.atall = 'False' self.mail.dingding_insert(get.url.strip(), get.atall) @@ -321,7 +332,9 @@ class config: public.SetConfigValue('title',get.webname) limitip = public.readFile('data/limitip.conf') - if get.limitip != limitip: public.writeFile('data/limitip.conf',get.limitip) + if get.limitip != limitip: + public.writeFile('data/limitip.conf',get.limitip) + cache.set('limit_ip',[]) public.writeFile('data/domain.conf',get.domain.strip()) public.writeFile('data/iplist.txt',get.address) @@ -364,8 +377,8 @@ class config: if not get.domain: get.domain = '' get.limitip = public.readFile('data/limitip.conf') if not get.limitip: get.limitip = '' - if not get.domain.strip() and not get.limitip.strip(): return public.returnMsg(False, - 'SECURITY_ENTRANCE_ADDRESS_TRUEN_OFF_WARN') + if not get.domain.strip() and not get.limitip.strip() and not os.path.exists('config/basic_auth.json'): + return public.returnMsg(False,'SECURITY_ENTRANCE_ADDRESS_TRUEN_OFF_WARN') admin_path_file = 'data/admin_path.pl' admin_path = '/' @@ -523,9 +536,21 @@ class config: rep = r"\s*pm\s*=\s*(\w+)\s*" tmp = re.search(rep, conf).groups() data['pm'] = tmp[0] + + rep = r"\s*listen.allowed_clients\s*=\s*([\w\.,/]+)\s*" + tmp = re.search(rep, conf).groups() + data['allowed'] = tmp[0] + + data['unix'] = 'unix' - if not isinstance(public.get_fpm_address(version),str): + data['port'] = '' + data['bind'] = '/tmp/php-cgi-{}.sock'.format(version) + + fpm_address = public.get_fpm_address(version,True) + if not isinstance(fpm_address,str): data['unix'] = 'tcp' + data['port'] = fpm_address[1] + data['bind'] = fpm_address[0] return data @@ -565,12 +590,24 @@ class config: if get.listen == 'unix': listen = '/tmp/php-cgi-{}.sock'.format(version) else: - listen = '127.0.0.1:10{}1'.format(version) + default_listen = '127.0.0.1:10{}1'.format(version) + if 'bind_port' in get: + if get.bind_port.find('sock') != -1: + listen = default_listen + else: + listen = get.bind_port + else: + listen = default_listen rep = r'\s*listen\s*=\s*.+\s*' conf = re.sub(rep, "\nlisten = "+listen+"\n", conf) + if 'allowed' in get: + if not get.allowed: get.allowed = '127.0.0.1' + rep = r"\s*listen.allowed_clients\s*=\s*([\w\.,/]+)\s*" + conf = re.sub(rep, "\nlisten.allowed_clients = "+get.allowed+"\n", conf) + public.writeFile(file,conf) public.phpReload(version) public.sync_php_address(version) @@ -696,6 +733,8 @@ class config: #设置面板SSL def SetPanelSSL(self,get): + ssl_path = "{}/ssl".format(public.get_panel_path()) + if not os.path.exists(ssl_path): os.makedirs(ssl_path,384) if hasattr(get,"email"): #rep_mail = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$" rep_mail = r"[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?" @@ -1681,7 +1720,7 @@ class config: def get_login_send(self,get): result={} import time - time.sleep(0.5) + time.sleep(0.01) if os.path.exists('/www/server/panel/data/login_send_mail.pl'): result['mail']=True else: diff --git a/class/data.py b/class/data.py index 42878915..eb3ec43f 100644 --- a/class/data.py +++ b/class/data.py @@ -38,7 +38,7 @@ class data: temp['local'] = True try: s = socket.socket() - s.settimeout(0.15) + s.settimeout(0.01) s.connect((localIP,port)) s.close() except: @@ -141,14 +141,16 @@ class data: conf = public.readFile( self.setupPath + '/panel/vhost/' + self.web_server + '/detail/' + siteName + '.conf') if self.web_server == 'nginx': - rep = r"enable-php-([0-9]{2,3})\.conf" + rep = r"enable-php-(\w{2,5})\.conf" elif self.web_server == 'apache': - rep = r"php-cgi-([0-9]{2,3})\.sock" + rep = r"php-cgi-(\w{2,5})\.sock" else: rep = r"path\s*/usr/local/lsws/lsphp(\d+)/bin/lsphp" tmp = re.search(rep,conf).groups() if tmp[0] == '00': return 'Static' + if tmp[0] == 'other': + return 'Other' return tmp[0][0] + '.' + tmp[0][1] except: @@ -199,6 +201,8 @@ class data: data['data'][i]['domain'] = SQL.table('domain').where("pid=?",(data['data'][i]['id'],)).count() data['data'][i]['ssl'] = self.get_site_ssl_info(data['data'][i]['name']) data['data'][i]['php_version'] = self.get_php_version(data['data'][i]['name']) + if not data['data'][i]['status'] in ['0','1',0,1]: + data['data'][i]['status'] = '1' elif table == 'firewall': for i in range(len(data['data'])): if data['data'][i]['port'].find(':') != -1 or data['data'][i]['port'].find('.') != -1 or data['data'][i]['port'].find('-') != -1: @@ -242,9 +246,7 @@ class data: where = "id=?" retuls = SQL.where(where,(id,)).getField(keyName) return retuls - - - + ''' * 获取数据与分页 * @param string table 表 @@ -334,7 +336,10 @@ class data: if not search: return "" if type(search) == bytes: search = search.encode('utf-8').strip() - search = re.search(r"[\w\x80-\xff\.]+",search).group() + try: + search = re.search(r"[\w\x80-\xff\.]+",search).group() + except: + return '' wheres = { 'sites' : "id='"+search+"' or name like '%"+search+"%' or status like '%"+search+"%' or ps like '%"+search+"%'", 'ftps' : "id='"+search+"' or name like '%"+search+"%' or ps like '%"+search+"%'", diff --git a/class/datatool.py b/class/datatool.py index 0c314560..50d8d40f 100644 --- a/class/datatool.py +++ b/class/datatool.py @@ -58,7 +58,7 @@ class datatools: ret2 = {} ret2['type']=table[0][1] data_size = table[0][6] - ret2['rows_count'] = table[0][4] + ret2['rows_count'] = self.DB_MySQL.query("select count(*) from `{}`.`{}`".format(db_name,i[0]))[0][0] #table[0][4] 实时获取行数 @authow hwliang<2021-08-05> 修改 ret2['collation'] = table[0][14] ret2['data_size'] = self.ToSize(int(data_size)) ret2['table_name'] = i[0] diff --git a/class/db.py b/class/db.py index 61721ef9..f47b6f9c 100644 --- a/class/db.py +++ b/class/db.py @@ -82,8 +82,9 @@ class Sql(): def limit(self,limit): #LIMIT条件 - if len(limit): - self.__OPT_LIMIT = " LIMIT "+limit + + if limit: + self.__OPT_LIMIT = " LIMIT {}".format(limit) return self diff --git a/class/files.py b/class/files.py index 3afd5624..8cf367a3 100644 --- a/class/files.py +++ b/class/files.py @@ -165,6 +165,23 @@ session.save_handler = files'''.format(path, sess_path, sess_path) if text2.find(rep) != -1: text2 = text2.replace(rep,reps[rep]) return text2 + # 名称输入系列化 + def xssdecode(self,text): + try: + cs = {""":'"',"'":"'"} + for c in cs.keys(): + text = text.replace(c,cs[c]) + + str_convert = text + if sys.version_info[0] == 3: + import html + text2 = html.unescape(str_convert) + else: + text2 = cgi.unescape(str_convert) + return text2 + except: + return text + # 上传文件 def UploadFile(self, get): from werkzeug.utils import secure_filename @@ -302,6 +319,13 @@ session.save_handler = files'''.format(path, sess_path, sess_path) return str(result) return '0' + + def __filename_flater(self,filename): + ms = {";":""} + for m in ms.keys(): + filename = filename.replace(m,ms[m]) + return filename + # 取文件/目录列表 def GetDir(self, get): if not hasattr(get, 'path'): @@ -311,6 +335,7 @@ session.save_handler = files'''.format(path, sess_path, sess_path) get.path = get.path.encode('utf-8') if get.path == '': get.path = '/www' + get.path = self.xssdecode(get.path) if not os.path.exists(get.path): get.path = '/www/wwwroot' #return public.ReturnMsg(False, '指定目录不存在!') @@ -406,11 +431,11 @@ session.save_handler = files'''.format(path, sess_path, sess_path) # 判断文件是否已经被收藏 favorite = self.__check_favorite(filePath,data['STORE']) if os.path.isdir(filePath): - dirnames.append(filename+';'+size+';' + mtime+';'+accept+';'+user+';'+link + ';' + + dirnames.append(self.__filename_flater(filename)+';'+size+';' + mtime+';'+accept+';'+user+';'+link + ';' + self.get_download_id(filePath)+';'+ self.is_composer_json(filePath)+';' +favorite+';'+self.__check_share(filePath)) else: - filenames.append(filename+';'+size+';'+mtime+';'+accept+';'+user+';'+link+';' + filenames.append(self.__filename_flater(filename)+';'+size+';'+mtime+';'+accept+';'+user+';'+link+';' +self.get_download_id(filePath)+';' + self.is_composer_json(filePath)+';' +favorite+';'+self.__check_share(filePath)) n += 1 @@ -437,7 +462,7 @@ session.save_handler = files'''.format(path, sess_path, sess_path) file_info = self.__format_stat(filename, get.path) if not file_info: continue favorite = self.__check_favorite(filename, data['STORE']) - r_file = file_info['name'] + ';' + str(file_info['size']) + ';' + str(file_info['mtime']) + ';' + str( + r_file = self.__filename_flater(file_info['name']) + ';' + str(file_info['size']) + ';' + str(file_info['mtime']) + ';' + str( file_info['accept']) + ';' + file_info['user'] + ';' + file_info['link']+';'\ + self.get_download_id(filename) + ';' + self.is_composer_json(filename)+';'\ + favorite+';'+self.__check_share(filename) @@ -477,6 +502,30 @@ session.save_handler = files'''.format(path, sess_path, sess_path) f_key2 = '/'.join((ps_path,public.md5(os.path.basename(filename)))) if os.path.exists(f_key2): return public.readFile(f_key2) + + pss = { + '/www/server/data':'MySQL data storage directory!', + '/www/server/mysql':'MySQL program directory', + '/www/server/redis':'Redis program directory', + '/www/server/mongodb':'MongoDB program directory', + '/www/server/nvm':'PM2/NVM/NPM program directory', + '/www/server/pass':'Website Basic Auth authentication password storage directory', + '/www/server/speed':'Website speed plugin directory', + '/www/server/docker':'Docker and data directory', + '/www/server/total':'Website Statistics Directory', + '/www/server/btwaf':'WAF directory', + '/www/server/pure-ftpd':'ftp program directory', + '/www/server/phpmyadmin':'phpMyAdmin program directory', + '/www/server/rar':'rar extension library directory, after deleting, it will lose support for RAR compressed files', + '/www/server/stop':'Website disabled page directory, please do not delete!', + '/www/server/nginx':'Nginx program directory', + '/www/server/apache':'Apache program directory', + '/www/server/cron':'Cron script and log directory', + '/www/server/php':'All interpreters of PHP versions are in this directory', + '/www/server/tomcat':'Tomcat program directory', + '/www/php_session':'PHP-SESSION Quarantine directory' + } + if filename in pss: return pss[filename] return '' @@ -512,6 +561,13 @@ session.save_handler = files'''.format(path, sess_path, sess_path) + def check_file_sort(self,sort): + """ + @校验排序字段 + """ + slist = ['name','size','mtime','accept','user'] + if sort in slist: return sort + return 'name' def __list_dir(self, path, my_sort='name', reverse=False): ''' @@ -554,8 +610,9 @@ session.save_handler = files'''.format(path, sess_path, sess_path) continue #使用list[tuple]排序效率更高 tmp_files.append((f_name,sort_val)) - - tmp_files = sorted(tmp_files, key=lambda x: x[sort_key], reverse=reverse) + try: + tmp_files = sorted(tmp_files, key=lambda x: x[sort_key], reverse=reverse) + except:pass return tmp_files def __format_stat(self, filename, path): @@ -1082,6 +1139,8 @@ session.save_handler = files'''.format(path, sess_path, sess_path) def GetFileBody(self, get): if sys.version_info[0] == 2: get.path = get.path.encode('utf-8') + + get.path = self.xssdecode(get.path) if not os.path.exists(get.path): if get.path.find('rewrite') == -1: return public.returnMsg(False,'FILE_NOT_EXISTS',(get.path,)) @@ -1308,6 +1367,11 @@ session.save_handler = files'''.format(path, sess_path, sess_path) def Zip(self, get): if not 'z_type' in get: get.z_type = 'rar' + + if get.z_type == 'rar': + if os.uname().machine == 'aarch64': + return public.returnMsg(False,'RAR component does not support aarch 64 platform') + import panelTask task_obj = panelTask.bt_task() task_obj.create_task(public.GetMsg("COMPRESSION_FILE"),3,get.path,json.dumps({"sfile":get.sfile,"dfile":get.dfile,"z_type":get.z_type})) @@ -1387,6 +1451,8 @@ session.save_handler = files'''.format(path, sess_path, sess_path) def CloseLogs(self, get): get.path = public.GetConfigValue('root_path') public.ExecShell('rm -f '+public.GetConfigValue('logs_path')+'/*') + public.ExecShell('rm -rf '+public.GetConfigValue('logs_path')+'/history_backups/*') + public.ExecShell('rm -f '+public.GetConfigValue('logs_path')+'/pm2/*.log') if public.get_webserver() == 'nginx': public.ExecShell( 'kill -USR1 `cat '+public.GetConfigValue('setup_path')+'/nginx/logs/nginx.pid`') @@ -1479,6 +1545,19 @@ session.save_handler = files'''.format(path, sess_path, sess_path) myfiles = json.loads(session['selected']['data']) l = len(myfiles) if get.type == '1': + + for key in myfiles: + if sys.version_info[0] == 2: + sfile = session['selected']['path'] + \ + '/' + key.encode('utf-8') + dfile = get.path + '/' + key.encode('utf-8') + else: + sfile = session['selected']['path'] + '/' + key + dfile = get.path + '/' + key + + if dfile.find(sfile) == 0: + return public.returnMsg(False,'Wrong copy logic, from {} copy to {} has an inclusive relationship, there is an infinite loop copy risk!'.format(sfile,dfile)) + for key in myfiles: i += 1 public.writeSpeed(key, i, l) @@ -2014,7 +2093,7 @@ cd %s if len(pdata['password']) < 4 and len(pdata['password']) > 0: return public.returnMsg(False,'The length of the extracted password cannot be less than 4 digits') if not re.match('^\w+$',pdata['password']): - return public.returnMsg(False,'No special symbols can be used in the extracted password') + return public.returnMsg(False,'The password only supports a combination of uppercase and lowercase letters and numbers') if 'ps' in get: pdata['ps'] = get.ps public.M(my_table).where('id=?', (id,)).update(pdata) @@ -2037,8 +2116,8 @@ cd %s } if len(pdata['password']) < 4 and len(pdata['password']) > 0: return public.returnMsg(False,'PASSWD_ERR') - if not re.match('^\w+$',pdata['password']): - return public.returnMsg(False,'No special symbols can be used in the extracted password') + if not re.match('^\w+$',pdata['password']) and pdata['password']: + return public.returnMsg(False,'The password only supports a combination of uppercase and lowercase letters and numbers') #更新 or 插入 token = public.M(my_table).where('filename=?',(get.filename,)).getField('token') if token: @@ -2123,8 +2202,10 @@ cd %s php_bin = self.__get_php_bin(php_version) if not php_bin: return public.returnMsg(False,'PHP_VER_NOT_FOUND') - if not os.path.exists(get.path + '/composer.json'): - return public.returnMsg(False,'COMPOSER_CONF_NOT_FOUND') + get.composer_cmd = get.composer_cmd.strip() + if get.composer_cmd == '': + if not os.path.exists(get.path + '/composer.json'): + return public.returnMsg(False,'COMPOSER_CONF_NOT_FOUND') log_file = '/tmp/composer.log' user = '' if 'user' in get: @@ -2143,7 +2224,15 @@ cd %s else: public.ExecShell('export COMPOSER_HOME=/tmp && {}{} {} config -g --unset repos.packagist'.format(user,php_bin,composer_bin)) #执行composer命令 - composer_exec_str = '{} {} {} -vvv'.format(php_bin,composer_bin,get.composer_args) + if not get.composer_cmd: + composer_exec_str = '{} {} {} -vvv'.format(php_bin,composer_bin,get.composer_args) + else: + if get.composer_cmd.find('composer ') == 0 or get.composer_cmd.find('/usr/bin/composer ') == 0: + composer_cmd = get.composer_cmd.replace('composer ','').replace('/usr/bin/composer ','') + composer_exec_str = '{} {} {} -vvv'.format(php_bin,composer_bin,composer_cmd) + else: + composer_exec_str = '{} {} {} {} -vvv'.format(php_bin,composer_bin,get.composer_args,get.composer_cmd) + if os.path.exists(log_file): os.remove(log_file) public.ExecShell("cd {} && export COMPOSER_HOME=/tmp && {} nohup {} &> {} && echo 'BT-Exec-Completed' >> {} && rm -rf /home/www &".format(get.path,user,composer_exec_str,log_file,log_file)) public.WriteLog('Composer',"EXEC_COMPOSER",(get.path,get.composer_args)) @@ -2258,6 +2347,27 @@ cd %s except: return uid + # 取lsattr + def get_lsattr(self,filename): + if os.path.isfile(filename): + return public.ExecShell('lsattr {}'.format(filename))[0].split(' ')[0] + else: + s_name = os.path.basename(filename) + s_path = os.path.dirname(filename) + + try: + res = public.ExecShell('lsattr {}'.format(s_path))[0].strip() + for s in res.split('\n'): + if not s: continue + lsattr_info = s.split() + if not lsattr_info: continue + if filename == lsattr_info[1]: + return lsattr_info[0] + except: + raise public.PanelError(lsattr_info) + + return '--------------e----' + # 取指定文件属性 def get_file_attribute(self,args): @@ -2283,6 +2393,7 @@ cd %s attribute['mode'] = str(oct(f_stat.st_mode)[-3:]) # 文件权限号 attribute['md5'] = 'Do not count files or directories larger than 100MB' # 文件MD5 attribute['sha1'] = 'Do not count files or directories larger than 100MB' # 文件sha1 + attribute['lsattr'] = self.get_lsattr(filename) attribute['is_dir'] = os.path.isdir(filename) # 是否为目录 attribute['is_link'] = os.path.islink(filename) # 是否为链接文件 if attribute['is_link']: diff --git a/class/firewalls.py b/class/firewalls.py index 856ef946..e2d85a97 100644 --- a/class/firewalls.py +++ b/class/firewalls.py @@ -284,34 +284,33 @@ class firewalls: #取SSH信息 def GetSshInfo(self,get): - file = '/etc/ssh/sshd_config' - conf = public.readFile(file) - if not conf: conf = '' - rep = r"#*Port\s+([0-9]+)\s*\n" - tmp1 = re.search(rep,conf) - port = '22' - if tmp1: - port = tmp1.groups(0)[0] - import system - panelsys = system.system() - - version = panelsys.GetSystemVersion() - if os.path.exists('/usr/bin/apt-get'): - if os.path.exists('/etc/init.d/sshd'): - status = public.ExecShell("service sshd status | grep -P '(dead|stop)'|grep -v grep") - else: - status = public.ExecShell("service ssh status | grep -P '(dead|stop)'|grep -v grep") + port = public.get_ssh_port() + + pid_file = '/run/sshd.pid' + if os.path.exists(pid_file): + pid = int(public.readFile(pid_file)) + status = public.pid_exists(pid) else: - if version.find(' 7.') != -1 or version.find(' 8.') != -1 or version.find('Fedora') != -1: - status = public.ExecShell("systemctl status sshd.service | grep 'dead'|grep -v grep") + import system + panelsys = system.system() + + version = panelsys.GetSystemVersion() + if os.path.exists('/usr/bin/apt-get'): + if os.path.exists('/etc/init.d/sshd'): + status = public.ExecShell("service sshd status | grep -P '(dead|stop)'|grep -v grep") + else: + status = public.ExecShell("service ssh status | grep -P '(dead|stop)'|grep -v grep") else: - status = public.ExecShell("/etc/init.d/sshd status | grep -e 'stopped' -e '已停'|grep -v grep") + if version.find(' 7.') != -1 or version.find(' 8.') != -1 or version.find('Fedora') != -1: + status = public.ExecShell("systemctl status sshd.service | grep 'dead'|grep -v grep") + else: + status = public.ExecShell("/etc/init.d/sshd status | grep -e 'stopped' -e '已停'|grep -v grep") -# return status; - if len(status[0]) > 3: - status = False - else: - status = True + # return status; + if len(status[0]) > 3: + status = False + else: + status = True isPing = True try: file = '/etc/sysctl.conf' diff --git a/class/ols.py b/class/ols.py index f3a2132e..b1184d9f 100644 --- a/class/ols.py +++ b/class/ols.py @@ -240,7 +240,7 @@ RewriteRule (.*\.php)?$ - [E=Cache-Control:private] def _get_siteconf_info(self): siteinfo = self._get_need_create_site() - phpv_reg = r'enable-php-(\d+)\.conf' + phpv_reg = r'enable-php-(\w+)\.conf' rundir_reg = r'root\s+(.*);' for s in siteinfo: path = '/www/server/panel/vhost/nginx/{}.conf'.format(s['sitename']) diff --git a/class/panelAuth.py b/class/panelAuth.py index 00b539d0..1461a5b7 100644 --- a/class/panelAuth.py +++ b/class/panelAuth.py @@ -71,8 +71,10 @@ class panelAuth: else: params['product_id'] = get.product_id data = self.send_cloud('{}/api/product/prices'.format(self.__official_url), params) - if len(data['res']) > 3: - return data['res'][-3:] + if not data['success']: + return public.returnMsg(False,data['msg']) + # if len(data['res']) == 6: + # return data['res'][3:] return data['res'] except: del(session['get_product_list']) @@ -108,6 +110,8 @@ class panelAuth: params['environment_info'] = json.dumps(env_info) params['server_id'] = env_info['install_code'] data = self.send_cloud('{}/api/order/product/create'.format(self.__official_url), params) + if not data['success']: + return public.returnMsg(False,data['res']) return data['res'] def get_stripe_session_id(self,get): @@ -285,6 +289,8 @@ class panelAuth: params['page'] = get.page if 'page' in get else 1 params['pageSize'] = get.pageSize if 'pageSize' in get else 15 data = self.send_cloud('{}/api/user/productAuthorizes'.format(self.__official_url), params) + if not data: + return [] if not data['success']: return [] data = data['res'] return [i for i in data['list'] if i['status'] != 'activated'] diff --git a/class/panelBackup.py b/class/panelBackup.py index 99f8d118..78400b61 100644 --- a/class/panelBackup.py +++ b/class/panelBackup.py @@ -75,6 +75,15 @@ class backup: self._error_msg += "\n" self._error_msg += msg + #取排除列表用于计算排除目录大小 + def get_exclude_list(self, exclude=[]): + if not exclude: + tmp_exclude = os.getenv('BT_EXCLUDE') + if tmp_exclude: + exclude = tmp_exclude.split(',') + if not exclude: return [] + return exclude + #构造排除 def get_exclude(self,exclude = []): if not exclude: @@ -274,10 +283,11 @@ class backup: dpath = os.path.dirname(dfile) if not os.path.exists(dpath): os.makedirs(dpath,384) - - p_size = public.get_path_size(spath) + self.get_exclude(exclude) exclude_config = self._exclude + exclude_list = self.get_exclude_list(exclude) + p_size = public.get_path_size(spath, exclude=exclude_list) if not self._exclude: exclude_config = "Not set" @@ -349,6 +359,7 @@ class backup: error_msg = self._error_msg self.send_failture_notification(error_msg) return False + if self._cloud: self.echo_info(public.getMsg("BACKUP_UPLOADING",(self._cloud._title,))) if self._cloud.upload_file(dfile,'site'): @@ -709,7 +720,7 @@ class backup: return if notice == 1 or notice == 2: - title = self.generate_failture_title() + title = self.generate_failture_title(cron_title) task_name = cron_title msg = self.generate_failture_notice(task_name, error_msg, remark) res = self.send_notification(notice_channel, title, msg) @@ -733,7 +744,7 @@ class backup: return if notice == 1 or notice == 2: - title = self.generate_failture_title() + title = self.generate_failture_title(cron_title) type_desc = { "site": "site", "database": "database" diff --git a/class/panelMessage.py b/class/panelMessage.py index 7ae3aac1..4fb7f4d4 100644 --- a/class/panelMessage.py +++ b/class/panelMessage.py @@ -22,9 +22,9 @@ class panelMessage: os = 'linux' def __init__(self): - # if not public.M('sqlite_master').where('type=? AND name=? AND sql LIKE ?', ('table', 'messages','%retry_num%')).count(): - # public.M('messages').execute("alter TABLE messages add send integer DEFAULT 0",()) - # public.M('messages').execute("alter TABLE messages add retry_num integer DEFAULT 0",()) + if not public.M('sqlite_master').where('type=? AND name=? AND sql LIKE ?', ('table', 'messages','%retry_num%')).count(): + public.M('messages').execute("alter TABLE messages add send integer DEFAULT 0",()) + public.M('messages').execute("alter TABLE messages add retry_num integer DEFAULT 0",()) pass diff --git a/class/panelPlugin.py b/class/panelPlugin.py index e3fc9d02..d8c7a95f 100644 --- a/class/panelPlugin.py +++ b/class/panelPlugin.py @@ -7,7 +7,7 @@ # Author: hwliang #------------------------------------------------------------------- import public,os,sys,json,time,psutil,py_compile,re -from BTPanel import session,cache +from BTPanel import session,cache,send_file if sys.version_info[0] == 3: from importlib import reload class mget: pass class panelPlugin: @@ -20,12 +20,13 @@ class panelPlugin: __link = 'config/link.json' __product_list = None __plugin_list = None + __exists_names = {} __official_url = 'https://brandnew.aapanel.com' pids = None ROWS = 15 def __init__(self): - self.__install_path = 'plugin' + self.__install_path = '/www/server/panel/plugin' #检查依赖 def check_deps(self,get): @@ -65,6 +66,7 @@ class panelPlugin: #检查互斥 def check_mutex(self,mutex): + if mutex == -1: return True mutexs = mutex.split(',') for name in mutexs: pluginInfo = self.get_soft_find(name) @@ -255,9 +257,13 @@ class panelPlugin: get.type = '4' if ols_execstr: ols_execstr = ols_execstr.format(get.type,mtype) - execstr = "cd /www/server/panel/install && /bin/bash install_soft.sh {} {} {} {} {}".format(get.type,mtype,get.sName,get.version,ols_execstr) + execstr = "cd /www/server/panel/install && /bin/bash install_soft.sh {} {} {} {} {}".format( + get.type, mtype, get.sName, get.version, ols_execstr) if get.sName == "phpmyadmin": execstr += "&> /tmp/panelExec.log && sleep 1 && /usr/local/lsws/bin/lswsctrl restart" + # 清理日志文件 + if os.path.exists("/tmp/panelExec.log"): + public.writeFile("/tmp/panelExec.log","") public.M('tasks').add('id,name,type,status,addtime,execstr',(None, mmsg + '['+get.sName+'-'+get.version+']','execshell','0',time.strftime('%Y-%m-%d %H:%M:%S'),execstr)) cache.delete('install_task') public.writeFile('/tmp/panelTask.pl','True') @@ -271,7 +277,7 @@ class panelPlugin: if pluginInfo['type'] != 5: pluginPath = self.__install_path + '/' + pluginInfo['name'] if pluginInfo['type'] != 6: - download_url = session['download_url'] + '/install/plugin/' + pluginInfo['name'] + '/install.sh' + download_url = session['download_url'] + '/install/plugin/' + pluginInfo['name'] + '_en/install.sh' toFile = '/tmp/%s.sh' % pluginInfo['name'] public.downloadFile(download_url,toFile) self.set_pyenv(toFile) @@ -372,6 +378,8 @@ class panelPlugin: for softInfo in softList['list']: if 'uninsatll_checks' not in softInfo: softInfo['uninsatll_checks'] = softInfo['uninstall_checks'] + if not softList['list']: + if os.path.exists(lcoalTmp): os.remove(lcoalTmp) return softList #取提醒标记 @@ -864,10 +872,8 @@ class panelPlugin: if not softInfo['fpm']: softInfo['status'] = True elif softInfo['status'] and os.path.exists(pid_file): - if not self.pids: self.pids = psutil.pids() try: - if not int(public.readFile(pid_file)) in self.pids: - softInfo['status'] = False + softInfo['status'] = public.pid_exists(int(public.readFile(pid_file))) except: if os.path.exists(pid_file): os.remove(pid_file) @@ -877,10 +883,10 @@ class panelPlugin: if not softInfo['status']: softInfo['status'] = self.process_exists('mariadbd') if softInfo['name'] == 'phpmyadmin': softInfo['status'] = self.get_phpmyadmin_stat() if softInfo['name'] == 'openlitespeed': - if public.ExecShell('ps aux|grep openlitespeed|grep -v "grep"')[0]: - softInfo['status'] = True - else: - softInfo['status'] = False + pid_file = '/run/openlitespeed.pid' + if os.path.exists(pid_file): + pid = int(public.readFile(pid_file)) + softInfo['status'] = public.pid_exists(pid) return softInfo def get_php_status(self,phpversion): @@ -1033,7 +1039,22 @@ class panelPlugin: #进程是否存在 def process_exists(self,pname,exe = None): - if not self.pids: self.pids = psutil.pids() #self.get_pids() # + if pname in ['mysqld','mariadbd']: + datadir = public.get_datadir() + if datadir: + pid_file = "{}/{}.pid".format(datadir,public.get_hostname()) + if os.path.exists(pid_file): + pid = int(public.readFile(pid_file)) + status = public.pid_exists(pid) + if status: return status + + if pname in ['php-fpm'] and exe: + pid_file = exe.replace('sbin/php-fpm','/var/run/php-fpm.pid') + if os.path.exists(pid_file): + pid = int(public.readFile(pid_file)) + return public.pid_exists(pid) + + if not self.pids: self.pids = psutil.pids() for pid in self.pids: try: l = '/proc/%s/exe' % pid @@ -1312,18 +1333,20 @@ class panelPlugin: if not pluginInfo: import json pluginInfo = json.loads(public.readFile(self.__install_path + '/' + get.name + '/info.json')) - if pluginInfo['tip'] == 'lib': if not os.path.exists(self.__install_path+ '/' + pluginInfo['name']): public.ExecShell('mkdir -p ' + self.__install_path + '/' + pluginInfo['name']) download_url = session['download_url'] + '/install/plugin/' + pluginInfo['name'] + '/install.sh' toFile = self.__install_path + '/' + pluginInfo['name'] + '/uninstall.sh' - public.downloadFile(download_url,toFile) - self.set_pyenv(toFile) - public.ExecShell('/bin/bash ' + toFile + ' uninstall') - public.ExecShell('rm -rf ' + session['download_url'] + '/install/plugin/' + pluginInfo['name']) + install_sh = self.__install_path + '/' + pluginInfo['name'] + '/install.sh' + if not os.path.exists(toFile) and not os.path.exists(install_sh): + public.downloadFile(download_url,toFile) + self.set_pyenv(toFile) + pluginPath = self.__install_path + '/' + pluginInfo['name'] - - if os.path.exists(pluginPath + '/install.sh'): + + if os.path.exists(toFile): + public.ExecShell('/bin/bash {} uninstall'.format(toFile)) + elif os.path.exists(pluginPath + '/install.sh'): public.ExecShell('/bin/bash ' + pluginPath + '/install.sh uninstall') if os.path.exists(pluginPath): @@ -1773,8 +1796,92 @@ class panelPlugin: def getConfigHtml(self,get): filename = self.__install_path + '/' + get.name + '/index.html' if not os.path.exists(filename): return public.returnMsg(False,'PLUGIN_GET_HTML') - srcBody = public.readFile(filename,'r') - return srcBody + mimetype = 'text/html' + cache_time = 0 if public.is_debug() else 86400 + self.plugin_open_total(get.name) + return send_file(filename, + mimetype = mimetype, + as_attachment = True, + add_etags = True, + conditional = True, + cache_timeout = cache_time) + + + def creatab_open_total_table(self,sql): + ''' + @name 创建插件打开统计表 + @author hwliang<2021-06-26> + @param sql 数据库对像 + @return void + ''' + if not sql.table('sqlite_master').where('type=? AND name=?', ('table', 'open_total')).count(): + csql = '''CREATE TABLE IF NOT EXISTS `open_total` ( +`id` INTEGER PRIMARY KEY AUTOINCREMENT, +`plugin_name` REAL, +`num` INTEGER +)''' + sql.execute(csql,()) + + + def plugin_open_total(self,plugin_name): + ''' + @name 插件打开统计 + @author hwliang<2021-06-26> + @param plugin_name 插件名称 + @return void + ''' + import db + sql = db.Sql().dbfile('plugin_total') + self.creatab_open_total_table(sql) + pdata = { + "plugin_name":plugin_name, + "num":1 + } + + num = sql.table('open_total').where('plugin_name=?',plugin_name).getField('num') + if not num: + sql.table('open_total').insert(pdata) + else: + sql.table('open_total').where('plugin_name=?',plugin_name).setField('num',num+1) + + def get_usually_plugin(self,get): + ''' + @name 获取常用插件 + @author hwliang<2021-06-26> + @param get + @return list + ''' + import db + sql = db.Sql().dbfile('plugin_total') + self.creatab_open_total_table(sql) + plugin_list = sql.table('open_total').order('num desc').limit(10).select() + usually_list = [] + for p in plugin_list: + plugin_info = self.get_soft_find(p['plugin_name']) + if plugin_info: + if plugin_info['setup']: + usually_list.append(plugin_info) + if len(usually_list) >= 5: break + return usually_list + + + def get_plugin_upgrades(self,get): + ''' + @name 获取指定插件的近期更新历史 + @author hwliang<2021-06-30> + @param get{ + plugin_name: string 插件名称 + } + @return list + ''' + plugin_name = get.plugin_name + if getattr(get,'show',0): + plugin_info = self.__get_plugin_find(plugin_name) + if plugin_info and 'versions' in plugin_info: + return plugin_info['versions'] + return [] + else: + return self.__get_plugin_upgrades(plugin_name) #取插件信息 def getPluginInfo(self,get): @@ -1840,7 +1947,7 @@ class panelPlugin: def getCloudPlugin(self,get): if session.get('getCloudPlugin') and get != None: return public.returnMsg(True,'PLUGIN_UPDATE_ERR1',("-1",)) import json - if not session.get('download_url'): session['download_url'] = 'http://download.bt.cn' + if not session.get('download_url'): session['download_url'] = 'https://node.aapanel.com' #获取列表 try: diff --git a/class/panelSSL.py b/class/panelSSL.py index 5b9228b9..ac154c26 100644 --- a/class/panelSSL.py +++ b/class/panelSSL.py @@ -29,8 +29,6 @@ class panelSSL: _check_url = None #构造方法 def __init__(self): - # pdata = {} - # data = {} if os.path.exists(self.__UPATH): my_tmp = public.readFile(self.__UPATH) if my_tmp: @@ -40,20 +38,6 @@ class panelSSL: self.__userInfo = {} else: self.__userInfo = {} - - # try: - # if self.__userInfo: - # pdata['access_key'] = self.__userInfo['access_key'] - # data['secret_key'] = self.__userInfo['secret_key'] - # except: - # self.__userInfo = {} - # pdata['access_key'] = 'test' - # data['secret_key'] = '123456' - # else: - # pdata['access_key'] = 'test' - # data['secret_key'] = '123456' - # pdata['data'] = data - # self.__PDATA = pdata def en_code_rsa(self, data): pk = public.readFile(self.__PUBKEY) @@ -503,7 +487,7 @@ class panelSSL: #检查域名是否解析 def CheckDomain(self,get): try: - epass = public.GetRandomString(32) + #创建目录 spath = get.path + '/.well-known/pki-validation' if not os.path.exists(spath): public.ExecShell("mkdir -p '" + spath + "'") @@ -520,9 +504,10 @@ class panelSSL: result = http_requests.get(self._check_url,s_type='curl',timeout=6,headers={"host":get.domain}).text self.__test = result if result == epass: return True - + self._check_url = self._check_url.replace('127.0.0.1', get.domain) return False except: + self._check_url = self._check_url.replace('127.0.0.1', get.domain) return False #确认域名 @@ -663,17 +648,7 @@ class panelSSL: if not tmp: continue tmp1 = json.loads(tmp) data.append(tmp1) - if not data: - lets_file = '/www/server/panel/config/letsencrypt.json' - tmp = public.readFile(ltes_file) - if not tmp: - return [] - tmp = json(tmp) - for i in tmp['orders']: - data.append({"domains":tmp['orders'][i]['domains'], - "notAfter":tmp['orders'][i]['cert_timeout'], - "save_path":tmp['orders'][i]['save_path'] - }) + return data except: return [] diff --git a/class/panelSite.py b/class/panelSite.py index 398e1677..04b2f305 100644 --- a/class/panelSite.py +++ b/class/panelSite.py @@ -487,6 +487,10 @@ include /www/server/panel/vhost/openlitespeed/proxy/BTSITENAME/*.conf import json, files get.path = self.__get_site_format_path(get.path) + + if not public.check_site_path(get.path): + a,c = public.get_sys_path() + return public.returnMsg(False,'Please do not set the website root directory to the system main directory:
                      {}'.format("
                      ".join(a+c))) try: siteMenu = json.loads(get.webname) except: @@ -520,10 +524,9 @@ include /www/server/panel/vhost/openlitespeed/proxy/BTSITENAME/*.conf domain = None # if siteMenu['count']: # domain = get.domain.replace(' ','') - # 表单验证 - if not files.files().CheckDir(self.sitePath) or not self.__check_site_path( - self.sitePath): return public.returnMsg(False, 'PATH_ERROR') - if len(self.phpVersion) < 2: return public.returnMsg(False, 'SITE_ADD_ERR_PHPEMPTY') + #表单验证 + if not self.__check_site_path(self.sitePath): return public.returnMsg(False,'PATH_ERROR') + if len(self.phpVersion) < 2: return public.returnMsg(False,'SITE_ADD_ERR_PHPEMPTY') reg = r"^([\w\-\*]{1,100}\.){1,4}([\w\-]{1,24}|[\w\-]{1,24}\.[\w\-]{1,24})$" if not re.match(reg, self.siteName): return public.returnMsg(False, 'SITE_ADD_ERR_DOMAIN') if self.siteName.find('*') != -1: return public.returnMsg(False, 'SITE_ADD_ERR_DOMAIN_TOW') @@ -600,13 +603,12 @@ set $bt_safe_open "{}/:/tmp/";'''.format(self.sitePath) get.ps = self.siteName firewalls.firewalls().AddAcceptPort(get) - if not hasattr(get, 'type_id'): get.type_id = 0 + if not hasattr(get,'type_id'): get.type_id = 0 + public.check_domain_cloud(self.siteName) + #写入数据库 + get.pid = sql.table('sites').add('name,path,status,ps,type_id,addtime',(self.siteName,self.sitePath,'1',ps,get.type_id,public.getDate())) - # 写入数据库 - get.pid = sql.table('sites').add('name,path,status,ps,type_id,addtime', - (self.siteName, self.sitePath, '1', ps, get.type_id, public.getDate())) - - # 添加更多域名 + #添加更多域名 for domain in siteMenu['domainlist']: get.domain = domain get.webname = self.siteName @@ -1045,6 +1047,7 @@ set $bt_safe_open "{}/:/tmp/";'''.format(self.sitePath) firewalls.firewalls().AddAcceptPort(get) if not multiple: public.serviceReload() + public.check_domain_cloud(get.domain) public.WriteLog('TYPE_SITE', 'DOMAIN_ADD_SUCCESS', (get.webname, get.domain)) sql.table('domain').add('pid,name,port,addtime', (get.id, get.domain, get.port, public.getDate())) @@ -1642,11 +1645,20 @@ listener Default%s{ # 获取TLS1.3标记 def get_tls13(self): nginx_bin = '/www/server/nginx/sbin/nginx' - nginx_v = public.ExecShell(nginx_bin + ' -V 2>&1|grep version:')[0] - nginx_v = re.search('nginx/1\.1(5|6|7|8|9).\d', nginx_v) - openssl_v = public.ExecShell(nginx_bin + ' -V 2>&1|grep OpenSSL')[0].find('OpenSSL 1.1.') != -1 - if nginx_v and openssl_v: - return ' TLSv1.3' + nginx_v = public.ExecShell(nginx_bin + ' -V 2>&1')[0] + nginx_v_re = re.findall("nginx/(\d\.\d+).+OpenSSL\s+(\d\.\d+)",nginx_v,re.DOTALL) + if nginx_v_re: + if nginx_v_re[0][0] in ['1.8','1.9','1.7','1.6','1.5','1.4']: + return '' + if float(nginx_v_re[0][0]) >= 1.15 and float(nginx_v_re[0][-1]) >= 1.1: + return ' TLSv1.3' + else: + _v = re.search('nginx/1\.1(5|6|7|8|9).\d',nginx_v) + if not _v: + _v = re.search('nginx/1\.2\d\.\d',nginx_v) + openssl_v = public.ExecShell(nginx_bin + ' -V 2>&1|grep OpenSSL')[0].find('OpenSSL 1.1.') != -1 + if _v and openssl_v: + return ' TLSv1.3' return '' # 获取apache反向代理 @@ -2567,8 +2579,8 @@ listener SSL443 { if conf: listen_ipv6 = '' if self.is_ipv6: listen_ipv6 = "\n listen [::]:%s;" % port - rep = "enable-php-([0-9]{2,3})\.conf" - tmp = re.search(rep, conf).groups() + rep = "enable-php-(\w{2,5})\.conf" + tmp = re.search(rep,conf).groups() version = tmp[0] bindingConf = ''' #BINDING-%s-START @@ -2889,9 +2901,10 @@ server Path = self.GetPath(get.path) if Path == "" or id == '0': return public.returnMsg(False, "DIR_EMPTY") - import files - if not files.files().CheckDir(Path) or not self.__check_site_path(Path): return public.returnMsg(False, - "PATH_ERROR") + if not self.__check_site_path(Path): return public.returnMsg(False,"PATH_ERROR") + if not public.check_site_path(Path): + a, c = public.get_sys_path() + return public.returnMsg(False,'Please do not set the website root directory to the system main directory:
                      {}'.format("
                      ".join(a+c))) SiteFind = public.M("sites").where("id=?", (id,)).field('path,name').find() if SiteFind["path"] == Path: return public.returnMsg(False, "SITE_PATH_ERR_RE") @@ -2929,33 +2942,41 @@ server public.set_site_open_basedir_nginx(Name) public.serviceReload() - public.M("sites").where("id=?", (id,)).setField('path', Path) - public.WriteLog('TYPE_SITE', 'SITE_PATH_SUCCESS', (Name,)) - return public.returnMsg(True, "SET_SUCCESS") + public.M("sites").where("id=?",(id,)).setField('path',Path) + public.WriteLog('TYPE_SITE', 'SITE_PATH_SUCCESS',(Name,)) + return public.returnMsg(True, "SET_SUCCESS") - # 取当前可用PHP版本 - def GetPHPVersion(self, get): - phpVersions = ('00', '52', '53', '54', '55', '56', '70', '71', '72', '73', '74', '80') + #取当前可用PHP版本 + def GetPHPVersion(self,get): + phpVersions = ('00','other','52','53','54','55','56','70','71','72','73','74','80') httpdVersion = "" filename = self.setupPath + '/apache/version.pl' if os.path.exists(filename): httpdVersion = public.readFile(filename).strip() - if httpdVersion == '2.2': phpVersions = ('00', '52', '53', '54') - if httpdVersion == '2.4': phpVersions = ('00', '53', '54', '55', '56', '70', '71', '72', '73', '74', '80') + if httpdVersion == '2.2': phpVersions = ('00','52','53','54') + if httpdVersion == '2.4': phpVersions = ('00','other','53','54','55','56','70','71','72','73','74','80') if os.path.exists('/www/server/nginx/sbin/nginx'): cfile = '/www/server/nginx/conf/enable-php-00.conf' - if not os.path.exists(cfile): public.writeFile(cfile, '') + if not os.path.exists(cfile): public.writeFile(cfile,'') + s_type = getattr(get,'s_type',0) data = [] for val in phpVersions: tmp = {} - checkPath = self.setupPath + '/php/' + val + '/bin/php' - if val == '00': checkPath = '/etc/init.d/bt' - if httpdVersion == '2.2': checkPath = self.setupPath + '/php/' + val + '/libphp5.so' + checkPath = self.setupPath+'/php/'+val+'/bin/php' + if val in ['00','other']: checkPath = '/etc/init.d/bt' + if httpdVersion == '2.2': checkPath = self.setupPath+'/php/'+val+'/libphp5.so' if os.path.exists(checkPath): tmp['version'] = val - tmp['name'] = 'PHP-' + val - if val == '00': tmp['name'] = public.getMsg('STATIC') + tmp['name'] = 'PHP-'+val + if val == '00': + tmp['name'] = public.getMsg('STATIC') + + if val == 'other': + if s_type: + tmp['name'] = 'Customize' + else: + continue data.append(tmp) return data @@ -2969,6 +2990,12 @@ server data['tomcat'] = conf.find('#TOMCAT-START') data['tomcatversion'] = public.readFile(self.setupPath + '/tomcat/version.pl') data['nodejsversion'] = public.readFile(self.setupPath + '/node.js/version.pl') + data['php_other'] = '' + if data['phpversion'] == 'other': + other_file = '/www/server/panel/vhost/other_php/{}/enable-php-other.conf'.format(siteName) + if os.path.exists(other_file): + conf = public.readFile(other_file) + data['php_other'] = re.findall(r"fastcgi_pass\s+(.+);",conf)[0] return data except: return public.returnMsg(False, 'SITE_PHPVERSION_ERR_A22,{}'.format(public.get_error_info())) @@ -3006,15 +3033,57 @@ server def SetPHPVersion(self, get, multiple=None): siteName = get.siteName version = get.version + if version == 'other' and not public.get_webserver() in ['nginx','tengine']: + return public.returnMsg(False,'Custom PHP configuration only supports Nginx') try: # nginx file = self.setupPath + '/panel/vhost/nginx/' + siteName + '.conf' conf = public.readFile(file) if conf: - rep = "enable-php-([0-9]{2,3})\.conf" - tmp = re.search(rep, conf).group() - conf = conf.replace(tmp, 'enable-php-' + version + '.conf') - public.writeFile(file, conf) + other_path = '/www/server/panel/vhost/other_php/{}'.format(siteName) + if not os.path.exists(other_path): os.makedirs(other_path) + other_rep = "{}/enable-php-other.conf".format(other_path) + + + if version == 'other': + dst = other_rep + get.other = get.other.strip() + + if not get.other: + return public.returnMsg(False,'The PHP connection configuration cannot be empty when customizing the version!') + + if not re.match(r"^(\d+\.\d+\.\d+\.\d+:\d+|unix:[\w/\.-]+)$",get.other): + return public.returnMsg(False,'The PHP connection configuration format is incorrect, please refer to the example!') + + other_tmp = get.other.split(':') + if other_tmp[0] == 'unix': + if not os.path.exists(other_tmp[1]): + return public.returnMsg(False,'The specified unix socket [{}] does not exist!'.format(other_tmp[1])) + else: + if not public.check_tcp(other_tmp[0],int(other_tmp[1])): + return public.returnMsg(False,'Unable to connect to [{}], please check whether the machine can connect to the target server'.format(get.other)) + + other_conf = '''location ~ [^/]\.php(/|$) +{{ + try_files $uri =404; + fastcgi_pass {}; + fastcgi_index index.php; + include fastcgi.conf; + include pathinfo.conf; +}}'''.format(get.other) + public.writeFile(other_rep,other_conf) + conf = conf.replace(other_rep,dst) + rep = "include\s+enable-php-(\w{2,5})\.conf" + tmp = re.search(rep,conf) + if tmp: conf = conf.replace(tmp.group(),'include ' + dst) + else: + dst = 'enable-php-'+version+'.conf' + conf = conf.replace(other_rep,dst) + rep = "enable-php-(\w{2,5})\.conf" + tmp = re.search(rep,conf) + if tmp: conf = conf.replace(tmp.group(),dst) + + public.writeFile(file,conf) try: import site_dir_auth site_dir_auth_module = site_dir_auth.SiteDirAuth() @@ -3028,23 +3097,25 @@ server site_dir_auth_module.change_dir_auth_file_nginx_phpver(siteName,version,auth_name) except: pass - # apache - file = self.setupPath + '/panel/vhost/apache/' + siteName + '.conf' + + #apache + file = self.setupPath + '/panel/vhost/apache/'+siteName+'.conf' conf = public.readFile(file) - if conf: - rep = "(unix:/tmp/php-cgi-([0-9]{2,3})\.sock\|fcgi://localhost|fcgi://127.0.0.1:\d+)" - tmp = re.search(rep, conf).group() - conf = conf.replace(tmp, public.get_php_proxy(version, 'apache')) - public.writeFile(file, conf) - # OLS - file = self.setupPath + '/panel/vhost/openlitespeed/detail/' + siteName + '.conf' - conf = public.readFile(file) - if conf: - rep = 'lsphp\d+' - tmp = re.search(rep, conf) - if tmp: - conf = conf.replace(tmp.group(), 'lsphp' + version) - public.writeFile(file, conf) + if conf and version != 'other': + rep = "(unix:/tmp/php-cgi-(\w{2,5})\.sock\|fcgi://localhost|fcgi://127.0.0.1:\d+)" + tmp = re.search(rep,conf).group() + conf = conf.replace(tmp,public.get_php_proxy(version,'apache')) + public.writeFile(file,conf) + #OLS + if version != 'other': + file = self.setupPath + '/panel/vhost/openlitespeed/detail/'+siteName+'.conf' + conf = public.readFile(file) + if conf: + rep = 'lsphp\d+' + tmp = re.search(rep, conf) + if tmp: + conf = conf.replace(tmp.group(), 'lsphp' + version) + public.writeFile(file, conf) if not multiple: public.serviceReload() public.WriteLog("TYPE_SITE", "SITE_PHPVERSION_SUCCESS", (siteName, version)) @@ -3162,12 +3233,10 @@ server return json.loads(upBody) # 写配置 - def __write_config(self, path, data): return public.writeFile(path, json.dumps(data)) # 取某个站点某条反向代理详情 - def GetProxyDetals(self, get): proxyUrl = self.__read_config(self.__proxyfile) sitename = get.sitename @@ -3306,7 +3375,6 @@ server if i["sitename"] == get.sitename: if i["advanced"] != int(get.advanced): return i - # 计算proxyname md5 def __calc_md5(self, proxyname): md5 = hashlib.md5() @@ -3368,8 +3436,8 @@ server return public.returnMsg(False, "PROXY_DIR_ERR", ("?,=,[,],),(,*,&,^,%,$,#,@,!,~,`,{,},>,<,\,',\"]",)) # 检测发送域名格式 if get.todomain: - if not re.search(tod, get.todomain): - return public.returnMsg(False, 'SENT_DOMAIN_FORMAT', (get.todomain,)) + if re.search("[\}\{\#\;\"\']+",get.todomain): + return public.returnMsg(False, 'Sent Domain format error :'+get.todomain+'
                      The following special characters cannot exist [ } { # ; \" \' ] ') if public.get_webserver() != 'openlitespeed' and not get.todomain: get.todomain = "$host" @@ -3648,7 +3716,11 @@ RewriteRule ^%s(.*)$ http://%s/$1 [P,E=Proxy-Host:%s] ng_conf = re.sub("location\s+\~\*\s+\\\.\(gif.*\n\{\s*proxy_pass\s+%s.*" % (php_pass_proxy), "location ~* \.(gif|png|jpg|css|js|woff|woff2)$\n{\n\tproxy_pass %s;" % php_pass_proxy,ng_conf) - ng_conf = re.sub("\sHost\s+%s" % '\\' + conf[i]["todomain"]," Host "+get.todomain,ng_conf) + backslash = "" + if "Host $host" in ng_conf: + backslash = "\\" + + ng_conf = re.sub("\sHost\s+%s" % backslash + conf[i]["todomain"], " Host " + get.todomain, ng_conf) cache_rep = r"proxy_cache_valid\s+200\s+304\s+301\s+302\s+\d+m;((\n|.)+expires\s+\d+m;)*" if int(get.cache) == 1: if re.search(cache_rep, ng_conf): diff --git a/class/public.py b/class/public.py index cd6df0db..76ce83bc 100644 --- a/class/public.py +++ b/class/public.py @@ -49,7 +49,6 @@ def HttpGet(url,timeout = 6,headers = {}): import http_requests res = http_requests.get(url,timeout=timeout,headers = headers) if res.status_code == 0: - if old_url.find(home) != -1: return http_get_home(old_url,timeout,res.text) if headers: return False s_body = res.text return s_body @@ -113,43 +112,12 @@ def HttpPost(url,data,timeout = 6,headers = {}): import http_requests res = http_requests.post(url,data=data,timeout=timeout,headers = headers) if res.status_code == 0: - if old_url.find(home) != -1: return http_post_home(old_url,data,timeout,res.text) if headers: return False s_body = res.text return s_body s_body = res.text return s_body - -def http_post_home(url,data,timeout,ex): - """ - @name POST方式使用优选节点访问官网 - @author hwliang - @param url(string) 当前官网URL地址 - @param data(dict) POST数据 - @param timeout(int) 用于测试超时时间 - @param ex(string) 上一次错误的响应内容 - @return string 响应内容 - - 如果已经是优选节点,将直接返回ex - """ - try: - home = 'www.bt.cn' - if url.find(home) == -1: return ex - hosts_file = "config/hosts.json" - if not os.path.exists(hosts_file): return ex - hosts = json.loads(readFile(hosts_file)) - headers = {"host": home} - for host in hosts: - new_url = url.replace(home, host) - res = HttpPost(new_url, data, timeout, headers) - if res: - writeFile("data/home_host.pl", host) - # set_home_host(host) - return res - return ex - except: return ex - def httpPost(url,data,timeout=6): """ @name 发送POST请求 @@ -200,7 +168,6 @@ def FileMd5(filename): f.close() return my_hash.hexdigest() - def GetRandomString(length): """ @name 取随机字符串 @@ -336,6 +303,13 @@ def ReadFile(filename,mode = 'r'): return f_body def readFile(filename,mode='r'): + ''' + @name 读取指定文件数据 + @author hwliang<2021-06-09> + @param filename 文件名 + @param mode 文件打开模式,默认r + @return string or bytes or False 如果返回False则说明读取失败 + ''' return ReadFile(filename,mode) def WriteFile(filename,s_body,mode='w+'): @@ -360,6 +334,14 @@ def WriteFile(filename,s_body,mode='w+'): return False def writeFile(filename,s_body,mode='w+'): + ''' + @name 写入到指定文件 + @author hwliang<2021-06-09> + @param filename 文件名 + @param s_boey 被写入的内容,字节或字符串 + @param mode 文件打开模式,默认w+ + @return bool + ''' return WriteFile(filename,s_body,mode) def WriteLog(type,logMsg,args=(),not_web = False): @@ -409,7 +391,9 @@ def GetConfigValue(key): 取配置值 ''' config = GetConfig() - if not key in config.keys(): return None + if not key in config.keys(): + if key == 'download': return 'https://node.aapanel.com' + return None return config[key] def SetConfigValue(key,value): @@ -495,7 +479,7 @@ def serviceReload(): return ServiceReload() -def ExecShell(cmdstring, cwd=None, timeout=None, shell=True): +def ExecShell(cmdstring, timeout=None, shell=True,cwd=None,env=None): a = '' e = '' import subprocess,tempfile @@ -504,8 +488,20 @@ def ExecShell(cmdstring, cwd=None, timeout=None, shell=True): rx = md5(cmdstring) succ_f = tempfile.SpooledTemporaryFile(max_size=4096,mode='wb+',suffix='_succ',prefix='btex_' + rx ,dir='/dev/shm') err_f = tempfile.SpooledTemporaryFile(max_size=4096,mode='wb+',suffix='_err',prefix='btex_' + rx ,dir='/dev/shm') - sub = subprocess.Popen(cmdstring, close_fds=True, shell=shell,bufsize=128,stdout=succ_f,stderr=err_f) - sub.wait() + sub = subprocess.Popen(cmdstring, close_fds=True, shell=shell,bufsize=128,stdout=succ_f,stderr=err_f,cwd=cwd,env=env) + if timeout: + s = 0 + d = 0.01 + while sub.poll() is None: + time.sleep(d) + s += d + if s >= timeout: + if not err_f.closed: err_f.close() + if not succ_f.closed: succ_f.close() + return 'Timed out' + else: + sub.wait() + err_f.seek(0) succ_f.seek(0) a = succ_f.read() @@ -513,7 +509,7 @@ def ExecShell(cmdstring, cwd=None, timeout=None, shell=True): if not err_f.closed: err_f.close() if not succ_f.closed: succ_f.close() except: - print(get_error_info()) + return '',get_error_info() try: #编码修正 if type(a) == bytes: a = a.decode('utf-8') @@ -600,7 +596,9 @@ def phpReload(version): if os.path.exists('/www/server/php/' + version + '/libphp5.so'): ExecShell('/etc/init.d/httpd reload') else: - ExecShell('/etc/init.d/php-fpm-' + version + ' reload') + ExecShell('/etc/init.d/php-fpm-'+version+' reload') + ExecShell("/etc/init.d/php-fpm-{} start".format(version)) + def get_timeout(url,timeout=3): try: @@ -610,6 +608,8 @@ def get_timeout(url,timeout=3): except: return 0,False def get_url(timeout = 0.5): + return 'https://node.aapanel.com' + import json try: pkey = 'node_url' @@ -824,6 +824,9 @@ def getSpeed(): writeFile('/tmp/panelSpeed.pl', data) return json.loads(data) +def get_requests_headers(): + return {"Content-type":"application/x-www-form-urlencoded","User-Agent":"BT-Panel"} + def downloadFile(url,filename): try: if sys.version_info[0] == 2: @@ -834,16 +837,30 @@ def downloadFile(url,filename): f.write(r.content) else: import urllib.request + import ssl + ssl._create_default_https_context = ssl._create_unverified_context opener = urllib.request.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36')] urllib.request.install_opener(opener) - urllib.request.urlretrieve(url, filename=filename, reporthook=downloadHook) + urllib.request.urlretrieve(url, filename=filename) except: - return get_error_info() + ExecShell("wget -O --no-check-certificate {} {}".format(filename,url)) + +def exists_args(args,get): + ''' + @name 检查参数是否存在 + @author hwliang<2021-06-08> + @param args 参数列表 允许是列表或字符串 + @param get 参数对像 + @return bool 都存在返回True,否则抛出KeyError异常 + ''' + if type(args) == str: + args = args.split(',') + for arg in args: + if not arg in get: + raise KeyError('Required parameters are missing:{}'.format(arg)) + return True -def downloadHook(count, blockSize, totalSize): - speed = {'total':totalSize,'block':blockSize,'count':count} - #print('%02d%%'%(100.0 * count * blockSize / totalSize)) def get_error_info(): import traceback @@ -851,6 +868,78 @@ def get_error_info(): return errorMsg +def get_plugin_replace_rules(): + ''' + @name 获取插件文件内容替换规则 + @author hwliang<2021-06-28> + @return list + ''' + return [ + { + "find":"[PATH]", + "replace": "[PATH]" + } + ] + + +def get_plugin_title(plugin_name): + ''' + @name 获取插件标题 + @author hwliang<2021-06-24> + @param plugin_name 插件名称 + @return string + ''' + + info_file = '/www/server/panel/plugin/{}/info.json'.format(plugin_name) + try: + return json.loads(readFile(info_file))['title'] + except: + return plugin_name + +def get_error_object(plugin_title = None,plugin_name = None): + ''' + @name 获取格式化错误响应对像 + @author hwliang<2021-06-21> + @return Resp + ''' + if not plugin_title: plugin_title = get_plugin_title(plugin_name) + try: + from BTPanel import request,Resp + is_cli = False + except: + is_cli = True + + if is_cli: + raise get_error_info() + ss = '''404 Not Found: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. + +During handling of the above exception, another exception occurred:''' + error_info = get_error_info().strip().split(ss)[-1].strip() + request_info = '''REQUEST_DATE: {request_date} + PAN_VERSION: {panel_version} + OS_VERSION: {os_version} + REMOTE_ADDR: {remote_addr} + REQUEST_URI: {method} {full_path} +REQUEST_FORM: {request_form} + USER_AGENT: {user_agent}'''.format( + request_date = getDate(), + remote_addr = GetClientIp(), + method = request.method, + full_path = request.full_path, + request_form = request.form.to_dict(), + user_agent = request.headers.get('User-Agent'), + panel_version = get_panel_version(), + os_version = get_os_version() +) + + result =readFile('/www/server/panel/BTPanel/templates/default/plugin_error.html').format( + plugin_name=plugin_title, + request_info=request_info, + error_title=error_info.split("\n")[-1], + error_msg=error_info + ) + return Resp(result,500) + # 搜索数据中是否存在 def inArray(arrays, searchStr): for key in arrays: @@ -1233,6 +1322,22 @@ def get_uuid(): import uuid return uuid.UUID(int=uuid.getnode()).hex[-12:] +#取计算机名 +def get_hostname(): + import socket + return socket.gethostname() + + +#取mysql datadir +def get_datadir(): + mycnf_file = '/etc/my.cnf' + if not os.path.exists(mycnf_file): return '' + mycnf = readFile(mycnf_file) + import re + tmp = re.findall(r"datadir\s*=\s*(.+)",mycnf) + if not tmp: return '' + return tmp[0] + #进程是否存在 def process_exists(pname,exe = None,cmdline = None): @@ -1253,8 +1358,13 @@ def process_exists(pname,exe = None,cmdline = None): except: pass return False - except: + except: return True + +#pid是否存在 +def pid_exists(pid): + if os.path.exists('/proc/{}/exe'.format(pid)): return True + return False # 重启面板 @@ -1359,18 +1469,79 @@ def get_panel_version(): return version -# 取文件或目录大小 -def get_path_size(path): +def get_os_version(): + ''' + @name 取操作系统版本 + @author hwliang<2021-08-07> + @return string + ''' + version = readFile('/etc/redhat-release') + if not version: + version = readFile('/etc/issue').strip().split("\n")[0].replace('\\n','').replace('\l','').strip() + else: + version = version.replace('release ','').replace('Linux','').replace('(Core)','').strip() + v_info = sys.version_info + version = "{} {}(Py{}.{}.{})".format(version,os.uname().machine,v_info.major,v_info.minor,v_info.micro) + return version + +#取文件或目录大小 +def get_path_size(path, exclude=[]): + """根据排除目录获取路径的总大小 + + :path 目标路径 + :exclude 排除路径单个字符串或者多个列表。匹配路径是基于path的相对路径,规则是 + tar命令的--exclude规则的子集。 + """ + import fnmatch if not os.path.exists(path): return 0 - if not os.path.isdir(path): return os.path.getsize(path) - size_total = 0 - for nf in os.walk(path): - for f in nf[2]: - filename = nf[0] + '/' + f + if os.path.isfile(path): return os.path.getsize(path) + if type(exclude) != type([]): + exclude = [exclude] + + path = path[0:-1] if path[-1] == "/" else path + path = os.path.normcase(path) + # print("path:"+ path) + # print("exclude:"+ str(exclude)) + _exclude = exclude[0:] + for i, e in enumerate(_exclude): + if not e.startswith(path): + basename = os.path.basename(path) + if not e.startswith(basename): + exclude.append(os.path.join(path, e)) + else: + new_exc = e.replace(basename+"/", "") + new_exc = os.path.join(path, new_exc) + exclude.append(new_exc) + + # print(exclude) + total_size = 0 + count = 0 + for root, dirs, files in os.walk(path, topdown=True): + # filter path + for exc in exclude: + for d in dirs: + sub_dir = os.path.normcase(root+os.path.sep+d) + if fnmatch.fnmatch(sub_dir, exc) or d==exc: + # print("排除目录:"+sub_dir) + dirs.remove(d) + count += 1 + for f in files: + to_exclude = False + count += 1 + filename = os.path.normcase(root+os.path.sep+f) if not os.path.exists(filename): continue if os.path.islink(filename): continue - size_total += os.path.getsize(filename) - return size_total + # filter file + norm_filename = os.path.normcase(filename) + for fexc in exclude: + if fnmatch.fnmatch(norm_filename, fexc) or fexc==f: + to_exclude = True + # print("排除文件:"+norm_filename) + break + if to_exclude: + continue + total_size += os.path.getsize(filename) + return total_size #写关键请求日志 def write_request_log(reques = None): @@ -1533,22 +1704,54 @@ def de_crypt(key,strings): return strings +#获取IP限制列表 +def get_limit_ip(): + iplong_list = [] + ip_file = 'data/limitip.conf' + if not os.path.exists(ip_file): return iplong_list + + from BTPanel import cache + ikey = 'limit_ip' + iplong_list = cache.get(ikey) + if iplong_list: return iplong_list + + iplong_list = [] + iplist = ReadFile(ip_file) + if not iplist:return iplong_list + iplist = iplist.strip() + for limit_ip in iplist.split(','): + if not limit_ip: continue + limit_ip = limit_ip.split('-') + iplong = {} + iplong['min'] = ip2long(limit_ip[0]) + if len(limit_ip) > 1: + iplong['max'] = ip2long(limit_ip[1]) + else: + iplong['max'] = iplong['min'] + iplong_list.append(iplong) + + cache.set(ikey,iplong_list,3600) + return iplong_list + + + + #检查IP白名单 def check_ip_panel(): - ip_file = 'data/limitip.conf' - if os.path.exists(ip_file): - iplist = ReadFile(ip_file) - if iplist: - iplist = iplist.strip() - client_ip = GetClientIp() - if client_ip in ['127.0.0.1','localhost','::1']: return False - if not client_ip in iplist.split(','): - errorStr = ReadFile('./BTPanel/templates/' + GetConfigValue('template') + '/error2.html') - try: - errorStr = errorStr.format(getMsg('PAGE_ERR_TITLE'),getMsg('PAGE_ERR_IP_H1'),getMsg('PAGE_ERR_IP_P1',(GetClientIp(),)),getMsg('PAGE_ERR_IP_P2'),getMsg('PAGE_ERR_IP_P3'),getMsg('NAME'),getMsg('PAGE_ERR_HELP')) - except IndexError:pass - return errorStr - return False + iplong_list = get_limit_ip() + if not iplong_list: return False + client_ip = GetClientIp() + if client_ip in ['127.0.0.1','localhost','::1']: return False + client_ip_long = ip2long(client_ip) + for limit_ip in iplong_list: + if client_ip_long >= limit_ip['min'] and client_ip_long <= limit_ip['max']: + return False + + errorStr = ReadFile('./BTPanel/templates/' + GetConfigValue('template') + '/error2.html') + try: + errorStr = errorStr.format(getMsg('PAGE_ERR_TITLE'),getMsg('PAGE_ERR_IP_H1'),getMsg('PAGE_ERR_IP_P1',(GetClientIp(),)),getMsg('PAGE_ERR_IP_P2'),getMsg('PAGE_ERR_IP_P3'),getMsg('NAME'),getMsg('PAGE_ERR_HELP')) + except IndexError:pass + return errorStr #检查面板域名 def check_domain_panel(): @@ -1625,7 +1828,7 @@ def sync_date(): if os.path.exists(tip_file): if s_time - int(readFile(tip_file)) < 60: return False os.remove(tip_file) - time_str = HttpGet('http://www.bt.cn/api/index/get_time') + time_str = HttpGet(GetConfigValue('home') + '/api/index/get_time') new_time = int(time_str) time_arr = time.localtime(new_time) date_str = time.strftime("%Y-%m-%d %H:%M:%S", time_arr) @@ -1724,7 +1927,7 @@ def request_php(version,uri,document_root,method='GET',pdata=b''): return result -def get_fpm_address(php_version): +def get_fpm_address(php_version,bind=False): ''' @name 获取FPM请求地址 @author hwliang<2020-10-23> @@ -1740,7 +1943,10 @@ def get_fpm_address(php_version): if tmp[0].find('sock') != -1: return fpm_address if tmp[0].find(':') != -1: listen_tmp = tmp[0].split(':') - fpm_address = ('127.0.0.1',int(listen_tmp[1])) + if bind: + fpm_address = (listen_tmp[0],int(listen_tmp[1])) + else: + fpm_address = ('127.0.0.1',int(listen_tmp[1])) else: fpm_address = ('127.0.0.1',int(tmp[0])) return fpm_address @@ -1777,7 +1983,7 @@ def get_php_version_conf(conf): ''' if not conf: return '00' if conf.find('enable-php-') != -1: - rep = r"enable-php-([0-9]{2,3})\.conf" + rep = r"enable-php-(\w{2,5})\.conf" tmp = re.findall(rep,conf) if not tmp: return '00' elif conf.find('/usr/local/lsws/lsphp') != -1: @@ -1809,6 +2015,25 @@ def get_site_php_version(siteName): return get_php_version_conf(conf) +def check_tcp(ip,port): + ''' + @name 使用TCP的方式检测指定IP:端口是否能连接 + @author hwliang<2021-06-01> + @param ip IP地址 + @param port 端口 + @return bool + ''' + import socket + try: + s = socket.socket() + s.settimeout(5) + s.connect((ip.strip(),int(port))) + s.close() + except: + return False + return True + + def sub_php_address(conf_file,rep,tsub,php_version): ''' @name 替换新的PHP配置到配置文件 @@ -2070,9 +2295,10 @@ def get_debug_log(): #获取sessionid def get_session_id(): - from BTPanel import request - session_id = request.cookies.get('SESSIONID','') - if not re.findall(r"^([\w\.-]{64,64})$",session_id): return GetRandomString(64) + from BTPanel import request,app + session_id = request.cookies.get(app.config['SESSION_COOKIE_NAME'],'') + if not re.findall(r"^([\w\.-]{64,64})$",session_id): + return GetRandomString(64) return session_id #尝试自动恢复面板数据库 @@ -2200,11 +2426,14 @@ def get_ssh_port(): s_file = '/etc/ssh/sshd_config' conf = readFile(s_file) if not conf: conf = '' - rep = r"#*Port\s+([0-9]+)\s*\n" - tmp1 = re.search(rep, conf) + port_all = re.findall(r".*Port\s+[0-9]+",conf) ssh_port = 22 - if tmp1: - ssh_port = int(tmp1.groups(0)[0]) + for p in port_all: + rep = r"^\s*Port\s+([0-9]+)\s*" + tmp1 = re.findall(rep,p) + if tmp1: + ssh_port = int(tmp1[0]) + return ssh_port def set_error_num(key,empty = False,expire=3600): @@ -2386,6 +2615,8 @@ def cloud_check_domain(domain): check_domain_path = '/www/server/panel/data/check_domain/' if not os.path.exists(check_domain_path): os.makedirs(check_domain_path,384) + pdata = get_user_info() + pdata['domain'] = domain result = httpPost('https://www.aapanel.com/api/panel/checkDomain',{"domain":domain}) cd_file = check_domain_path + domain +'.pl' writeFile(cd_file,result) @@ -2393,6 +2624,23 @@ def cloud_check_domain(domain): pass +def get_user_info(): + user_file = '/www/server/panel/data/userInfo.json' + if not os.path.exists(user_file): return {} + userInfo = {} + try: + userTmp = json.loads(readFile(user_file)) + userInfo['uid'] = userTmp['id'] + userInfo['username'] = userTmp['username'] + userInfo['serverid'] = userTmp['serverid'] + userInfo['oem'] = get_oem_name() + userInfo['o'] = userInfo['oem'] + except: pass + return userInfo + + + + def send_file(data,fname='',mimetype = ''): ''' @name 以文件流的形式返回 @@ -2449,12 +2697,41 @@ def get_oem_name(): @return string ''' oem = '' - oem_file = '/www/server/panel/data/o.pl' + oem_file = '{}/data/o.pl'.format(get_panel_path()) if os.path.exists(oem_file): oem = readFile(oem_file) if oem: oem = oem.strip() return oem +def get_pdata(): + ''' + @name 构造POST基础参数 + @author hwliang<2021-03-24> + @return dict + ''' + import panelAuth + pdata = panelAuth.panelAuth().create_serverid(None) + pdata['oem'] = get_oem_name() + return pdata + + +# 名称输入系列化 +def xssdecode(text): + try: + cs = {""":'"',"'":"'"} + for c in cs.keys(): + text = text.replace(c,cs[c]) + + str_convert = text + if sys.version_info[0] == 3: + import html + text2 = html.unescape(str_convert) + else: + text2 = cgi.unescape(str_convert) + return text2 + except: + return text + def fetch_disk_SN(): r,e = ExecShell("fdisk -l |grep 'Disk identifier' |awk {'print $3'}") if r: @@ -2511,6 +2788,8 @@ class dict_obj: def __delitem__(self,key): delattr(self,key) def __delattr__(self, key): delattr(self,key) def get_items(self): return self + def exists(self,keys): + return exists_args(keys,self) def get(self,key,default='',format='',limit = []): ''' @name 获取指定参数 @@ -2659,7 +2938,7 @@ class get_modules: else: print(p.__dict__) ''' - os.chdir('/www/server/panel') + os.chdir(get_panel_path()) exp_files = ['__init__.py','__pycache__'] if not path in sys.path: sys.path.insert(0,path) @@ -2685,7 +2964,7 @@ class get_modules: #检查App和小程序的绑定 def check_app(check='app'): - path='/www/server/panel/' + path=get_panel_path() + '/' if check=='app': try: if not os.path.exists(path+'data/user.json') and os.path.exists(path+'config/api.json') and not os.path.exists(path+'plugin/app/user.json'):return False @@ -2723,8 +3002,8 @@ def send_mail(title,body,is_logs=False,is_type="aapanel login reminder"): import send_mail send_mail22 = send_mail.send_mail() tongdao = send_mail22.get_settings() - if tongdao['user_mail']['mail_list']==0:return false - if not tongdao['user_mail']['info']: return false + if tongdao['user_mail']['mail_list']==0:return False + if not tongdao['user_mail']['info']: return False if len(tongdao['user_mail']['mail_list'])==1: send_mail=tongdao['user_mail']['mail_list'][0] send_mail22.qq_smtp_send(send_mail, title=title, body=body) @@ -2739,8 +3018,8 @@ def send_mail(title,body,is_logs=False,is_type="aapanel login reminder"): import send_mail send_mail22 = send_mail.send_mail() tongdao = send_mail22.get_settings() - if tongdao['user_mail']['mail_list'] == 0: return false - if not tongdao['user_mail']['info']: return false + if tongdao['user_mail']['mail_list'] == 0: return False + if not tongdao['user_mail']['info']: return False if len(tongdao['user_mail']['mail_list']) == 1: send_mail = tongdao['user_mail']['mail_list'][0] return send_mail22.qq_smtp_send(send_mail, title=title, body=body) @@ -2756,7 +3035,7 @@ def send_dingding(body,is_logs=False,is_type="aapanel login reminder"): import send_mail send_mail22 = send_mail.send_mail() tongdao = send_mail22.get_settings() - if not tongdao['dingding']['info']: return false + if not tongdao['dingding']['info']: return False tongdao = send_mail22.get_settings() if is_logs: WriteLog2(is_type,body) @@ -2768,15 +3047,16 @@ def send_dingding(body,is_logs=False,is_type="aapanel login reminder"): import send_mail send_mail22 = send_mail.send_mail() tongdao = send_mail22.get_settings() - if not tongdao['dingding']['info']: return false + if not tongdao['dingding']['info']: return False tongdao = send_mail22.get_settings() return send_mail22.dingding_send(body) except:return False #获取服务器IP def get_ip(): - if os.path.exists('/www/server/panel/data/iplist.txt'): - data=ReadFile('/www/server/panel/data/iplist.txt') + iplist_file = '{}/data/iplist.txt'.format(get_panel_path()) + if os.path.exists(iplist_file): + data=ReadFile(iplist_file) return data.strip() else:return '127.0.0.1' @@ -2825,11 +3105,14 @@ def check_ip_white(path,ip): #登陆告警 def login_send_body(is_type,username,login_ip,port): - if os.path.exists("/www/server/panel/data/login_send_mail.pl"): - if check_ip_white('/www/server/panel/data/send_login_white.json',login_ip):return False + login_send_mail = "{}/data/login_send_mail.pl".format(get_panel_path()) + send_login_white = '{}/data/send_login_white.json'.format(get_panel_path()) + login_send_dingding = "{}/data/login_send_dingding.pl".format(get_panel_path()) + if os.path.exists(login_send_mail): + if check_ip_white(send_login_white,login_ip):return False send_mail("aapanel login reminder","aapanel login reminder:Your server "+get_ip()+" successfully logged in via "+is_type+", account number: "+username+", login IP: "+login_ip+":"+port+", login time: "+time.strftime('%Y -%m-%d %X',time.localtime()), True) - if os.path.exists("/www/server/panel/data/login_send_dingding.pl"): - if check_ip_white('/www/server/panel/data/send_login_white.json',login_ip):return False + if os.path.exists(login_send_dingding): + if check_ip_white(send_login_white,login_ip):return False send_dingding("aapanel login reminder:Your server "+get_ip()+" successfully logged in via "+is_type+", account number: "+username+", login IP: "+login_ip+":"+port+", login time: "+time.strftime('%Y -%m-%d %X',time.localtime()), True) #普通模式下调用发送消息【设置登陆告警后的设置】 @@ -2838,11 +3121,14 @@ def login_send_body(is_type,username,login_ip,port): #is_logs= 是否记录日志 #is_type=发送告警的类型 def send_to_body(title,body,is_logs=False,is_type="aaPanel email alert"): - if os.path.exists("/www/server/panel/data/login_send_mail.pl"): + login_send_mail = "{}/data/login_send_mail.pl".format(get_panel_path()) + login_send_dingding = "{}/data/login_send_dingding.pl".format(get_panel_path()) + if os.path.exists(login_send_mail): if is_logs: send_mail(title, body,True,is_type) send_mail(title,body) - if os.path.exists("/www/server/panel/data/login_send_dingding.pl"): + + if os.path.exists(login_send_dingding): if is_logs: send_dingding(body,True,is_type) send_dingding(body) @@ -2864,4 +3150,171 @@ def return_is_send_info(): ret={} ret['mail']=tongdao['user_mail']['user_name'] ret['dingding']=tongdao['dingding']['dingding'] - return ret \ No newline at end of file + return ret + + +def get_sys_path(): + ''' + @name 关键目录 + @author hwliang<2021-06-11> + @return tuple + ''' + a = ['/www','/usr','/','/dev','/home','/media','/mnt','/opt','/tmp','/var'] + c = ['/www/Recycle_bin/','/www/backup/','/www/php_session/','/www/wwwlogs/','/www/server/','/etc/','/usr/','/var/','/boot/','/proc/','/sys/','/tmp/','/root/','/lib/','/bin/','/sbin/','/run/','/lib64/','/lib32/','/srv/'] + return a,c + + +def check_site_path(site_path): + ''' + @name 检查网站根目录是否为系统关键目录 + @author hwliang<2021-05-31> + @param site_path 网站根目录全路径 + @return bool + ''' + whites = ['/www/server/tomcat','/www/server/stop','/www/server/phpmyadmin'] + for w in whites: + if site_path.find(w) == 0: return True + a,error_paths = get_sys_path() + site_path = site_path.strip() + if site_path[-1] == '/': site_path = site_path[:-1] + if site_path in a: + return False + site_path += '/' + for ep in error_paths: + if site_path.find(ep) == 0: return False + return True + +def is_debug(): + debug_file = "{}/data/debug.pl".format(get_panel_path()) + return os.path.exists(debug_file) + + +class PanelError(Exception): + ''' + @name 宝塔通用异常对像 + @author hwliang<2021-06-25> + ''' + def __init__(self, value): + self.value = value + + def __str__(self): + return ("面板运行时发生错误: {}".format(repr(self.value))) + +def get_setup_path(): + ''' + @name 获取安装路径 + @author hwliang<2021-07-22> + @return string + ''' + return '/www/server' + +def get_panel_path(): + ''' + @name 取面板根目录 + @author hwliang<2021-07-14> + @return string + ''' + return '{}/panel'.format(get_setup_path()) + +def check_hooks(): + ''' + @name 自动注册HOOK + @author hwliang<2021-07-19> + @return void + ''' + hooks_path = '{}/hooks'.format(get_panel_path()) + if not os.path.exists(hooks_path): + return + for hook_name in os.listdir(hooks_path): + if hook_name[-3:] != '.py': continue + filename = os.path.join(hooks_path,hook_name) + _obj = get_script_object(filename) + _main = getattr(_obj,'main',None) + if not _main: continue + _main() + +def register_hook(hook_index, hook_def): + ''' + @name 注册HOOK + @author hwliang<2021-07-15> + @param hook_index HOOK位置 + @param hook_def HOOK函数对像 + @return void + ''' + from BTPanel import hooks + hook_keys = hooks.keys() + if not hook_index in hook_keys: + hooks[hook_index] = [] + if not hook_def in hooks[hook_index]: + hooks[hook_index].append(hook_def) + +def exec_hook(hook_index, data): + ''' + @name 执行HOOk + @author hwliang<2021-07-15> + @param hook_index HOOK索引位置,格式限制:^\w+$ + @param data 运行数据 + @return mixed + ''' + + from BTPanel import hooks + hook_keys = hooks.keys() + if not hook_index in hook_keys: + return data + + for hook_def in hooks[hook_index]: + data = hook_def(data) + return data + +def get_hook_index(mod_name, def_name): + ''' + @name 获取HOOK位置 + @author hwliang<2021-07-19> + @param mod_name 模块名称 + @param def_name 方法名称 + @return tuple + ''' + mod_name = mod_name.upper() + def_name = def_name.upper() + last_index = '{}_{}_LAST'.format(mod_name, def_name) + end_index = '{}_{}_END'.format(mod_name, def_name) + return last_index, end_index + +def get_session_timeout(): + ''' + @name 获取session过期时间 + @author hwliang<2021-07-28> + @return int + ''' + from BTPanel import cache + skey = 'session_timeout' + session_timeout = cache.get(skey) + if not session_timeout is None: return session_timeout + + sess_out_path = '{}/data/session_timeout.pl'.format(get_panel_path()) + session_timeout = 86400 + if not os.path.exists(sess_out_path): + return session_timeout + session_timeout = int(readFile(sess_out_path)) + cache.set(skey,session_timeout,3600) + return session_timeout + + +def get_login_token_auth(): + ''' + @name 获取登录token + @author hwliang<2021-07-28> + @return string + ''' + from BTPanel import cache + skey = 'login_token' + login_token = cache.get(skey) + if not login_token is None: return login_token + + login_token_file = '{}/data/login_token.pl'.format(get_panel_path()) + login_token = '1234567890' + if not os.path.exists(login_token_file): + return login_token + login_token = readFile(login_token_file) + cache.set(skey,login_token,3600) + return login_token \ No newline at end of file diff --git a/class/setPanelLets.py b/class/setPanelLets.py index 1a15d3a8..ab653393 100644 --- a/class/setPanelLets.py +++ b/class/setPanelLets.py @@ -85,7 +85,7 @@ class setPanelLets: gcl = pssl.GetCertList(get) for i in gcl: for v in i.values(): - if get.domain in v: + if get.domain == v: try: time_stamp = int(i['notAfter']) except: diff --git a/class/site_dir_auth.py b/class/site_dir_auth.py index 9690275c..12987216 100644 --- a/class/site_dir_auth.py +++ b/class/site_dir_auth.py @@ -123,9 +123,9 @@ class SiteDirAuth: try: conf = public.readFile(self.setup_path + '/panel/vhost/'+public.get_webserver()+'/'+siteName+'.conf'); if public.get_webserver() == 'nginx': - rep = "enable-php-([0-9]{2,3})\.conf" + rep = "enable-php-(\w{2,5})\.conf" else: - rep = "php-cgi-([0-9]{2,3})\.sock" + rep = "php-cgi-(\w{2,5})\.sock" tmp = re.search(rep,conf).groups() if tmp: return tmp[0] @@ -145,8 +145,15 @@ class SiteDirAuth: conf = public.readFile(file_path) if not conf: return False - rep = "include\s+enable-php-\d+\.conf;" - conf = re.sub(rep,'include enable-php-{}.conf;'.format(phpv),conf) + + if phpv == 'other': + php_conf = "include /www/server/panel/vhost/other_php/{}/enable-php-other.conf;".format(site_name) + else: + php_conf = 'include enable-php-{}.conf;'.format(phpv) + + rep = r"include\s+(enable-php-\w+|/www/server/panel/vhost/other_php/{}/enable-php-other)\.conf;".format(site_name) + conf = re.sub(rep,php_conf,conf) + public.writeFile(file_path,conf) # 设置独立认证文件 @@ -154,7 +161,11 @@ class SiteDirAuth: php_ver = self.get_site_php_version(site_name) php_conf = "" if php_ver: - php_conf = "include enable-php-{}.conf;".format(php_ver) + if php_ver == 'other': + php_conf = "include /www/server/panel/vhost/other_php/{}/enable-php-{}.conf;".format(site_name,php_ver) + else: + php_conf = "include enable-php-{}.conf;".format(php_ver) + for i in ["nginx","apache"]: file_path = "{setup_path}/panel/vhost/{webserver}/dir_auth/{site_name}" if i == "nginx": @@ -242,26 +253,27 @@ class SiteDirAuth: site_info = self.get_site_info(get.id) site_name = site_info["site_name"] conf = self._read_conf() - if site_name in conf: - for i in range(len(conf[site_name])): - if name in conf[site_name][i].values(): - print(conf[site_name][i]) - del(conf[site_name][i]) - if not conf[site_name]: - del(conf[site_name]) - break - public.writeFile(self.conf_file,json.dumps(conf)) - for i in ["nginx", "apache"]: - file_path = "{setup_path}/panel/vhost/{webserver}/dir_auth/{site_name}/{name}.conf".format(webserver=i, - setup_path=self.setup_path, - site_name=site_name, - name=name) - os.remove(file_path) - if not conf: - self.set_conf(site_name,"delete") - if not hasattr(get,'multiple'): - public.serviceReload() - return public.returnMsg(True,"DEL_SUCCESS") + if site_name not in conf: + return public.returnMsg(False,"The website does not exist in the configuration:{}".format(site_name)) + for i in range(len(conf[site_name])): + if name in conf[site_name][i].values(): + print(conf[site_name][i]) + del(conf[site_name][i]) + if not conf[site_name]: + del(conf[site_name]) + break + public.writeFile(self.conf_file,json.dumps(conf)) + for i in ["nginx", "apache"]: + file_path = "{setup_path}/panel/vhost/{webserver}/dir_auth/{site_name}/{name}.conf".format(webserver=i, + setup_path=self.setup_path, + site_name=site_name, + name=name) + os.remove(file_path) + if not conf: + self.set_conf(site_name,"delete") + if not hasattr(get,'multiple'): + public.serviceReload() + return public.returnMsg(True,"DEL_SUCCESS") # 修改目录保护密码 def modify_dir_auth_pass(self,get): diff --git a/class/ssh_terminal.py b/class/ssh_terminal.py index 5516c3ce..91dbbaee 100644 --- a/class/ssh_terminal.py +++ b/class/ssh_terminal.py @@ -47,6 +47,7 @@ class ssh_terminal: _tp = None _old_conf = None _debug_file = 'logs/terminal.log' + _s_code = None def connect(self): ''' @@ -123,8 +124,16 @@ class ssh_terminal: pkey = paramiko.DSSKey.from_private_key(p_file) self._tp.auth_publickey(username=self._user, key=pkey) else: - self.debug(public.getMsg('AUTH_PASSWD')) - self._tp.auth_password(username=self._user, password=self._pass) + try: + self._tp.auth_none(self._user) + except Exception as e: + e = str(e) + if e.find('keyboard-interactive') >= 0: + self._auth_interactive() + else: + self.debug('Authenticating password') + self._tp.auth_password(username=self._user, password=self._pass) + # self._tp.auth_password(username=self._user, password=self._pass) except Exception as e: if self._old_conf: s_file = '/www/server/panel/config/t_info.json' @@ -132,6 +141,11 @@ class ssh_terminal: self.set_sshd_config(True) self._tp.close() e = str(e) + if e.find('websocket error!') != -1: + return returnMsg(True,'connection succeeded') + if e.find('Authentication timeout') != -1: + self.debug("认证超时{}".format(e)) + return returnMsg(False,'Authentication timed out, please press enter to try again!{}'.format(e)) if e.find('Authentication failed') != -1: self.debug(public.getMsg('AUTH_FAIL',(str(e),))) return returnMsg(False,'SSH_LOGIN_ERR1',(str(e + "," + self._user + "@" + self._host + ":" +str(self._port)),)) @@ -167,6 +181,40 @@ class ssh_terminal: self.debug('SSH_LOGIN_INFO2') return returnMsg(True,'CONNECTION_SUCCEEDED') + def _auth_interactive(self): + self.debug('Verification Code') + + self.brk = False + + def handler(title, instructions, prompt_list): + if not self._ws: raise public.PanelError('websocket error!') + if instructions: + self._ws.send(instructions) + if title: + self._ws.send(title) + resp = [] + for pr in prompt_list: + if str(pr[0]).strip() == "Password:": + resp.append(self._pass) + elif str(pr[0]).strip() == "Verification code:": + # 获取前段传入的验证码 + self._ws.send("Verification code# ") + self._s_code = True + code = "" + while True: + data = self._ws.receive() + if data.find('"resize":1') != -1: + self.resize(data) + continue + self._ws.send(data) + if data in ["\n", "\r"]: break + code += data + resp.append(code) + self._ws.send("\n") + self._s_code = None + return tuple(resp) + + self._tp.auth_interactive(self._user, handler) def get_login_user(self): ''' @@ -349,7 +397,6 @@ class ssh_terminal: @return bool ''' self.is_running(rep) - return False if rep and not self._rep_ssh_config: return False @@ -490,6 +537,9 @@ class ssh_terminal: ''' try: while not self._ws.closed: + if self._s_code: + time.sleep(0.1) + continue client_data = self._ws.receive() if not client_data: continue if len(client_data) > 10: @@ -588,7 +638,8 @@ class ssh_terminal: try: if self._ssh: self._ssh.close() - #self._ssh = None + if self._tp: # 关闭宿主服务 + self._tp.close() if not self._ws.closed: self._ws.close() except: @@ -609,8 +660,11 @@ class ssh_terminal: self._pkey = ssh_info['pkey'] if 'password' in ssh_info: self._pass = ssh_info['password'] - - result = self.connect() + try: + result = self.connect() + except Exception as ex: + if str(ex).find("NoneType") == -1: + raise public.PanelError(ex) return result diff --git a/class/system.py b/class/system.py index 9bd7de18..07c1e6db 100644 --- a/class/system.py +++ b/class/system.py @@ -127,46 +127,46 @@ class system: data['web'] = tmp tmp = {} - vfile = self.setupPath + '/phpmyadmin/version.pl'; - tmp['version'] = public.readFile(vfile); + vfile = self.setupPath + '/phpmyadmin/version.pl' + tmp['version'] = public.readFile(vfile) if tmp['version']: tmp['version'] = tmp['version'].strip() - tmp['setup'] = os.path.exists(vfile); - tmp['status'] = pstatus; - tmp['phpversion'] = phpversion.strip(); - tmp['port'] = phpport; - tmp['auth'] = pauth; - data['phpmyadmin'] = tmp; + tmp['setup'] = os.path.exists(vfile) + tmp['status'] = pstatus + tmp['phpversion'] = phpversion.strip() + tmp['port'] = phpport + tmp['auth'] = pauth + data['phpmyadmin'] = tmp tmp = {} - tmp['setup'] = os.path.exists('/etc/init.d/tomcat'); + tmp['setup'] = os.path.exists('/etc/init.d/tomcat') tmp['status'] = tmp['setup'] #if public.ExecShell('ps -aux|grep tomcat|grep -v grep')[0] == "": tmp['status'] = False - tmp['version'] = public.readFile(self.setupPath + '/tomcat/version.pl'); - data['tomcat'] = tmp; + tmp['version'] = public.readFile(self.setupPath + '/tomcat/version.pl') + data['tomcat'] = tmp tmp = {} - tmp['setup'] = os.path.exists(self.setupPath +'/mysql/bin/mysql'); - tmp['version'] = public.readFile(self.setupPath + '/mysql/version.pl'); + tmp['setup'] = os.path.exists(self.setupPath +'/mysql/bin/mysql') + tmp['version'] = public.readFile(self.setupPath + '/mysql/version.pl') tmp['status'] = os.path.exists('/tmp/mysql.sock') data['mysql'] = tmp tmp = {} - tmp['setup'] = os.path.exists(self.setupPath +'/redis/runtest'); - tmp['status'] = os.path.exists('/var/run/redis_6379.pid'); - data['redis'] = tmp; + tmp['setup'] = os.path.exists(self.setupPath +'/redis/runtest') + tmp['status'] = os.path.exists('/var/run/redis_6379.pid') + data['redis'] = tmp tmp = {} - tmp['setup'] = os.path.exists('/usr/local/memcached/bin/memcached'); - tmp['status'] = os.path.exists('/var/run/memcached.pid'); - data['memcached'] = tmp; + tmp['setup'] = os.path.exists('/usr/local/memcached/bin/memcached') + tmp['status'] = os.path.exists('/var/run/memcached.pid') + data['memcached'] = tmp tmp = {} - tmp['setup'] = os.path.exists(self.setupPath +'/pure-ftpd/bin/pure-pw'); - tmp['version'] = public.readFile(self.setupPath + '/pure-ftpd/version.pl'); + tmp['setup'] = os.path.exists(self.setupPath +'/pure-ftpd/bin/pure-pw') + tmp['version'] = public.readFile(self.setupPath + '/pure-ftpd/version.pl') tmp['status'] = os.path.exists('/var/run/pure-ftpd.pid') data['pure-ftpd'] = tmp data['panel'] = self.GetPanelInfo() - data['systemdate'] = public.ExecShell('date +"%Y-%m-%d %H:%M:%S %Z %z"')[0].strip(); + data['systemdate'] = public.format_date("%Y-%m-%d %H:%M:%S %Z %z") #public.ExecShell('date +"%Y-%m-%d %H:%M:%S %Z %z"')[0].strip() return data @@ -176,15 +176,15 @@ class system: try: port = public.GetHost(True) except: - port = '8888'; + port = '8888' domain = '' if os.path.exists('data/domain.conf'): - domain = public.readFile('data/domain.conf'); + domain = public.readFile('data/domain.conf') autoUpdate = '' - if os.path.exists('data/autoUpdate.pl'): autoUpdate = 'checked'; + if os.path.exists('data/autoUpdate.pl'): autoUpdate = 'checked' limitip = '' - if os.path.exists('data/limitip.conf'): limitip = public.readFile('data/limitip.conf'); + if os.path.exists('data/limitip.conf'): limitip = public.readFile('data/limitip.conf') admin_path = '/' if os.path.exists('data/admin_path.pl'): admin_path = public.readFile('data/admin_path.pl').strip() @@ -193,8 +193,8 @@ class system: # if os.path.isdir('templates/' + template): templates.append(template); template = public.GetConfigValue('template') - check502 = ''; - if os.path.exists('data/502Task.pl'): check502 = 'checked'; + check502 = '' + if os.path.exists('data/502Task.pl'): check502 = 'checked' return {'port':port,'address':address,'domain':domain,'auto':autoUpdate,'502':check502,'limitip':limitip,'templates':templates,'template':template,'admin_path':admin_path} def GetPHPConfig(self,version): @@ -373,9 +373,13 @@ class system: def GetMemInfo(self,get=None): #取内存信息 + skey = 'memInfo' + memInfo = cache.get(skey) + if memInfo: return memInfo mem = psutil.virtual_memory() memInfo = {'memTotal':int(mem.total/1024/1024),'memFree':int(mem.free/1024/1024),'memBuffers':int(mem.buffers/1024/1024),'memCached':int(mem.cached/1024/1024)} memInfo['memRealUsed'] = memInfo['memTotal'] - memInfo['memFree'] - memInfo['memBuffers'] - memInfo['memCached'] + cache.set(skey,memInfo,60) return memInfo def GetDiskInfo(self,get=None): @@ -428,7 +432,7 @@ class system: except Exception as ex: public.WriteLog('GET_INFO',str(ex)) continue - cache.set(key,diskInfo,360) + cache.set(key,diskInfo,10) return diskInfo @@ -483,7 +487,6 @@ class system: cache.set(iokey,{'info':diskio_2,'time':mtime}) except: - public.writeFile('/tmp/2',str(public.get_error_info())) return diskInfo return diskInfo @@ -625,8 +628,11 @@ class system: def get_cpu_times(self): - data = {} + skey = 'cpu_times' + data = cache.get(skey) + if data:return data try: + data = {} cpu_times_p = psutil.cpu_times_percent() data['user'] = cpu_times_p.user data['nice'] = cpu_times_p.nice @@ -649,7 +655,8 @@ class system: continue data['total_processes'] += 1 - except: pass + cache.set(skey,data,60) + except: return None return data @@ -921,38 +928,10 @@ class system: #重启面板 def ReWeb(self,get): - #s = time.time() - #if not self.shell: self.connect_ssh() - #self.shell.send("nohup /etc/init.d/bt restart && sleep 1 && /etc/init.d/bt start > /dev/null &\n") - #public.ExecShell("nohup sleep 2 && /etc/init.d/bt restart 2>&1 >/dev/null &") - public.ExecShell("/etc/init.d/bt start") public.writeFile('data/restart.pl','True') return public.returnMsg(True,'PANEL_WAS_RESTART') - def connect_ssh(self): - import paramiko - self.ssh = paramiko.SSHClient() - self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) - try: - self.ssh.connect('127.0.0.1', public.GetSSHPort()) - except: - if public.GetSSHStatus(): - try: - self.ssh.connect('localhost', public.GetSSHPort()) - except: - return False - import firewalls - fw = firewalls.firewalls() - get = public.dict_obj() - get.status = '0' - fw.SetSshStatus(get) - self.ssh.connect('127.0.0.1', public.GetSSHPort()) - get.status = '1' - fw.SetSshStatus(get) - self.shell = self.ssh.invoke_shell(term='xterm', width=100, height=29) - self.shell.setblocking(0) - return True #修复面板 def RepPanel(self,get): @@ -966,10 +945,3 @@ class system: public.ExecShell("wget -O update.sh " + public.get_url() + "/install/update6_en.sh && bash update.sh") self.ReWeb(None) return True - - - - - - - \ No newline at end of file diff --git a/class/userlogin.py b/class/userlogin.py index a44385dd..12cd1c25 100644 --- a/class/userlogin.py +++ b/class/userlogin.py @@ -106,8 +106,7 @@ class userlogin: self.limit_address('-') cache.delete('panelNum') cache.delete('dologin') - sess_input_path = 'data/session_last.pl' - public.writeFile(sess_input_path,str(int(time.time()))) + session['session_timeout'] = time.time() + public.get_session_timeout() del(data['tmp_token']) del(data['tmp_time']) public.writeFile(save_path,json.dumps(data)) @@ -157,8 +156,7 @@ class userlogin: self.limit_address('-') cache.delete('panelNum') cache.delete('dologin') - sess_input_path = 'data/session_last.pl' - public.writeFile(sess_input_path,str(int(time.time()))) + session['session_timeout'] = time.time() + public.get_session_timeout() self.set_request_token() self.login_token() self.set_cdn_host(get) @@ -277,12 +275,12 @@ class userlogin: session['login'] = True session['username'] = userInfo['username'] session['uid'] = userInfo['id'] + session['login_user_agent'] = public.md5(request.headers.get('User-Agent','')) public.WriteLog('TYPE_LOGIN','LOGIN_SUCCESS',(userInfo['username'],public.GetClientIp()+ ":" + str(request.environ.get('REMOTE_PORT')))) self.limit_address('-') cache.delete('panelNum') cache.delete('dologin') - sess_input_path = 'data/session_last.pl' - public.writeFile(sess_input_path,str(int(time.time()))) + session['session_timeout'] = time.time() + public.get_session_timeout() self.set_request_token() self.login_token() login_type = 'data/app_login.pl' diff --git a/class/wxapp.py b/class/wxapp.py index 886248b3..d5e1ddaa 100644 --- a/class/wxapp.py +++ b/class/wxapp.py @@ -58,28 +58,28 @@ class ScanLogin(object): if cache.get(session_id) == 'True': return self.check_app_login(get) - if os.path.exists(self.app_path+"login.pl"): - data = public.readFile(self.app_path+'login.pl') - public.ExecShell('rm ' + self.app_path+"login.pl") - secret_key, init_time = data.split(':') - if time.time() - float(init_time) < 60 and get['secret_key'] == secret_key: - sql = db.Sql() - userInfo = sql.table('users').where( - "id=?", (1,)).field('id,username,password').find() - session['login'] = True - session['username'] = userInfo['username'] - cache.delete('panelNum') - cache.delete('dologin') - public.WriteLog('TYPE_LOGIN', 'LOGIN_SUCCESS', - ('WeChat scan code login', public.GetClientIp()+ ":" + str(request.environ.get('REMOTE_PORT')))) - login_type = 'data/app_login.pl' - self.set_request_token() - import config - config.config().reload_session() - public.writeFile(login_type,'True') - public.login_send_body("Wechat program",userInfo['username'],public.GetClientIp(),str(request.environ.get('REMOTE_PORT'))) - return public.returnMsg(True, 'login successful') - return public.returnMsg(False, 'Login failed') + # if os.path.exists(self.app_path+"login.pl"): + # data = public.readFile(self.app_path+'login.pl') + # public.ExecShell('rm ' + self.app_path+"login.pl") + # secret_key, init_time = data.split(':') + # if time.time() - float(init_time) < 60 and get['secret_key'] == secret_key: + # sql = db.Sql() + # userInfo = sql.table('users').where( + # "id=?", (1,)).field('id,username,password').find() + # session['login'] = True + # session['username'] = userInfo['username'] + # cache.delete('panelNum') + # cache.delete('dologin') + # public.WriteLog('TYPE_LOGIN', 'LOGIN_SUCCESS', + # ('微信扫码登录', public.GetClientIp()+ ":" + str(request.environ.get('REMOTE_PORT')))) + # login_type = 'data/app_login.pl' + # self.set_request_token() + # import config + # config.config().reload_session() + # public.writeFile(login_type,'True') + # public.login_send_body("微信小程序",userInfo['username'],public.GetClientIp(),str(request.environ.get('REMOTE_PORT'))) + # return public.returnMsg(True, '登录成功') + return public.returnMsg(False, '登录失败') #验证APP是否登录成功 @@ -107,8 +107,7 @@ class ScanLogin(object): public.WriteLog('TYPE_LOGIN','APP scan code login, account: {}, login IP: {}'.format(userInfo['username'],public.GetClientIp()+ ":" + str(request.environ.get('REMOTE_PORT')))) cache.delete('panelNum') cache.delete('dologin') - sess_input_path = 'data/session_last.pl' - public.writeFile(sess_input_path,str(int(time.time()))) + session['session_timeout'] = time.time() + public.get_session_timeout() login_type = 'data/app_login.pl' self.set_request_token() import config @@ -208,17 +207,17 @@ class wxapp(SelfModule, ScanLogin): elif get['panel_token'] != password: return public.returnMsg(False, 'SK_NOT_INCORRECT') return True - else: - # 是否在白名单ip sgin 是否正确 - if hasattr(get, 'uid') and hasattr(get, 'sgin') and hasattr(get, 'fun') and get['uid'] in self.user_info.keys(): - encryption_str = self.user_info[get['uid']]['token']+get['fun']+get['uid'] - if sys.version_info[0] == 3: - if type(encryption_str) == str: - encryption_str = encryption_str.encode() - if get['sgin'] == public.md5(binascii.hexlify(base64.b64encode(encryption_str))): - if public.GetClientIp() in ['47.52.194.186']: - return True - return public.returnMsg(False, 'UNAUTHORIZED') + # else: + # # 是否在白名单ip sgin 是否正确 + # if hasattr(get, 'uid') and hasattr(get, 'sgin') and hasattr(get, 'fun') and get['uid'] in self.user_info.keys(): + # encryption_str = self.user_info[get['uid']]['token']+get['fun']+get['uid'] + # if sys.version_info[0] == 3: + # if type(encryption_str) == str: + # encryption_str = encryption_str.encode() + # if get['sgin'] == public.md5(binascii.hexlify(base64.b64encode(encryption_str))): + # if public.GetClientIp() in ['47.52.194.186']: + # return public.returnMsg(False, '未授权') + return public.returnMsg(False, 'UNAUTHORIZED') # 用户绑定 def blind(self, get): diff --git a/install.sh b/install.sh new file mode 100644 index 00000000..4fc17952 --- /dev/null +++ b/install.sh @@ -0,0 +1,790 @@ +#!/bin/bash +PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin +export PATH +LANG=en_US.UTF-8 +cd ~ + +setup_path="/www" +SET_SSL=false +python_bin=$setup_path/server/panel/pyenv/bin/python +cpu_cpunt=$(cat /proc/cpuinfo|grep processor|wc -l) +if [ "$1" ];then + IDC_CODE=$1 +fi + +GetSysInfo(){ + if [ -s "/etc/redhat-release" ];then + SYS_VERSION=$(cat /etc/redhat-release) + elif [ -s "/etc/issue" ]; then + SYS_VERSION=$(cat /etc/issue) + fi + SYS_INFO=$(uname -r) + SYS_BIT=$(getconf LONG_BIT) + MEM_TOTAL=$(free -m|grep Mem|awk '{print $2}') + CPU_INFO=$(getconf _NPROCESSORS_ONLN) + + echo -e ${SYS_VERSION} + echo -e Bit:${SYS_BIT} Mem:${MEM_TOTAL}M Core:${CPU_INFO} + echo -e ${SYS_INFO} + echo -e "Please screenshot the above error message and post to the forum forum.aapanel.com for help" +} +Red_Error(){ + echo '================================================='; + printf '\033[1;31;40m%b\033[0m\n' "$1"; + GetSysInfo + exit 1; +} + +is64bit=$(getconf LONG_BIT) +if [ "${is64bit}" != '64' ];then + Red_Error "Sorry, aaPanel Does not support 32-bit systems, Use 64-bit system Please!"; + +fi +Lock_Clear(){ + if [ -f "/etc/bt_crack.pl" ];then + chattr -R -ia /www + chattr -ia /etc/init.d/bt + \cp -rpa /www/backup/panel/vhost/* /www/server/panel/vhost/ + mv /www/server/panel/BTPanel/__init__.bak /www/server/panel/BTPanel/__init__.py + rm -f /etc/bt_crack.pl + fi +} +Install_Check(){ + while [ "$yes" != 'yes' ] && [ "$yes" != 'n' ] + do + echo -e "----------------------------------------------------" + echo -e "Web service is alreday installed,installing aaPanel may affect existing sites." + echo -e "----------------------------------------------------" + read -p "Enter yes to force installation (yes/n): " yes; + done + if [ "$yes" == 'n' ];then + exit; + fi +} +System_Check(){ + for serviceS in nginx httpd mysqld + do + if [ -f "/etc/init.d/${serviceS}" ]; then + if [ "${serviceS}" = "httpd" ]; then + serviceCheck=$(cat /etc/init.d/${serviceS}|grep /www/server/apache) + elif [ "${serviceS}" = "mysqld" ]; then + serviceCheck=$(cat /etc/init.d/${serviceS}|grep /www/server/mysql) + else + serviceCheck=$(cat /etc/init.d/${serviceS}|grep /www/server/${serviceS}) + fi + [ -z "${serviceCheck}" ] && Install_Check + fi + done +} +Set_Ssl(){ + echo -e "" + echo -e "----------------------------------------------------------------------" + echo -e "If you choose to enable SSL (self-signed certificate), you will use https access panel after installation." + echo -e "After logging in, you can go to the panel settings and change to Let's Encrypt certificate." + echo -e "----------------------------------------------------------------------" + echo -e "" + read -p "Do you need to enable the panel SSl ? (yes/n): " yes; + if [ "$yes" == "yes" ];then + SET_SSL=true + fi + if [ "$yes" != "yes" ] && [ $yes != "n" ];then + Set_Ssl + fi +} +Get_Pack_Manager(){ + if [ -f "/usr/bin/yum" ] && [ -d "/etc/yum.repos.d" ]; then + PM="yum" + elif [ -f "/usr/bin/apt-get" ] && [ -f "/usr/bin/dpkg" ]; then + PM="apt-get" + fi +} + +Auto_Swap() +{ + swap=$(free |grep Swap|awk '{print $2}') + if [ "${swap}" -gt 1 ];then + echo "Swap total sizse: $swap"; + return; + fi + if [ ! -d /www ];then + mkdir /www + fi + swapFile="/www/swap" + dd if=/dev/zero of=$swapFile bs=1M count=1025 + mkswap -f $swapFile + swapon $swapFile + echo "$swapFile swap swap defaults 0 0" >> /etc/fstab + swap=`free |grep Swap|awk '{print $2}'` + if [ $swap -gt 1 ];then + echo "Swap total sizse: $swap"; + return; + fi + + sed -i "/\/www\/swap/d" /etc/fstab + rm -f $swapFile +} +Service_Add(){ + if [ "${PM}" == "yum" ] || [ "${PM}" == "dnf" ]; then + chkconfig --add bt + chkconfig --level 2345 bt on + elif [ "${PM}" == "apt-get" ]; then + update-rc.d bt defaults + fi +} + +get_node_url(){ + if [ ! -f /bin/curl ];then + if [ "${PM}" = "yum" ]; then + yum install curl -y + elif [ "${PM}" = "apt-get" ]; then + apt-get install curl -y + fi + fi + + echo '---------------------------------------------'; + echo "Selected download node..."; + nodes=(http://node.aapanel.com http://128.1.164.196 http://45.76.53.20 http://103.224.251.67 http://dg2.bt.cn http://dg1.bt.cn http://123.129.198.197 http://125.88.182.172:5880 http://119.188.210.21:5880 http://120.206.184.160 http://113.107.111.78); + tmp_file1=/dev/shm/net_test1.pl + tmp_file2=/dev/shm/net_test2.pl + + [ -f "${tmp_file1}" ] && rm -f ${tmp_file1} + + + [ -f "${tmp_file2}" ] && rm -f ${tmp_file2} + + touch $tmp_file1 + touch $tmp_file2 + for node in ${nodes[@]}; + do + NODE_CHECK=$(curl --connect-timeout 3 -m 3 2>/dev/null -w "%{http_code} %{time_total}" ${node}/net_test|xargs) + RES=$(echo ${NODE_CHECK}|awk '{print $1}') + NODE_STATUS=$(echo ${NODE_CHECK}|awk '{print $2}') + TIME_TOTAL=$(echo ${NODE_CHECK}|awk '{print $3 * 1000 - 500 }'|cut -d '.' -f 1) + if [ "${NODE_STATUS}" == "200" ];then + if [ $TIME_TOTAL -lt 100 ];then + if [ $RES -ge 1500 ];then + echo "$RES $node" >> $tmp_file1 + fi + else + if [ $RES -ge 1500 ];then + echo "$TIME_TOTAL $node" >> $tmp_file2 + fi + fi + + i=$(($i+1)) + if [ $TIME_TOTAL -lt 100 ];then + if [ $RES -ge 3000 ];then + break; + fi + fi + + fi + done + + NODE_URL=$(cat $tmp_file1|sort -r -g -t " " -k 1|head -n 1|awk '{print $2}') + if [ -z "$NODE_URL" ];then + NODE_URL=$(cat $tmp_file2|sort -g -t " " -k 1|head -n 1|awk '{print $2}') + if [ -z "$NODE_URL" ];then + NODE_URL='http://download.bt.cn'; + fi + fi + + rm -f $tmp_file1 + rm -f $tmp_file2 + download_Url=$NODE_URL + echo "Download node: $download_Url"; + echo '---------------------------------------------'; +} +Remove_Package(){ + local PackageNmae=$1 + if [ "${PM}" == "yum" ];then + isPackage=$(rpm -q ${PackageNmae}|grep "not installed") + if [ -z "${isPackage}" ];then + yum remove ${PackageNmae} -y + fi + elif [ "${PM}" == "apt-get" ];then + isPackage=$(dpkg -l|grep ${PackageNmae}) + if [ "${PackageNmae}" ];then + apt-get remove ${PackageNmae} -y + fi + fi +} +Install_RPM_Pack(){ + yumPath=/etc/yum.conf + Centos8Check=$(cat /etc/redhat-release | grep ' 8.' | grep -iE 'centos|Red Hat') + isExc=$(cat $yumPath|grep httpd) + if [ "$isExc" = "" ];then + echo "exclude=httpd nginx php mysql mairadb python-psutil python2-psutil" >> $yumPath + fi + + yumBaseUrl=$(cat /etc/yum.repos.d/CentOS-Base.repo|grep baseurl=http|cut -d '=' -f 2|cut -d '$' -f 1|head -n 1) + [ "${yumBaseUrl}" ] && checkYumRepo=$(curl --connect-timeout 5 --head -s -o /dev/null -w %{http_code} ${yumBaseUrl}) + if [ "${checkYumRepo}" != "200" ];then + curl -Ss --connect-timeout 3 -m 60 http://download.bt.cn/install/yumRepo_select.sh|bash + fi + +# 尝试同步时间(从bt.cn) + echo 'Synchronizing system time...' + getBtTime=$(curl -sS --connect-timeout 3 -m 60 http://www.bt.cn/api/index/get_time) + if [ "${getBtTime}" ];then + date -s "$(date -d @$getBtTime +"%Y-%m-%d %H:%M:%S")" + fi + + #if [ -z "${Centos8Check}" ]; then + # yum install ntp -y + # rm -rf /etc/localtime + # ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime + + #尝试同步国际时间(从ntp服务器) + # ntpdate 0.asia.pool.ntp.org + # setenforce 0 + #fi + + startTime=`date +%s` + + sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config + #yum remove -y python-requests python3-requests python-greenlet python3-greenlet + yumPacks="libcurl-devel wget tar gcc make zip unzip openssl openssl-devel gcc libxml2 libxml2-devel libxslt* zlib zlib-devel libjpeg-devel libpng-devel libwebp libwebp-devel freetype freetype-devel lsof pcre pcre-devel vixie-cron crontabs icu libicu-devel c-ares libffi-devel bzip2-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel" + yum install -y ${yumPacks} + + for yumPack in ${yumPacks} + do + rpmPack=$(rpm -q ${yumPack}) + packCheck=$(echo ${rpmPack}|grep not) + if [ "${packCheck}" ]; then + yum install ${yumPack} -y + fi + done + if [ -f "/usr/bin/dnf" ]; then + dnf install -y redhat-rpm-config + fi + + yum install epel-release -y +} +Install_Deb_Pack(){ + ln -sf bash /bin/sh + apt-get update -y + apt-get install ruby -y + apt-get install lsb-release -y + #apt-get install ntp ntpdate -y + #/etc/init.d/ntp stop + #update-rc.d ntp remove + #cat >>~/.profile< /var/spool/cron/crontabs/root + chmod 600 /var/spool/cron/crontabs/root + fi + fi +} +Install_Bt(){ + panelPort="8888" + if [ -f ${setup_path}/server/panel/data/port.pl ];then + panelPort=$(cat ${setup_path}/server/panel/data/port.pl) + fi + mkdir -p ${setup_path}/server/panel/logs + mkdir -p ${setup_path}/server/panel/vhost/apache + mkdir -p ${setup_path}/server/panel/vhost/nginx + mkdir -p ${setup_path}/server/panel/vhost/rewrite + mkdir -p ${setup_path}/server/panel/install + mkdir -p /www/server + mkdir -p /www/wwwroot + mkdir -p /www/wwwlogs + mkdir -p /www/backup/database + mkdir -p /www/backup/site + + if [ ! -f "/usr/bin/unzip" ]; then + if [ "${PM}" = "yum" ]; then + yum install unzip -y + elif [ "${PM}" = "apt-get" ]; then + apt-get install unzip -y + fi + fi + + if [ -f "/etc/init.d/bt" ]; then + /etc/init.d/bt stop + sleep 1 + fi + + wget -O panel.zip ${download_Url}/install/src/panel6_en.zip -T 10 + wget -O /etc/init.d/bt ${download_Url}/install/src/bt6_en.init -T 10 + wget -O /www/server/panel/install/public.sh ${download_Url}/install/public.sh -T 10 + + if [ -f "${setup_path}/server/panel/data/default.db" ];then + if [ -d "/${setup_path}/server/panel/old_data" ];then + rm -rf ${setup_path}/server/panel/old_data + fi + mkdir -p ${setup_path}/server/panel/old_data + mv -f ${setup_path}/server/panel/data/default.db ${setup_path}/server/panel/old_data/default.db + mv -f ${setup_path}/server/panel/data/system.db ${setup_path}/server/panel/old_data/system.db + mv -f ${setup_path}/server/panel/data/port.pl ${setup_path}/server/panel/old_data/port.pl + mv -f ${setup_path}/server/panel/data/admin_path.pl ${setup_path}/server/panel/old_data/admin_path.pl + fi + + unzip -o panel.zip -d ${setup_path}/server/ > /dev/null + + if [ -d "${setup_path}/server/panel/old_data" ];then + mv -f ${setup_path}/server/panel/old_data/default.db ${setup_path}/server/panel/data/default.db + mv -f ${setup_path}/server/panel/old_data/system.db ${setup_path}/server/panel/data/system.db + mv -f ${setup_path}/server/panel/old_data/port.pl ${setup_path}/server/panel/data/port.pl + mv -f ${setup_path}/server/panel/old_data/admin_path.pl ${setup_path}/server/panel/data/admin_path.pl + if [ -d "/${setup_path}/server/panel/old_data" ];then + rm -rf ${setup_path}/server/panel/old_data + fi + fi + + rm -f panel.zip + + if [ ! -f ${setup_path}/server/panel/tools.py ];then + Red_Error "ERROR: Failed to download, please try install again!" + fi + + rm -f ${setup_path}/server/panel/class/*.pyc + rm -f ${setup_path}/server/panel/*.pyc + + chmod +x /etc/init.d/bt + chmod -R 600 ${setup_path}/server/panel + chmod -R +x ${setup_path}/server/panel/script + ln -sf /etc/init.d/bt /usr/bin/bt + echo "${panelPort}" > ${setup_path}/server/panel/data/port.pl + wget -O /etc/init.d/bt ${download_Url}/install/src/bt6_en.init -T 10 + wget -O /www/server/panel/init.sh ${download_Url}/install/src/bt6_en.init -T 10 +} +Install_Python_Lib(){ + #curl -Ss --connect-timeout 3 -m 60 $download_Url/install/pip_select.sh|bash + pyenv_path="/www/server/panel" + if [ -f $pyenv_path/pyenv/bin/python ];then + chmod -R 700 $pyenv_path/pyenv/bin + $pyenv_path/pyenv/bin/pip install cachelib + is_package=$($python_bin -m psutil 2>&1|grep package) + if [ "$is_package" = "" ];then + wget -O $pyenv_path/pyenv/pip.txt $download_Url/install/pyenv/pip.txt -T 5 + $pyenv_path/pyenv/bin/pip install -U pip + $pyenv_path/pyenv/bin/pip install -U setuptools + $pyenv_path/pyenv/bin/pip install -r $pyenv_path/pyenv/pip.txt + $pyenv_path/pyenv/bin/pip install cachelib + fi + source $pyenv_path/pyenv/bin/activate + return + fi + py_version="3.7.8" + mkdir -p $pyenv_path + os_type='el' + os_version='7' + is_export_openssl=0 + Get_Versions + Centos6_Openssl + Other_Openssl + echo "OS: $os_type - $os_version" + is_aarch64=$(uname -a|grep aarch64) + if [ "$is_aarch64" != "" ];then + os_version="aarch64" + fi + if [ "${os_version}" != "" ];then + pyenv_file="/www/pyenv.tar.gz" + wget -O $pyenv_file $download_Url/install/pyenv/pyenv-${os_type}${os_version}-x${is64bit}.tar.gz -T 10 + tmp_size=$(du -b $pyenv_file|awk '{print $1}') + if [ $tmp_size -lt 703460 ];then + rm -f $pyenv_file + echo "ERROR: Download python env fielded." + else + echo "Install python env..." + tar zxvf $pyenv_file -C $pyenv_path/ &> /dev/null + chmod -R 700 $pyenv_path/pyenv/bin + if [ ! -f $pyenv_path/pyenv/bin/python ];then + rm -f $pyenv_file + Red_Error "ERROR: Install python env fielded." + fi + rm -f $pyenv_file + ln -sf $pyenv_path/pyenv/bin/pip3.7 /usr/bin/btpip + ln -sf $pyenv_path/pyenv/bin/python3.7 /usr/bin/btpython + source $pyenv_path/pyenv/bin/activate + return + fi + fi + if [ -f /usr/local/openssl/lib/libssl.so ];then + export LDFLAGS="-L/usr/local/openssl/lib" + export CPPFLAGS="-I/usr/local/openssl/include" + export PKG_CONFIG_PATH="/usr/local/openssl/lib/pkgconfig" + echo "export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/openssl/lib" >> /etc/profile + source /etc/profile + fi + cd /www + python_src='/www/python_src.tar.xz' + python_src_path="/www/Python-${py_version}" + wget -O $python_src $download_Url/src/Python-${py_version}.tar.xz -T 5 + tmp_size=$(du -b $python_src|awk '{print $1}') + if [ $tmp_size -lt 10703460 ];then + rm -f $python_src + Red_Error "ERROR: Download python source code fielded." + fi + tar xvf $python_src + rm -f $python_src + cd $python_src_path + ./configure --prefix=$pyenv_path/pyenv + make -j$cpu_cpunt + make install + if [ ! -f $pyenv_path/pyenv/bin/python3.7 ];then + rm -rf $python_src_path + Red_Error "ERROR: Make python env fielded." + fi + cd ~ + rm -rf $python_src_path + wget -O $pyenv_path/pyenv/bin/activate $download_Url/install/pyenv/activate.panel -T 5 + wget -O $pyenv_path/pyenv/pip.txt $download_Url/install/pyenv/pip-3.7.8.txt -T 5 + ln -sf $pyenv_path/pyenv/bin/pip3.7 $pyenv_path/pyenv/bin/pip + ln -sf $pyenv_path/pyenv/bin/python3.7 $pyenv_path/pyenv/bin/python + ln -sf $pyenv_path/pyenv/bin/pip3.7 /usr/bin/btpip + ln -sf $pyenv_path/pyenv/bin/python3.7 /usr/bin/btpython + chmod -R 700 $pyenv_path/pyenv/bin + $pyenv_path/pyenv/bin/pip install -U pip + $pyenv_path/pyenv/bin/pip install -U setuptools + $pyenv_path/pyenv/bin/pip install -U wheel==0.34.2 + $pyenv_path/pyenv/bin/pip install -r $pyenv_path/pyenv/pip.txt + $pyenv_path/pyenv/bin/pip install -U cachelib + source $pyenv_path/pyenv/bin/activate +} + +Other_Openssl(){ + openssl_version=$(openssl version|grep -Eo '[0-9]\.[0-9]\.[0-9]') + if [ "$openssl_version" = '1.0.1' ] || [ "$openssl_version" = '1.0.0' ];then + opensslVersion="1.0.2r" + if [ ! -f "/usr/local/openssl/lib/libssl.so" ];then + cd /www + openssl_src_file=/www/openssl.tar.gz + wget -O $openssl_src_file ${download_Url}/src/openssl-${opensslVersion}.tar.gz + tmp_size=$(du -b $openssl_src_file|awk '{print $1}') + if [ $tmp_size -lt 703460 ];then + rm -f $openssl_src_file + Red_Error "ERROR: Download openssl-1.0.2 source code fielded." + fi + tar -zxf $openssl_src_file + rm -f $openssl_src_file + cd openssl-${opensslVersion} + #zlib-dynamic shared + ./config --openssldir=/usr/local/openssl zlib-dynamic shared + make -j${cpuCore} + make install + echo "/usr/local/openssl/lib" > /etc/ld.so.conf.d/zopenssl.conf + ldconfig + cd .. + rm -rf openssl-${opensslVersion} + is_export_openssl=1 + cd ~ + fi + fi +} + +Insatll_Libressl(){ + openssl_version=$(openssl version|grep -Eo '[0-9]\.[0-9]\.[0-9]') + if [ "$openssl_version" = '1.0.1' ] || [ "$openssl_version" = '1.0.0' ];then + opensslVersion="3.0.2" + cd /www + openssl_src_file=/www/openssl.tar.gz + wget -O $openssl_src_file ${download_Url}/install/pyenv/libressl-${opensslVersion}.tar.gz + tmp_size=$(du -b $openssl_src_file|awk '{print $1}') + if [ $tmp_size -lt 703460 ];then + rm -f $openssl_src_file + Red_Error "ERROR: Download libressl-$opensslVersion source code fielded." + fi + tar -zxf $openssl_src_file + rm -f $openssl_src_file + cd libressl-${opensslVersion} + ./config –prefix=/usr/local/lib + make -j${cpuCore} + make install + ldconfig + ldconfig -v + cd .. + rm -rf libressl-${opensslVersion} + is_export_openssl=1 + cd ~ + fi +} + +Centos6_Openssl(){ + if [ "$os_type" != 'el' ];then + return + fi + if [ "$os_version" != '6' ];then + return + fi + echo 'Centos6 install openssl-1.0.2...' + openssl_rpm_file="/www/openssl.rpm" + wget -O $openssl_rpm_file $download_Url/rpm/centos6/${is64bit}/bt-openssl102.rpm -T 10 + tmp_size=$(du -b $openssl_rpm_file|awk '{print $1}') + if [ $tmp_size -lt 102400 ];then + rm -f $openssl_rpm_file + Red_Error "ERROR: Download python env fielded." + fi + rpm -ivh $openssl_rpm_file + rm -f $openssl_rpm_file + is_export_openssl=1 +} + +Get_Versions(){ + redhat_version_file="/etc/redhat-release" + deb_version_file="/etc/issue" + if [ -f $redhat_version_file ];then + os_type='el' + is_aliyunos=$(cat $redhat_version_file|grep Aliyun) + if [ "$is_aliyunos" != "" ];then + return + fi + os_version=$(cat $redhat_version_file|grep CentOS|grep -Eo '([0-9]+\.)+[0-9]+'|grep -Eo '^[0-9]') + if [ "${os_version}" = "5" ];then + os_version="" + fi + else + os_type='ubuntu' + os_version=$(cat $deb_version_file|grep Ubuntu|grep -Eo '([0-9]+\.)+[0-9]+'|grep -Eo '^[0-9]+') + if [ "${os_version}" = "" ];then + os_type='debian' + os_version=$(cat $deb_version_file|grep Debian|grep -Eo '([0-9]+\.)+[0-9]+'|grep -Eo '[0-9]+') + if [ "${os_version}" = "" ];then + os_version=$(cat $deb_version_file|grep Debian|grep -Eo '[0-9]+') + fi + if [ "${os_version}" = "8" ];then + os_version="" + fi + if [ "${is64bit}" = '32' ];then + os_version="" + fi + else + if [ "$os_version" = "14" ];then + os_version="" + fi + if [ "$os_version" = "12" ];then + os_version="" + fi + if [ "$os_version" = "19" ];then + os_version="" + fi + fi + fi +} + +Set_Bt_Panel(){ + chmod -R 700 /www/server/panel/pyenv/bin + /www/server/panel/pyenv/bin/pip install cachelib + password=$(cat /dev/urandom | head -n 16 | md5sum | head -c 8) + sleep 1 + admin_auth="/www/server/panel/data/admin_path.pl" + if [ ! -f ${admin_auth} ];then + auth_path=$(cat /dev/urandom | head -n 16 | md5sum | head -c 8) + echo "/${auth_path}" > ${admin_auth} + fi + auth_path=$(cat ${admin_auth}) + cd ${setup_path}/server/panel/ + if [ "$SET_SSL" == true ];then + pip install -I pyOpenSSl + python /www/server/panel/tools.py ssl + fi + /etc/init.d/bt start + $python_bin -m py_compile tools.py + $python_bin tools.py username + username=$($python_bin tools.py panel ${password}) + cd ~ + echo "${password}" > ${setup_path}/server/panel/default.pl + chmod 600 ${setup_path}/server/panel/default.pl + sleep 3 + /etc/init.d/bt restart + sleep 3 + isStart=$(ps aux |grep 'BT-Panel'|grep -v grep|awk '{print $2}') + LOCAL_CURL=$(curl 127.0.0.1:8888/login 2>&1 |grep -i html) + if [ -z "${isStart}" ] && [ -z "${LOCAL_CURL}" ];then + /etc/init.d/bt 22 + Red_Error "ERROR: The BT-Panel service startup failed." + fi +} +Set_Firewall(){ + sshPort=$(cat /etc/ssh/sshd_config | grep 'Port '|awk '{print $2}') + if [ "${PM}" = "apt-get" ]; then + apt-get install -y ufw + if [ -f "/usr/sbin/ufw" ];then + ufw allow 888/tcp + ufw allow 20/tcp + ufw allow 21/tcp + ufw allow 22/tcp + ufw allow 80/tcp + ufw allow ${panelPort}/tcp + ufw allow ${sshPort}/tcp ufw allow 39000:40000/tcp + + ufw_status=`ufw status` + echo y|ufw enable + ufw default deny + ufw reload + fi + else + if [ -f "/etc/init.d/iptables" ];then + iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport 20 -j ACCEPT + iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport 21 -j ACCEPT + iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT + iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT + iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport ${panelPort} -j ACCEPT + iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport ${sshPort} -j ACCEPT + iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport 39000:40000 -j ACCEPT + #iptables -I INPUT -p tcp -m state --state NEW -m udp --dport 39000:40000 -j ACCEPT + iptables -A INPUT -p icmp --icmp-type any -j ACCEPT + iptables -A INPUT -s localhost -d localhost -j ACCEPT + iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT + iptables -P INPUT DROP + service iptables save + sed -i "s#IPTABLES_MODULES=\"\"#IPTABLES_MODULES=\"ip_conntrack_netbios_ns ip_conntrack_ftp ip_nat_ftp\"#" /etc/sysconfig/iptables-config + iptables_status=$(service iptables status | grep 'not running') + if [ "${iptables_status}" == '' ];then + service iptables restart + fi + else + AliyunCheck=$(cat /etc/redhat-release|grep "Aliyun Linux") + [ "${AliyunCheck}" ] && return + yum install firewalld -y + [ "${Centos8Check}" ] && yum reinstall python3-six -y + systemctl enable firewalld + systemctl start firewalld + firewall-cmd --set-default-zone=public > /dev/null 2>&1 + firewall-cmd --permanent --zone=public --add-port=20/tcp > /dev/null 2>&1 + firewall-cmd --permanent --zone=public --add-port=21/tcp > /dev/null 2>&1 + firewall-cmd --permanent --zone=public --add-port=22/tcp > /dev/null 2>&1 + firewall-cmd --permanent --zone=public --add-port=80/tcp > /dev/null 2>&1 + firewall-cmd --permanent --zone=public --add-port=${panelPort}/tcp > /dev/null 2>&1 + firewall-cmd --permanent --zone=public --add-port=${sshPort}/tcp > /dev/null 2>&1 + firewall-cmd --permanent --zone=public --add-port=39000-40000/tcp > /dev/null 2>&1 + #firewall-cmd --permanent --zone=public --add-port=39000-40000/udp > /dev/null 2>&1 + firewall-cmd --reload + fi + fi +} +Get_Ip_Address(){ + getIpAddress="" +# getIpAddress=$(curl -sS --connect-timeout 10 -m 60 https://brandnew.aapanel.com/api/common/getClientIP) + getIpAddress=$(curl -sS --connect-timeout 10 -m 60 https://www.bt.cn/Api/getIpAddress) + if [ -z "${getIpAddress}" ] || [ "${getIpAddress}" = "0.0.0.0" ]; then + isHosts=$(cat /etc/hosts|grep 'www.bt.cn') + if [ -z "${isHosts}" ];then + echo "" >> /etc/hosts + echo "103.224.251.67 www.bt.cn" >> /etc/hosts + #getIpAddress=$(curl -sS --connect-timeout 10 -m 60 https://brandnew.aapanel.com/api/common/getClientIP) + getIpAddress=$(curl -sS --connect-timeout 10 -m 60 https://www.bt.cn/Api/getIpAddress) + if [ -z "${getIpAddress}" ];then + sed -i "/bt.cn/d" /etc/hosts + fi + fi + fi + + ipv4Check=$($python_bin -c "import re; print(re.match('^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$','${getIpAddress}'))") + if [ "${ipv4Check}" == "None" ];then + ipv6Address=$(echo ${getIpAddress}|tr -d "[]") + ipv6Check=$($python_bin -c "import re; print(re.match('^([0-9a-fA-F]{0,4}:){1,7}[0-9a-fA-F]{0,4}$','${ipv6Address}'))") + if [ "${ipv6Check}" == "None" ]; then + getIpAddress="SERVER_IP" + else + echo "True" > ${setup_path}/server/panel/data/ipv6.pl + sleep 1 + /etc/init.d/bt restart + fi + fi + + if [ "${getIpAddress}" != "SERVER_IP" ];then + echo "${getIpAddress}" > ${setup_path}/server/panel/data/iplist.txt + fi +} +Setup_Count(){ + curl -sS --connect-timeout 10 -m 60 https://brandnew.aapanel.com/api/setupCount/setupPanel?type=Linux > /dev/null 2>&1 + #curl -sS --connect-timeout 10 -m 60 https://www.aapanel.com/Api/SetupCount?type=Linux > /dev/null 2>&1 + curl -sS --connect-timeout 10 -m 60 https://console.aapanel.com/Api/SetupCount?type=Linux > /dev/null 2>&1 + #if [ "$1" != "" ];then + echo "66959f96" > /www/server/panel/data/o.pl + cd /www/server/panel + $python_bin tools.py o + #fi + echo /www > /var/bt_setupPath.conf +} + +Install_Main(){ + setenforce 0 + startTime=`date +%s` + Lock_Clear + System_Check + #Set_Ssl + Get_Pack_Manager + get_node_url + + MEM_TOTAL=$(free -g|grep Mem|awk '{print $2}') + if [ "${MEM_TOTAL}" -le "1" ];then + Auto_Swap + fi + + + if [ "${PM}" = "yum" ]; then + Install_RPM_Pack + elif [ "${PM}" = "apt-get" ]; then + Install_Deb_Pack + fi + + Install_Python_Lib + Install_Bt + + Set_Bt_Panel + Service_Add + Set_Firewall + + Get_Ip_Address + Setup_Count ${IDC_CODE} +} + +echo " ++---------------------------------------------------------------------- +| aaPanel 6.0 FOR CentOS/Ubuntu/Debian ++---------------------------------------------------------------------- +| Copyright © 2015-2099 BT-SOFT(http://www.aapanel.com) All rights reserved. ++---------------------------------------------------------------------- +| The WebPanel URL will be http://SERVER_IP:8888 when installed. ++---------------------------------------------------------------------- +" + +while [ "$go" != 'y' ] && [ "$go" != 'n' ] +do + read -p "Do you want to install aaPanel to the $setup_path directory now?(y/n): " go; +done + +if [ "$go" == 'n' ];then + exit; +fi + +Install_Main +intenal_ip=$(ip addr | grep -E -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | grep -E -v "^127\.|^255\.|^0\." | head -n 1) +echo -e "==================================================================" +echo -e "\033[32mCongratulations! Installed successfully!\033[0m" +echo -e "==================================================================" +if [ "$SET_SSL" == true ];then + echo "aaPanel Internet Address: https://${getIpAddress}:${panelPort}$auth_path" + echo "aaPanel Internal Address: https://${intenal_ip}:${panelPort}$auth_path" +else + echo "aaPanel Internet Address: http://${getIpAddress}:${panelPort}$auth_path" + echo "aaPanel Internal Address: http://${intenal_ip}:${panelPort}$auth_path" +fi +echo -e "username: $username" +echo -e "password: $password" +echo -e "\033[33mWarning:\033[0m" +echo -e "\033[33mIf you cannot access the panel, \033[0m" +echo -e "\033[33mrelease the following port (8888|888|80|443|20|21) in the security group\033[0m" +echo -e "==================================================================" + +endTime=`date +%s` +((outTime=($endTime-$startTime)/60)) +echo -e "Time consumed:\033[32m $outTime \033[0mMinute!" +rm -f new_install_en.sh + + diff --git a/task.py b/task.py index d57cc788..20cc843e 100644 --- a/task.py +++ b/task.py @@ -94,14 +94,14 @@ def WriteLogs(logMsg): pass -def ExecShell(cmdstring, cwd=None, timeout=None, shell=True): +def ExecShell(cmdstring, cwd=None, timeout=None, shell=True, symbol = '&>'): try: global logPath import shlex import datetime import subprocess import time - sub = subprocess.Popen(cmdstring+' &> '+logPath, cwd=cwd, + sub = subprocess.Popen(cmdstring+ symbol +logPath, cwd=cwd, stdin=subprocess.PIPE, shell=shell, bufsize=4096) while sub.poll() is None: @@ -135,6 +135,7 @@ def startTask(): DownloadFile(argv[0], argv[1]) elif value['type'] == 'execshell': ExecShell(value['execstr']) + ExecShell("echo '|-Successify ---Script execution completed---'",symbol=">>") end = int(time.time()) sql.table('tasks').where("id=?", (value['id'],)).save( 'status,end', ('1', end)) @@ -603,11 +604,11 @@ def check_files_panel(): # 面板消息提醒 -def check_panel_msg(): - python_bin = get_python_bin() - while True: - os.system('{} {}/script/check_msg.py &'.format(python_bin,base_path)) - time.sleep(600) +# def check_panel_msg(): +# python_bin = get_python_bin() +# while True: +# os.system('{} {}/script/check_msg.py &'.format(python_bin,base_path)) +# time.sleep(600) def main(): @@ -658,9 +659,9 @@ def main(): p.setDaemon(True) p.start() - p = threading.Thread(target=check_files_panel) - p.setDaemon(True) - p.start() + # p = threading.Thread(target=check_files_panel) + # p.setDaemon(True) + # p.start() import panelTask task_obj = panelTask.bt_task() task_obj.not_web = True @@ -668,9 +669,9 @@ def main(): p.setDaemon(True) p.start() - p = threading.Thread(target=check_panel_msg) - p.setDaemon(True) - p.start() + # p = threading.Thread(target=check_panel_msg) + # p.setDaemon(True) + # p.start() startTask() diff --git a/tools.py b/tools.py index 6970bc11..d03349d8 100644 --- a/tools.py +++ b/tools.py @@ -275,7 +275,7 @@ def ClearMail(): total += size; count += num; print('=======================================================================') - print("CLEAR_RUBBISH2",(str(count),ToSize(total))) + print(public.GetMsg('CLEAR_RUBBISH2',(str(count),ToSize(total)))) return total,count #清理php_session文件