From b92be80c3602a374c3d6fd3fabda4927d73af673 Mon Sep 17 00:00:00 2001 From: Mr Chen Date: Fri, 26 Oct 2018 16:53:20 +0800 Subject: [PATCH] u --- class/db.py | 280 ++++--- class/page.py | 269 ++++--- class/public.py | 56 +- class/system.py | 932 ++++++++++++----------- plugins/nginx/info.json | 1 - static/js/files.js | 1609 +++++++++++++++++++++++++++++++++++++++ task.py | 2 + 7 files changed, 2401 insertions(+), 748 deletions(-) create mode 100755 static/js/files.js diff --git a/class/db.py b/class/db.py index 05dda89ea..e15339ca1 100755 --- a/class/db.py +++ b/class/db.py @@ -1,91 +1,82 @@ -#coding: utf-8 -# +------------------------------------------------------------------- -# | 宝塔Linux面板 -# +------------------------------------------------------------------- -# | Copyright (c) 2015-2016 宝塔软件(http://bt.cn) All rights reserved. -# +------------------------------------------------------------------- -# | Author: 黄文良 <287962566@qq.com> -# +------------------------------------------------------------------- +# coding: utf-8 + import sqlite3 import os + class Sql(): #------------------------------ # 数据库操作类 For sqlite3 #------------------------------ - __DB_FILE = None # 数据库文件 - __DB_CONN = None # 数据库连接对象 - __DB_TABLE = "" # 被操作的表名称 - __OPT_WHERE = "" # where条件 - __OPT_LIMIT = "" # limit条件 - __OPT_ORDER = "" # order条件 - __OPT_FIELD = "*" # field条件 - __OPT_PARAM = () # where值 - + __DB_FILE = None # 数据库文件 + __DB_CONN = None # 数据库连接对象 + __DB_TABLE = "" # 被操作的表名称 + __OPT_WHERE = "" # where条件 + __OPT_LIMIT = "" # limit条件 + __OPT_ORDER = "" # order条件 + __OPT_FIELD = "*" # field条件 + __OPT_PARAM = () # where值 + def __init__(self): self.__DB_FILE = 'data/default.db' - - def __GetConn(self): - #取数据库对象 + + def __GetConn(self): + # 取数据库对象 try: if self.__DB_CONN == None: self.__DB_CONN = sqlite3.connect(self.__DB_FILE) - except Exception,ex: + except Exception, ex: return "error: " + str(ex) - - def dbfile(self,name): + + def dbfile(self, name): self.__DB_FILE = 'data/' + name + '.db' return self - - def table(self,table): - #设置表名 + + def table(self, table): + # 设置表名 self.__DB_TABLE = table return self - - - def where(self,where,param): - #WHERE条件 + + def where(self, where, param): + # WHERE条件 if where: self.__OPT_WHERE = " WHERE " + where self.__OPT_PARAM = param return self - - - def order(self,order): - #ORDER条件 + + def order(self, order): + # ORDER条件 if len(order): - self.__OPT_ORDER = " ORDER BY "+order + self.__OPT_ORDER = " ORDER BY " + order return self - - - def limit(self,limit): - #LIMIT条件 + + def limit(self, limit): + # LIMIT条件 if len(limit): - self.__OPT_LIMIT = " LIMIT "+limit + self.__OPT_LIMIT = " LIMIT " + limit return self - - - def field(self,field): - #FIELD条件 + + def field(self, field): + # FIELD条件 if len(field): self.__OPT_FIELD = field return self - - + def select(self): - #查询数据集 + # 查询数据集 self.__GetConn() try: - sql = "SELECT " + self.__OPT_FIELD + " FROM " + self.__DB_TABLE + self.__OPT_WHERE + self.__OPT_ORDER + self.__OPT_LIMIT - result = self.__DB_CONN.execute(sql,self.__OPT_PARAM) + sql = "SELECT " + self.__OPT_FIELD + " FROM " + self.__DB_TABLE + \ + self.__OPT_WHERE + self.__OPT_ORDER + self.__OPT_LIMIT + result = self.__DB_CONN.execute(sql, self.__OPT_PARAM) data = result.fetchall() - #构造字曲系列 + # 构造字曲系列 if self.__OPT_FIELD != "*": field = self.__OPT_FIELD.split(',') tmp = [] for row in data: - i=0 + i = 0 tmp1 = {} for key in field: tmp1[key] = row[i] @@ -95,196 +86,191 @@ class Sql(): data = tmp del(tmp) else: - #将元组转换成列表 - tmp = map(list,data) + # 将元组转换成列表 + tmp = map(list, data) data = tmp del(tmp) self.__close() return data - except Exception,ex: + except Exception, ex: return "error: " + str(ex) - - - def getField(self,keyName): - #取回指定字段 - result = self.field(keyName).select(); + + def getField(self, keyName): + # 取回指定字段 + result = self.field(keyName).select() if len(result) == 1: return result[0][keyName] return result - - - def setField(self,keyName,keyValue): - #更新指定字段 - return self.save(keyName,(keyValue,)) - - + + def setField(self, keyName, keyValue): + # 更新指定字段 + return self.save(keyName, (keyValue,)) + def find(self): - #取一行数据 + # 取一行数据 result = self.limit("1").select() if len(result) == 1: return result[0] return result - - + def count(self): - #取行数 - key="COUNT(*)" + # 取行数 + key = "COUNT(*)" data = self.field(key).select() try: return int(data[0][key]) except: return 0 - - - def add(self,keys,param): - #插入数据 + + def add(self, keys, param): + # 插入数据 self.__GetConn() self.__DB_CONN.text_factory = str try: - values="" + values = "" for key in keys.split(','): values += "?," - values = self.checkInput(values[0:len(values)-1]); - sql = "INSERT INTO "+self.__DB_TABLE+"("+keys+") "+"VALUES("+values+")" - result = self.__DB_CONN.execute(sql,param) + values = self.checkInput(values[0:len(values) - 1]) + sql = "INSERT INTO " + self.__DB_TABLE + \ + "(" + keys + ") " + "VALUES(" + values + ")" + result = self.__DB_CONN.execute(sql, param) id = result.lastrowid self.__close() self.__DB_CONN.commit() return id - except Exception,ex: + except Exception, ex: return "error: " + str(ex) - - def checkInput(self,data): - if not data: return data; - if type(data) != str: return data; - checkList = [ - {'d':'<','r':'<'}, - {'d':'>','r':'>'}, - {'d':'\'','r':'‘'}, - {'d':'"','r':'“'}, - {'d':'&','r':'&'}, - {'d':'#','r':'#'}, - {'d':'<','r':'<'} - ] - for v in checkList: - data = data.replace(v['d'],v['r']); - return data; - - def addAll(self,keys,param): - #插入数据 + + def checkInput(self, data): + if not data: + return data + if type(data) != str: + return data + checkList = [ + {'d': '<', 'r': '<'}, + {'d': '>', 'r': '>'}, + {'d': '\'', 'r': '‘'}, + {'d': '"', 'r': '“'}, + {'d': '&', 'r': '&'}, + {'d': '#', 'r': '#'}, + {'d': '<', 'r': '<'} + ] + for v in checkList: + data = data.replace(v['d'], v['r']) + return data + + def addAll(self, keys, param): + # 插入数据 self.__GetConn() self.__DB_CONN.text_factory = str try: - values="" + values = "" for key in keys.split(','): values += "?," - values = values[0:len(values)-1] - sql = "INSERT INTO "+self.__DB_TABLE+"("+keys+") "+"VALUES("+values+")" - result = self.__DB_CONN.execute(sql,param) + values = values[0:len(values) - 1] + sql = "INSERT INTO " + self.__DB_TABLE + \ + "(" + keys + ") " + "VALUES(" + values + ")" + result = self.__DB_CONN.execute(sql, param) return True - except Exception,ex: + except Exception, ex: return "error: " + str(ex) - + def commit(self): self.__close() self.__DB_CONN.commit() - - - def save(self,keys,param): - #更新数据 + + def save(self, keys, param): + # 更新数据 self.__GetConn() self.__DB_CONN.text_factory = str try: opt = "" for key in keys.split(','): opt += key + "=?," - opt = opt[0:len(opt)-1] - sql = "UPDATE " + self.__DB_TABLE + " SET " + opt+self.__OPT_WHERE - + opt = opt[0:len(opt) - 1] + sql = "UPDATE " + self.__DB_TABLE + " SET " + opt + self.__OPT_WHERE + import public - public.writeFile('/tmp/test.pl',sql) - - #处理拼接WHERE与UPDATE参数 + public.writeFile('/tmp/test.pl', sql) + + # 处理拼接WHERE与UPDATE参数 tmp = list(param) for arg in self.__OPT_PARAM: tmp.append(arg) self.__OPT_PARAM = tuple(tmp) - result = self.__DB_CONN.execute(sql,self.__OPT_PARAM) + result = self.__DB_CONN.execute(sql, self.__OPT_PARAM) self.__close() self.__DB_CONN.commit() return result.rowcount - except Exception,ex: + except Exception, ex: return "error: " + str(ex) - - def delete(self,id=None): - #删除数据 + + def delete(self, id=None): + # 删除数据 self.__GetConn() try: if id: self.__OPT_WHERE = " WHERE id=?" self.__OPT_PARAM = (id,) sql = "DELETE FROM " + self.__DB_TABLE + self.__OPT_WHERE - result = self.__DB_CONN.execute(sql,self.__OPT_PARAM) + result = self.__DB_CONN.execute(sql, self.__OPT_PARAM) self.__close() self.__DB_CONN.commit() return result.rowcount - except Exception,ex: + except Exception, ex: return "error: " + str(ex) - - - def execute(self,sql,param): - #执行SQL语句返回受影响行 + + def execute(self, sql, param): + # 执行SQL语句返回受影响行 self.__GetConn() try: - result = self.__DB_CONN.execute(sql,param) + result = self.__DB_CONN.execute(sql, param) self.__DB_CONN.commit() return result.rowcount - except Exception,ex: + except Exception, ex: return "error: " + str(ex) - - - def query(self,sql,param): - #执行SQL语句返回数据集 + + def query(self, sql, param): + # 执行SQL语句返回数据集 self.__GetConn() try: - result = self.__DB_CONN.execute(sql,param) - #将元组转换成列表 - data = map(list,result) + result = self.__DB_CONN.execute(sql, param) + # 将元组转换成列表 + data = map(list, result) return data - except Exception,ex: + except Exception, ex: return "error: " + str(ex) - - def create(self,name): - #创建数据表 + + def create(self, name): + # 创建数据表 self.__GetConn() import public script = public.readFile('data/' + name + '.sql') result = self.__DB_CONN.executescript(script) self.__DB_CONN.commit() return result.rowcount - - def fofile(self,filename): - #执行脚本 + + def fofile(self, filename): + # 执行脚本 self.__GetConn() import public script = public.readFile(filename) result = self.__DB_CONN.executescript(script) self.__DB_CONN.commit() return result.rowcount - + def __close(self): - #清理条件属性 + # 清理条件属性 self.__OPT_WHERE = "" self.__OPT_FIELD = "*" self.__OPT_ORDER = "" self.__OPT_LIMIT = "" self.__OPT_PARAM = () - + def close(self): - #释放资源 + # 释放资源 try: self.__DB_CONN.close() self.__DB_CONN = None except: pass - diff --git a/class/page.py b/class/page.py index ded36592a..d4bd24945 100755 --- a/class/page.py +++ b/class/page.py @@ -1,207 +1,222 @@ -#coding: utf-8 -# +------------------------------------------------------------------- -# | 宝塔Linux面板 -# +------------------------------------------------------------------- -# | Copyright (c) 2015-2016 宝塔软件(http://bt.cn) All rights reserved. -# +------------------------------------------------------------------- -# | Author: 黄文良 <2879625666@qq.com> -# +------------------------------------------------------------------- -import math,string,public +# coding: utf-8 + +import math +import string +import public + class Page(): #-------------------------- # 分页类 - JS回调版 #-------------------------- - __PREV = '上一页' - __NEXT = '下一页' - __START = '首页' - __END = '尾页' - __COUNT_START = '共' - __COUNT_END = '条数据' - __FO = '从' - __LINE = '条' - __LIST_NUM = 4 - SHIFT = None #偏移量 - ROW = None #每页行数 - __C_PAGE = None #当前页 - __COUNT_PAGE = None #总页数 - __COUNT_ROW = None #总行数 - __URI = None #URI - __RTURN_JS = False #是否返回JS回调 - __START_NUM = None #起始行 - __END_NUM = None #结束行 - + __PREV = '上一页' + __NEXT = '下一页' + __START = '首页' + __END = '尾页' + __COUNT_START = '共' + __COUNT_END = '条数据' + __FO = '从' + __LINE = '条' + __LIST_NUM = 4 + SHIFT = None # 偏移量 + ROW = None # 每页行数 + __C_PAGE = None # 当前页 + __COUNT_PAGE = None # 总页数 + __COUNT_ROW = None # 总行数 + __URI = None # URI + __RTURN_JS = False # 是否返回JS回调 + __START_NUM = None # 起始行 + __END_NUM = None # 结束行 + def __init__(self): - tmp = public.getMsg('PAGE'); + tmp = public.getMsg('PAGE') if tmp: - self.__PREV = tmp['PREV']; - self.__NEXT = tmp['NEXT']; - self.__START = tmp['START']; - self.__END = tmp['END']; - self.__COUNT_START = tmp['COUNT_START']; - self.__COUNT_END = tmp['COUNT_END']; - self.__FO = tmp['FO']; - self.__LINE = tmp['LINE']; - - def GetPage(self,pageInfo,limit = '1,2,3,4,5,6,7,8'): + self.__PREV = tmp['PREV'] + self.__NEXT = tmp['NEXT'] + self.__START = tmp['START'] + self.__END = tmp['END'] + self.__COUNT_START = tmp['COUNT_START'] + self.__COUNT_END = tmp['COUNT_END'] + self.__FO = tmp['FO'] + self.__LINE = tmp['LINE'] + + def GetPage(self, pageInfo, limit='1,2,3,4,5,6,7,8'): # 取分页信息 # @param pageInfo 传入分页参数字典 # @param limit 返回系列 - self.__RTURN_JS = pageInfo['return_js'] - self.__COUNT_ROW = pageInfo['count'] - self.ROW = pageInfo['row'] - self.__C_PAGE = self.__GetCpage(pageInfo['p']) - self.__START_NUM = self.__StartRow() - self.__END_NUM = self.__EndRow() - self.__COUNT_PAGE = self.__GetCountPage() - self.__URI = self.__SetUri(pageInfo['uri']) - self.SHIFT = self.__START_NUM - 1 - + self.__RTURN_JS = pageInfo['return_js'] + self.__COUNT_ROW = pageInfo['count'] + self.ROW = pageInfo['row'] + self.__C_PAGE = self.__GetCpage(pageInfo['p']) + self.__START_NUM = self.__StartRow() + self.__END_NUM = self.__EndRow() + self.__COUNT_PAGE = self.__GetCountPage() + self.__URI = self.__SetUri(pageInfo['uri']) + self.SHIFT = self.__START_NUM - 1 + keys = limit.split(',') - + pages = {} - #起始页 + # 起始页 pages['1'] = self.__GetStart() - #上一页 + # 上一页 pages['2'] = self.__GetPrev() - #分页 + # 分页 pages['3'] = self.__GetPages() - #下一页 + # 下一页 pages['4'] = self.__GetNext() - #尾页 + # 尾页 pages['5'] = self.__GetEnd() - - #当前显示页与总页数 - pages['6'] = "" + bytes(self.__C_PAGE) + "/" + bytes(self.__COUNT_PAGE) + "" - #本页显示开始与结束行 - pages['7'] = "" + self.__FO + bytes(self.__START_NUM) + "-" + bytes(self.__END_NUM) + self.__LINE + "" - #行数 - pages['8'] = "" + self.__COUNT_START + bytes(self.__COUNT_ROW) + self.__COUNT_END + "" - - #构造返回数据 - retuls = '
'; + + # 当前显示页与总页数 + pages['6'] = "" + \ + bytes(self.__C_PAGE) + "/" + bytes(self.__COUNT_PAGE) + "" + # 本页显示开始与结束行 + pages['7'] = "" + self.__FO + \ + bytes(self.__START_NUM) + "-" + \ + bytes(self.__END_NUM) + self.__LINE + "" + # 行数 + pages['8'] = "" + self.__COUNT_START + \ + bytes(self.__COUNT_ROW) + self.__COUNT_END + "" + + # 构造返回数据 + retuls = '
' for value in keys: retuls += pages[value] - retuls +='
'; - - #返回分页数据 - return retuls; - + retuls += '
' + + # 返回分页数据 + return retuls + def __GetEnd(self): - #构造尾页 + # 构造尾页 endStr = "" if self.__C_PAGE >= self.__COUNT_PAGE: - endStr = ''; + endStr = '' else: if self.__RTURN_JS == "": - endStr = "" + self.__END + "" + endStr = "" + self.__END + "" else: - endStr = "" + self.__END + "" + endStr = "" + self.__END + "" return endStr - + def __GetNext(self): - #构造下一页 + # 构造下一页 nextStr = "" if self.__C_PAGE >= self.__COUNT_PAGE: - nextStr = ''; + nextStr = '' else: if self.__RTURN_JS == "": - nextStr = "" + self.__NEXT + "" - else: - nextStr = "" + self.__NEXT + "" - + nextStr = "" + self.__NEXT + "" + else: + nextStr = "" + self.__NEXT + "" + return nextStr - + def __GetPages(self): - #构造分页 + # 构造分页 pages = '' - num = 0 - #当前页之前 + num = 0 + # 当前页之前 if (self.__COUNT_PAGE - self.__C_PAGE) < self.__LIST_NUM: - num = self.__LIST_NUM + (self.__LIST_NUM - (self.__COUNT_PAGE - self.__C_PAGE)); + num = self.__LIST_NUM + \ + (self.__LIST_NUM - (self.__COUNT_PAGE - self.__C_PAGE)) else: num = self.__LIST_NUM n = 0 for i in range(num): n = num - i - page = self.__C_PAGE - n; + page = self.__C_PAGE - n if page > 0: if self.__RTURN_JS == "": - pages += "" + bytes(page) + "" + pages += "" + bytes(page) + "" else: - pages += "" + bytes(page) + "" - - #当前页 + pages += "" + bytes(page) + "" + + # 当前页 if self.__C_PAGE > 0: - pages += "" + bytes(self.__C_PAGE) + "" - - #当前页之后 + pages += "" + \ + bytes(self.__C_PAGE) + "" + + # 当前页之后 if self.__C_PAGE <= self.__LIST_NUM: num = self.__LIST_NUM + (self.__LIST_NUM - self.__C_PAGE) + 1 else: - num = self.__LIST_NUM; + num = self.__LIST_NUM for i in range(num): if i == 0: continue - page = self.__C_PAGE + i; + page = self.__C_PAGE + i if page > self.__COUNT_PAGE: - break; + break if self.__RTURN_JS == "": - pages += "" + bytes(page) + "" - else: - pages += "" + bytes(page) + "" - - return pages; - + pages += "" + bytes(page) + "" + else: + pages += "" + bytes(page) + "" + + return pages + def __GetPrev(self): - #构造上一页 + # 构造上一页 startStr = '' if self.__C_PAGE == 1: - startStr = ''; + startStr = '' else: if self.__RTURN_JS == "": - startStr = "" + self.__PREV + "" - else: - startStr = "" + self.__PREV + "" + startStr = "" + self.__PREV + "" + else: + startStr = "" + self.__PREV + "" return startStr - + def __GetStart(self): - #构造起始分页 + # 构造起始分页 startStr = '' if self.__C_PAGE == 1: - startStr = ''; + startStr = '' else: if self.__RTURN_JS == "": - startStr = "" + self.__START + "" + startStr = "" + self.__START + "" else: - startStr = "" + self.__START + "" - return startStr; - - def __GetCpage(self,p): - #取当前页 + startStr = "" + self.__START + "" + return startStr + + def __GetCpage(self, p): + # 取当前页 if p: return p return 1 - + def __StartRow(self): - #从多少行开始 + # 从多少行开始 return (self.__C_PAGE - 1) * self.ROW + 1 - + def __EndRow(self): - #从多少行结束 + # 从多少行结束 if self.ROW > self.__COUNT_ROW: return self.__COUNT_ROW return self.__C_PAGE * self.ROW - + def __GetCountPage(self): - #取总页数 + # 取总页数 return int(math.ceil(self.__COUNT_ROW / float(self.ROW))) - - def __SetUri(self,input): - #构造URI + + def __SetUri(self, input): + # 构造URI uri = '?' for key in input: if key == 'p': continue - uri += key+'='+input[key]+'&' + uri += key + '=' + input[key] + '&' return str(uri) diff --git a/class/public.py b/class/public.py index 9ec91f45d..5f96b5264 100755 --- a/class/public.py +++ b/class/public.py @@ -72,22 +72,6 @@ def GetRandomString(length): return str -def checkCode(code, outime=120): - # 校验验证码 - import web - try: - if md5(code.lower()) != web.ctx.session.codeStr: - web.ctx.session.login_error = getMsg('CODE_ERR') - return False - if time.time() - web.ctx.session.codeTime > outime: - web.ctx.session.login_error = getMsg('CODE_TIMEOUT') - return False - return True - except: - web.ctx.session.login_error = getMsg('CODE_NOT_EXISTS') - return False - - def retJson(status, msg, data=()): return jsonify({'status': status, 'msg': msg, 'data': data}) @@ -139,13 +123,6 @@ def getLan(key): return msg -def getJson(data): - import json - import web - web.header('Content-Type', 'application/json; charset=utf-8') - return json.dumps(data) - - def readFile(filename): # 读文件内容 try: @@ -333,13 +310,13 @@ def GetLocalIp(): ipaddress = re.search('\d+.\d+.\d+.\d+', ipaddress).group(0) return ipaddress except: - try: - url = web.ctx.session.home + '/Api/getIpAddress' - opener = urllib2.urlopen(url) - return opener.read() - except: - import web - return web.ctx.host.split(':')[0] + pass + # try: + # url = web.ctx.session.home + '/Api/getIpAddress' + # opener = urllib2.urlopen(url) + # return opener.read() + # except: + # return web.ctx.host.split(':')[0] # 搜索数据中是否存在 @@ -355,7 +332,6 @@ def inArray(arrays, searchStr): def checkWebConfig(): - import web if get_webserver() == 'nginx': result = ExecShell( "ulimit -n 10240 && /www/server/nginx/sbin/nginx -t -c /www/server/nginx/conf/nginx.conf") @@ -787,15 +763,15 @@ def CheckCert(certPath='ssl/certificate.pem'): # 获取面板地址 -def getPanelAddr(): - import web - protocol = 'https://' if os.path.exists("data/ssl.pl") else 'http://' - h = web.ctx.host.split(':') - try: - result = protocol + h[0] + ':' + h[1] - except: - result = protocol + h[0] + ':' + readFile('data/port.pl').strip() - return result +# def getPanelAddr(): +# import web +# protocol = 'https://' if os.path.exists("data/ssl.pl") else 'http://' +# h = web.ctx.host.split(':') +# try: +# result = protocol + h[0] + ':' + h[1] +# except: +# result = protocol + h[0] + ':' + readFile('data/port.pl').strip() +# return result # 字节单位转换 diff --git a/class/system.py b/class/system.py index 99e6d55cd..e23330620 100755 --- a/class/system.py +++ b/class/system.py @@ -1,173 +1,191 @@ -#coding: utf-8 -# +------------------------------------------------------------------- -# | 宝塔Linux面板 x3 -# +------------------------------------------------------------------- -# | Copyright (c) 2015-2016 宝塔软件(http://bt.cn) All rights reserved. -# +------------------------------------------------------------------- -# | Author: 黄文良 <287962566@qq.com> -# +------------------------------------------------------------------- -import psutil,web,time,os,public,re +# coding: utf-8 + +import psutil +import time +import os +import public +import re + + class system: - setupPath = None; + setupPath = None pids = None + def __init__(self): - self.setupPath = '/www/server'; - - def GetConcifInfo(self,get=None): - #取环境配置信息 + self.setupPath = '/www/server' + + def GetConcifInfo(self, get=None): + # 取环境配置信息 if not hasattr(web.ctx.session, 'config'): - web.ctx.session.config = public.M('config').where("id=?",('1',)).field('webserver,sites_path,backup_path,status,mysql_root').find(); - if not hasattr(web.ctx.session.config,'email'): - web.ctx.session.config['email'] = public.M('users').where("id=?",('1',)).getField('email'); + web.ctx.session.config = public.M('config').where("id=?", ('1',)).field( + 'webserver,sites_path,backup_path,status,mysql_root').find() + if not hasattr(web.ctx.session.config, 'email'): + web.ctx.session.config['email'] = public.M( + 'users').where("id=?", ('1',)).getField('email') data = {} data = web.ctx.session.config data['webserver'] = web.ctx.session.config['webserver'] - #PHP版本 - phpVersions = ('52','53','54','55','56','70','71','72','73','74') - + # PHP版本 + phpVersions = ('52', '53', '54', '55', '56', + '70', '71', '72', '73', '74') + data['php'] = [] - + for version in phpVersions: tmp = {} - tmp['setup'] = os.path.exists(self.setupPath + '/php/'+version+'/bin/php'); + tmp['setup'] = os.path.exists( + self.setupPath + '/php/' + version + '/bin/php') if tmp['setup']: phpConfig = self.GetPHPConfig(version) tmp['version'] = version tmp['max'] = phpConfig['max'] tmp['maxTime'] = phpConfig['maxTime'] tmp['pathinfo'] = phpConfig['pathinfo'] - tmp['status'] = os.path.exists('/tmp/php-cgi-'+version+'.sock') + tmp['status'] = os.path.exists( + '/tmp/php-cgi-' + version + '.sock') data['php'].append(tmp) - + tmp = {} data['webserver'] = '' serviceName = 'nginx' tmp['setup'] = False phpversion = "54" - phpport = '888'; - pstatus = False; - pauth = False; - if os.path.exists(self.setupPath+'/nginx'): + phpport = '888' + pstatus = False + pauth = False + if os.path.exists(self.setupPath + '/nginx'): data['webserver'] = 'nginx' serviceName = 'nginx' - tmp['setup'] = os.path.exists(self.setupPath +'/nginx/sbin/nginx'); - configFile = self.setupPath + '/nginx/conf/nginx.conf'; + tmp['setup'] = os.path.exists(self.setupPath + '/nginx/sbin/nginx') + configFile = self.setupPath + '/nginx/conf/nginx.conf' try: if os.path.exists(configFile): - conf = public.readFile(configFile); - rep = "listen\s+([0-9]+)\s*;"; - rtmp = re.search(rep,conf); + conf = public.readFile(configFile) + rep = "listen\s+([0-9]+)\s*;" + rtmp = re.search(rep, conf) if rtmp: - phpport = rtmp.groups()[0]; - - if conf.find('AUTH_START') != -1: pauth = True; - if conf.find(self.setupPath + '/stop') == -1: pstatus = True; - configFile = self.setupPath + '/nginx/conf/enable-php.conf'; - conf = public.readFile(configFile); - rep = "php-cgi-([0-9]+)\.sock"; - rtmp = re.search(rep,conf); + phpport = rtmp.groups()[0] + + if conf.find('AUTH_START') != -1: + pauth = True + if conf.find(self.setupPath + '/stop') == -1: + pstatus = True + configFile = self.setupPath + '/nginx/conf/enable-php.conf' + conf = public.readFile(configFile) + rep = "php-cgi-([0-9]+)\.sock" + rtmp = re.search(rep, conf) if rtmp: - phpversion = rtmp.groups()[0]; + phpversion = rtmp.groups()[0] except: - pass; - - elif os.path.exists(self.setupPath+'/apache'): + pass + + elif os.path.exists(self.setupPath + '/apache'): data['webserver'] = 'apache' serviceName = 'httpd' - tmp['setup'] = os.path.exists(self.setupPath +'/apache/bin/httpd'); - configFile = self.setupPath + '/apache/conf/extra/httpd-vhosts.conf'; + tmp['setup'] = os.path.exists(self.setupPath + '/apache/bin/httpd') + configFile = self.setupPath + '/apache/conf/extra/httpd-vhosts.conf' try: if os.path.exists(configFile): - conf = public.readFile(configFile); - rep = "php-cgi-([0-9]+)\.sock"; - rtmp = re.search(rep,conf); + conf = public.readFile(configFile) + rep = "php-cgi-([0-9]+)\.sock" + rtmp = re.search(rep, conf) if rtmp: - phpversion = rtmp.groups()[0]; - rep = "Listen\s+([0-9]+)\s*\n"; - rtmp = re.search(rep,conf); + phpversion = rtmp.groups()[0] + rep = "Listen\s+([0-9]+)\s*\n" + rtmp = re.search(rep, conf) if rtmp: - phpport = rtmp.groups()[0]; - if conf.find('AUTH_START') != -1: pauth = True; - if conf.find(self.setupPath + '/stop') == -1: pstatus = True; + phpport = rtmp.groups()[0] + if conf.find('AUTH_START') != -1: + pauth = True + if conf.find(self.setupPath + '/stop') == -1: + pstatus = True except: pass - - + tmp['type'] = data['webserver'] - tmp['version'] = public.readFile(self.setupPath + '/'+data['webserver']+'/version.pl'); + tmp['version'] = public.readFile( + self.setupPath + '/' + data['webserver'] + '/version.pl') tmp['status'] = False result = public.ExecShell('/etc/init.d/' + serviceName + ' status') - if result[0].find('running') != -1: tmp['status'] = True + if result[0].find('running') != -1: + tmp['status'] = True data['web'] = tmp - + tmp = {} - vfile = self.setupPath + '/phpmyadmin/version.pl'; - tmp['version'] = public.readFile(vfile); - tmp['setup'] = os.path.exists(vfile); - tmp['status'] = pstatus; - tmp['phpversion'] = phpversion; - tmp['port'] = phpport; - tmp['auth'] = pauth; - data['phpmyadmin'] = tmp; - + vfile = self.setupPath + '/phpmyadmin/version.pl' + tmp['version'] = public.readFile(vfile) + tmp['setup'] = os.path.exists(vfile) + tmp['status'] = pstatus + tmp['phpversion'] = phpversion + 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'] = False if tmp['setup']: if os.path.exists('/www/server/tomcat/logs/catalina-daemon.pid'): tmp['status'] = self.getPid('jsvc') if not tmp['status']: tmp['status'] = self.getPid('java') - 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.ExecShell( + 'date +"%Y-%m-%d %H:%M:%S %Z %z"')[0].strip() + return data - - - #名取PID - def getPid(self,pname): + + # 名取PID + def getPid(self, pname): try: - if not self.pids: self.pids = psutil.pids() + if not self.pids: + self.pids = psutil.pids() for pid in self.pids: - if psutil.Process(pid).name() == pname: return True; + if psutil.Process(pid).name() == pname: + return True return False - except: return False - - #检测指定进程是否存活 - def checkProcess(self,pid): + except: + return False + + # 检测指定进程是否存活 + def checkProcess(self, pid): try: - if not self.pids: self.pids = psutil.pids() - if int(pid) in self.pids: return True - return False; - except: return False - - - def GetPanelInfo(self,get=None): - #取面板配置 + if not self.pids: + self.pids = psutil.pids() + if int(pid) in self.pids: + return True + return False + except: + return False + + def GetPanelInfo(self, get=None): + # 取面板配置 address = public.GetLocalIp() try: try: @@ -175,211 +193,232 @@ class system: except: port = public.readFile('data/port.pl') 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') + templates = [] for template in os.listdir('templates/'): - if os.path.isdir('templates/' + template): templates.append(template); - template = public.readFile('data/templates.pl'); - - 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} - - def GetPHPConfig(self,version): - #取PHP配置 - file = self.setupPath + "/php/"+version+"/etc/php.ini" + if os.path.isdir('templates/' + template): + templates.append(template) + template = public.readFile('data/templates.pl') + + 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} + + def GetPHPConfig(self, version): + # 取PHP配置 + file = self.setupPath + "/php/" + version + "/etc/php.ini" phpini = public.readFile(file) - file = self.setupPath + "/php/"+version+"/etc/php-fpm.conf" + file = self.setupPath + "/php/" + version + "/etc/php-fpm.conf" phpfpm = public.readFile(file) data = {} try: rep = "upload_max_filesize\s*=\s*([0-9]+)M" - tmp = re.search(rep,phpini).groups() + tmp = re.search(rep, phpini).groups() data['max'] = tmp[0] except: data['max'] = '50' try: rep = "request_terminate_timeout\s*=\s*([0-9]+)\n" - tmp = re.search(rep,phpfpm).groups() + tmp = re.search(rep, phpfpm).groups() data['maxTime'] = tmp[0] except: data['maxTime'] = 0 - + try: rep = ur"\n;*\s*cgi\.fix_pathinfo\s*=\s*([0-9]+)\s*\n" - tmp = re.search(rep,phpini).groups() - + tmp = re.search(rep, phpini).groups() + if tmp[0] == '1': data['pathinfo'] = True else: data['pathinfo'] = False except: data['pathinfo'] = False - + return data - - def GetSystemTotal(self,get,interval = 1): - #取系统统计信息 - data = self.GetMemInfo(); - cpu = self.GetCpuInfo(interval); - data['cpuNum'] = cpu[1]; - data['cpuRealUsed'] = cpu[0]; - data['time'] = self.GetBootTime(); - data['system'] = self.GetSystemVersion(); - data['isuser'] = public.M('users').where('username=?',('admin',)).count(); - data['version'] = web.ctx.session.version; + def GetSystemTotal(self, get, interval=1): + # 取系统统计信息 + data = self.GetMemInfo() + cpu = self.GetCpuInfo(interval) + data['cpuNum'] = cpu[1] + data['cpuRealUsed'] = cpu[0] + data['time'] = self.GetBootTime() + data['system'] = self.GetSystemVersion() + data['isuser'] = public.M('users').where( + 'username=?', ('admin',)).count() + data['version'] = web.ctx.session.version return data - - def GetLoadAverage(self,get): + + def GetLoadAverage(self, get): c = os.getloadavg() - data = {}; - data['one'] = float(c[0]); - data['five'] = float(c[1]); - data['fifteen'] = float(c[2]); - data['max'] = psutil.cpu_count() * 2; - data['limit'] = data['max']; - data['safe'] = data['max'] * 0.75; - return data; - - def GetAllInfo(self,get): data = {} - data['load_average'] = self.GetLoadAverage(get); - data['title'] = self.GetTitle(); - data['network'] = self.GetNetWorkApi(get); - data['panel_status'] = not os.path.exists('/www/server/panel/data/close.pl'); + data['one'] = float(c[0]) + data['five'] = float(c[1]) + data['fifteen'] = float(c[2]) + data['max'] = psutil.cpu_count() * 2 + data['limit'] = data['max'] + data['safe'] = data['max'] * 0.75 + return data + + def GetAllInfo(self, get): + data = {} + data['load_average'] = self.GetLoadAverage(get) + data['title'] = self.GetTitle() + data['network'] = self.GetNetWorkApi(get) + data['panel_status'] = not os.path.exists( + '/www/server/panel/data/close.pl') import firewalls ssh_info = firewalls.firewalls().GetSshInfo(None) data['enable_ssh_status'] = ssh_info['status'] data['disable_ping_status'] = not ssh_info['ping'] - data['time'] = self.GetBootTime(); + data['time'] = self.GetBootTime() #data['system'] = self.GetSystemVersion(); #data['mem'] = self.GetMemInfo(); - data['version'] = web.ctx.session.version; - return data; - + data['version'] = web.ctx.session.version + return data + def GetTitle(self): - titlePl = 'data/title.pl'; - title = '宝塔Linux面板'; - if os.path.exists(titlePl): title = public.readFile(titlePl).strip(); - return title; - + titlePl = 'data/title.pl' + title = '宝塔Linux面板' + if os.path.exists(titlePl): + title = public.readFile(titlePl).strip() + return title + def GetSystemVersion(self): - #取操作系统版本 + # 取操作系统版本 import public version = public.readFile('/etc/redhat-release') if not version: - version = public.readFile('/etc/issue').strip().split("\n")[0].replace('\\n','').replace('\l','').strip(); + version = public.readFile( + '/etc/issue').strip().split("\n")[0].replace('\\n', '').replace('\l', '').strip() else: - version = version.replace('release ','').strip(); + version = version.replace('release ', '').strip() return version - + def GetBootTime(self): - #取系统启动时间 - import public,math + # 取系统启动时间 + import public + import math conf = public.readFile('/proc/uptime').split() tStr = float(conf[0]) - min = tStr / 60; - hours = min / 60; - days = math.floor(hours / 24); - hours = math.floor(hours - (days * 24)); - min = math.floor(min - (days * 60 * 24) - (hours * 60)); - return public.getMsg('SYS_BOOT_TIME',(str(int(days)),str(int(hours)),str(int(min)))) - - def GetCpuInfo(self,interval = 1): - #取CPU信息 + min = tStr / 60 + hours = min / 60 + days = math.floor(hours / 24) + hours = math.floor(hours - (days * 24)) + min = math.floor(min - (days * 60 * 24) - (hours * 60)) + return public.getMsg('SYS_BOOT_TIME', (str(int(days)), str(int(hours)), str(int(min)))) + + def GetCpuInfo(self, interval=1): + # 取CPU信息 cpuCount = psutil.cpu_count() used = psutil.cpu_percent(interval=interval) - return used,cpuCount - - def GetMemInfo(self,get=None): - #取内存信息 + return used, cpuCount + + def GetMemInfo(self, get=None): + # 取内存信息 mem = psutil.virtual_memory() - memInfo = {'memTotal':mem.total/1024/1024,'memFree':mem.free/1024/1024,'memBuffers':mem.buffers/1024/1024,'memCached':mem.cached/1024/1024} - memInfo['memRealUsed'] = memInfo['memTotal'] - memInfo['memFree'] - memInfo['memBuffers'] - memInfo['memCached'] + memInfo = {'memTotal': mem.total / 1024 / 1024, 'memFree': mem.free / 1024 / 1024, + 'memBuffers': mem.buffers / 1024 / 1024, 'memCached': mem.cached / 1024 / 1024} + memInfo['memRealUsed'] = memInfo['memTotal'] - \ + memInfo['memFree'] - memInfo['memBuffers'] - memInfo['memCached'] return memInfo - - def GetDiskInfo(self,get=None): - return self.GetDiskInfo2(); - #取磁盘分区信息 - diskIo = psutil.disk_partitions(); + + def GetDiskInfo(self, get=None): + return self.GetDiskInfo2() + # 取磁盘分区信息 + diskIo = psutil.disk_partitions() diskInfo = [] - + for disk in diskIo: - if disk[1] == '/mnt/cdrom':continue; - if disk[1] == '/boot':continue; + if disk[1] == '/mnt/cdrom': + continue + if disk[1] == '/boot': + continue tmp = {} tmp['path'] = disk[1] tmp['size'] = psutil.disk_usage(disk[1]) diskInfo.append(tmp) return diskInfo - + def GetDiskInfo2(self): - #取磁盘分区信息 - temp = public.ExecShell("df -h -P|grep '/'|grep -v tmpfs")[0]; - tempInodes = public.ExecShell("df -i -P|grep '/'|grep -v tmpfs")[0]; - temp1 = temp.split('\n'); - tempInodes1 = tempInodes.split('\n'); - diskInfo = []; + # 取磁盘分区信息 + temp = public.ExecShell("df -h -P|grep '/'|grep -v tmpfs")[0] + tempInodes = public.ExecShell("df -i -P|grep '/'|grep -v tmpfs")[0] + temp1 = temp.split('\n') + tempInodes1 = tempInodes.split('\n') + diskInfo = [] n = 0 - cuts = ['/mnt/cdrom','/boot','/boot/efi','/dev','/dev/shm','/run/lock','/run','/run/shm','/run/user']; + cuts = ['/mnt/cdrom', '/boot', '/boot/efi', '/dev', + '/dev/shm', '/run/lock', '/run', '/run/shm', '/run/user'] for tmp in temp1: n += 1 - inodes = tempInodes1[n-1].split(); - disk = tmp.split(); - if len(disk) < 5: continue; - if disk[1].find('M') != -1: continue; - if disk[1].find('K') != -1: continue; - if len(disk[5].split('/')) > 4: continue; - if disk[5] in cuts: continue; + inodes = tempInodes1[n - 1].split() + disk = tmp.split() + if len(disk) < 5: + continue + if disk[1].find('M') != -1: + continue + if disk[1].find('K') != -1: + continue + if len(disk[5].split('/')) > 4: + continue + if disk[5] in cuts: + continue arr = {} - arr['path'] = disk[5]; - tmp1 = [disk[1],disk[2],disk[3],disk[4]]; - arr['size'] = tmp1; - arr['inodes'] = [inodes[1],inodes[2],inodes[3],inodes[4]] + arr['path'] = disk[5] + tmp1 = [disk[1], disk[2], disk[3], disk[4]] + arr['size'] = tmp1 + arr['inodes'] = [inodes[1], inodes[2], inodes[3], inodes[4]] if disk[5] == '/': - bootLog = '/tmp/panelBoot.pl'; + bootLog = '/tmp/panelBoot.pl' if disk[2].find('M') != -1: - if os.path.exists(bootLog): os.system('rm -f ' + bootLog); + if os.path.exists(bootLog): + os.system('rm -f ' + bootLog) else: - if not os.path.exists(bootLog): os.system('sleep 1 && /etc/init.d/bt reload &'); - diskInfo.append(arr); - return diskInfo; - - #清理系统垃圾 - def ClearSystem(self,get): - count = total = 0; - tmp_total,tmp_count = self.ClearMail(); - count += tmp_count; - total += tmp_total; - tmp_total,tmp_count = self.ClearOther(); - count += tmp_count; - total += tmp_total; - return count,total - - #清理邮件日志 + if not os.path.exists(bootLog): + os.system('sleep 1 && /etc/init.d/bt reload &') + diskInfo.append(arr) + return diskInfo + + # 清理系统垃圾 + def ClearSystem(self, get): + count = total = 0 + tmp_total, tmp_count = self.ClearMail() + count += tmp_count + total += tmp_total + tmp_total, tmp_count = self.ClearOther() + count += tmp_count + total += tmp_total + return count, total + + # 清理邮件日志 def ClearMail(self): - rpath = '/var/spool'; - total = count = 0; + rpath = '/var/spool' + total = count = 0 import shutil - con = ['cron','anacron','mail']; + con = ['cron', 'anacron', 'mail'] for d in os.listdir(rpath): - if d in con: continue; + if d in con: + continue dpath = rpath + '/' + d - time.sleep(0.2); - num = size = 0; + time.sleep(0.2) + num = size = 0 for n in os.listdir(dpath): filename = dpath + '/' + n - fsize = os.path.getsize(filename); + fsize = os.path.getsize(filename) size += fsize if os.path.isdir(filename): shutil.rmtree(filename) @@ -387,248 +426,275 @@ class system: os.remove(filename) print '\t\033[1;32m[OK]\033[0m' num += 1 - total += size; - count += num; - return total,count - - #清理其它 + total += size + count += num + return total, count + + # 清理其它 def ClearOther(self): clearPath = [ - {'path':'/www/server/panel','find':'testDisk_'}, - {'path':'/www/wwwlogs','find':'log'}, - {'path':'/tmp','find':'panelBoot.pl'}, - {'path':'/www/server/panel/install','find':'.rpm'} - ] - - total = count = 0; + {'path': '/www/server/panel', 'find': 'testDisk_'}, + {'path': '/www/wwwlogs', 'find': 'log'}, + {'path': '/tmp', 'find': 'panelBoot.pl'}, + {'path': '/www/server/panel/install', 'find': '.rpm'} + ] + + total = count = 0 for c in clearPath: for d in os.listdir(c['path']): - if d.find(c['find']) == -1: continue; - filename = c['path'] + '/' + d; - fsize = os.path.getsize(filename); + if d.find(c['find']) == -1: + continue + filename = c['path'] + '/' + d + fsize = os.path.getsize(filename) total += fsize if os.path.isdir(filename): shutil.rmtree(filename) else: os.remove(filename) - count += 1; - public.serviceReload(); - os.system('echo > /tmp/panelBoot.pl'); - return total,count - - def GetNetWork(self,get=None): - #return self.GetNetWorkApi(get); - #取网络流量信息 + count += 1 + public.serviceReload() + os.system('echo > /tmp/panelBoot.pl') + return total, count + + def GetNetWork(self, get=None): + # return self.GetNetWorkApi(get); + # 取网络流量信息 try: networkIo = psutil.net_io_counters()[:4] - if not hasattr(web.ctx.session,'otime'): - web.ctx.session.up = networkIo[0] - web.ctx.session.down = networkIo[1] - web.ctx.session.otime = time.time(); - - ntime = time.time(); + if not hasattr(web.ctx.session, 'otime'): + web.ctx.session.up = networkIo[0] + web.ctx.session.down = networkIo[1] + web.ctx.session.otime = time.time() + + ntime = time.time() networkInfo = {} - networkInfo['upTotal'] = networkIo[0] + networkInfo['upTotal'] = networkIo[0] networkInfo['downTotal'] = networkIo[1] - networkInfo['up'] = round(float(networkIo[0] - web.ctx.session.up) / 1024 / (ntime - web.ctx.session.otime),2) - networkInfo['down'] = round(float(networkIo[1] - web.ctx.session.down) / 1024 / (ntime - web.ctx.session.otime),2) - networkInfo['downPackets'] =networkIo[3] - networkInfo['upPackets'] =networkIo[2] - - web.ctx.session.up = networkIo[0] - web.ctx.session.down = networkIo[1] - web.ctx.session.otime = ntime; - + networkInfo['up'] = round(float( + networkIo[0] - web.ctx.session.up) / 1024 / (ntime - web.ctx.session.otime), 2) + networkInfo['down'] = round(float( + networkIo[1] - web.ctx.session.down) / 1024 / (ntime - web.ctx.session.otime), 2) + networkInfo['downPackets'] = networkIo[3] + networkInfo['upPackets'] = networkIo[2] + + web.ctx.session.up = networkIo[0] + web.ctx.session.down = networkIo[1] + web.ctx.session.otime = ntime + networkInfo['cpu'] = self.GetCpuInfo() - networkInfo['load'] = self.GetLoadAverage(get); + networkInfo['load'] = self.GetLoadAverage(get) return networkInfo except: return None - - - def GetNetWorkApi(self,get=None): - #取网络流量信息 + + def GetNetWorkApi(self, get=None): + # 取网络流量信息 try: - tmpfile = 'data/network.temp'; + tmpfile = 'data/network.temp' networkIo = psutil.net_io_counters()[:4] - - if not os.path.exists(tmpfile): - public.writeFile(tmpfile,str(networkIo[0])+'|'+str(networkIo[1])+'|' + str(int(time.time()))); - - lastValue = public.readFile(tmpfile).split('|'); - - ntime = time.time(); + + if not os.path.exists(tmpfile): + public.writeFile(tmpfile, str( + networkIo[0]) + '|' + str(networkIo[1]) + '|' + str(int(time.time()))) + + lastValue = public.readFile(tmpfile).split('|') + + ntime = time.time() networkInfo = {} - networkInfo['upTotal'] = networkIo[0] + networkInfo['upTotal'] = networkIo[0] networkInfo['downTotal'] = networkIo[1] - networkInfo['up'] = round(float(networkIo[0] - int(lastValue[0])) / 1024 / (ntime - int(lastValue[2])),2) - networkInfo['down'] = round(float(networkIo[1] - int(lastValue[1])) / 1024 / (ntime - int(lastValue[2])),2) - networkInfo['downPackets'] =networkIo[3] - networkInfo['upPackets'] =networkIo[2] - - public.writeFile(tmpfile,str(networkIo[0])+'|'+str(networkIo[1])+'|' + str(int(time.time()))); - + networkInfo['up'] = round( + float(networkIo[0] - int(lastValue[0])) / 1024 / (ntime - int(lastValue[2])), 2) + networkInfo['down'] = round( + float(networkIo[1] - int(lastValue[1])) / 1024 / (ntime - int(lastValue[2])), 2) + networkInfo['downPackets'] = networkIo[3] + networkInfo['upPackets'] = networkIo[2] + + public.writeFile(tmpfile, str( + networkIo[0]) + '|' + str(networkIo[1]) + '|' + str(int(time.time()))) + #networkInfo['cpu'] = self.GetCpuInfo(0.1) return networkInfo except: return None - + def GetNetWorkOld(self): - #取网络流量信息 - import time; - pnet = public.readFile('/proc/net/dev'); - rep = '([^\s]+):[\s]{0,}(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)'; - pnetall = re.findall(rep,pnet); + # 取网络流量信息 + import time + pnet = public.readFile('/proc/net/dev') + rep = '([^\s]+):[\s]{0,}(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)' + pnetall = re.findall(rep, pnet) networkInfo = {} - networkInfo['upTotal'] = networkInfo['downTotal'] = networkInfo['up'] = networkInfo['down'] = networkInfo['downPackets'] = networkInfo['upPackets'] = 0; + networkInfo['upTotal'] = networkInfo['downTotal'] = networkInfo['up'] = networkInfo[ + 'down'] = networkInfo['downPackets'] = networkInfo['upPackets'] = 0 for pnetInfo in pnetall: - if pnetInfo[0] == 'io': continue; - networkInfo['downTotal'] += int(pnetInfo[1]); - networkInfo['downPackets'] += int(pnetInfo[2]); - networkInfo['upTotal'] += int(pnetInfo[9]); - networkInfo['upPackets'] += int(pnetInfo[10]); - - if not hasattr(web.ctx.session,'otime'): - web.ctx.session.up = networkInfo['upTotal'] - web.ctx.session.down = networkInfo['downTotal'] - web.ctx.session.otime = time.time(); - ntime = time.time(); - tmpDown = networkInfo['downTotal'] - web.ctx.session.down; - tmpUp = networkInfo['upTotal'] - web.ctx.session.up; - networkInfo['down'] = str(round(float(tmpDown) / 1024 / (ntime - web.ctx.session.otime),2)); - networkInfo['up'] = str(round(float(tmpUp) / 1024 / (ntime - web.ctx.session.otime),2)); - if networkInfo['down'] < 0: networkInfo['down'] = 0; - if networkInfo['up'] < 0: networkInfo['up'] = 0; - - web.ctx.session.up = networkInfo['upTotal']; - web.ctx.session.down = networkInfo['downTotal']; - web.ctx.session.otime = ntime; + if pnetInfo[0] == 'io': + continue + networkInfo['downTotal'] += int(pnetInfo[1]) + networkInfo['downPackets'] += int(pnetInfo[2]) + networkInfo['upTotal'] += int(pnetInfo[9]) + networkInfo['upPackets'] += int(pnetInfo[10]) + + if not hasattr(web.ctx.session, 'otime'): + web.ctx.session.up = networkInfo['upTotal'] + web.ctx.session.down = networkInfo['downTotal'] + web.ctx.session.otime = time.time() + ntime = time.time() + tmpDown = networkInfo['downTotal'] - web.ctx.session.down + tmpUp = networkInfo['upTotal'] - web.ctx.session.up + networkInfo['down'] = str( + round(float(tmpDown) / 1024 / (ntime - web.ctx.session.otime), 2)) + networkInfo['up'] = str( + round(float(tmpUp) / 1024 / (ntime - web.ctx.session.otime), 2)) + if networkInfo['down'] < 0: + networkInfo['down'] = 0 + if networkInfo['up'] < 0: + networkInfo['up'] = 0 + + web.ctx.session.up = networkInfo['upTotal'] + web.ctx.session.down = networkInfo['downTotal'] + web.ctx.session.otime = ntime networkInfo['cpu'] = self.GetCpuInfo() - return networkInfo; - - def ServiceAdmin(self,get=None): - #服务管理 - - if get.name == 'mysqld': public.CheckMyCnf(); - + return networkInfo + + def ServiceAdmin(self, get=None): + # 服务管理 + + if get.name == 'mysqld': + public.CheckMyCnf() + if get.name == 'phpmyadmin': import ajax - get.status = 'True'; - ajax.ajax().setPHPMyAdmin(get); - return public.returnMsg(True,'SYS_EXEC_SUCCESS'); - - #检查httpd配置文件 + get.status = 'True' + ajax.ajax().setPHPMyAdmin(get) + return public.returnMsg(True, 'SYS_EXEC_SUCCESS') + + # 检查httpd配置文件 if get.name == 'apache' or get.name == 'httpd': - get.name = 'httpd'; - if not os.path.exists(self.setupPath+'/apache/bin/apachectl'): return public.returnMsg(True,'SYS_NOT_INSTALL_APACHE'); + get.name = 'httpd' + if not os.path.exists(self.setupPath + '/apache/bin/apachectl'): + return public.returnMsg(True, 'SYS_NOT_INSTALL_APACHE') vhostPath = self.setupPath + '/panel/vhost/apache' if not os.path.exists(vhostPath): - public.ExecShell('mkdir ' + vhostPath); - public.ExecShell('/etc/init.d/httpd start'); - - if get.type == 'start': - public.ExecShell('/etc/init.d/httpd stop'); - public.ExecShell('pkill -9 httpd'); - - result = public.ExecShell('ulimit -n 10240 && ' + self.setupPath+'/apache/bin/apachectl -t'); + public.ExecShell('mkdir ' + vhostPath) + public.ExecShell('/etc/init.d/httpd start') + + if get.type == 'start': + public.ExecShell('/etc/init.d/httpd stop') + public.ExecShell('pkill -9 httpd') + + result = public.ExecShell( + 'ulimit -n 10240 && ' + self.setupPath + '/apache/bin/apachectl -t') if result[1].find('Syntax OK') == -1: - public.WriteLog("TYPE_SOFT",'SYS_EXEC_ERR', (str(result),)); - return public.returnMsg(False,'SYS_CONF_APACHE_ERR',(result[1].replace("\n",'
'),)); - + public.WriteLog("TYPE_SOFT", 'SYS_EXEC_ERR', (str(result),)) + return public.returnMsg(False, 'SYS_CONF_APACHE_ERR', (result[1].replace("\n", '
'),)) + if get.type == 'restart': - public.ExecShell('pkill -9 httpd'); - public.ExecShell('/etc/init.d/httpd start'); - - #检查nginx配置文件 + public.ExecShell('pkill -9 httpd') + public.ExecShell('/etc/init.d/httpd start') + + # 检查nginx配置文件 elif get.name == 'nginx': vhostPath = self.setupPath + '/panel/vhost/rewrite' - if not os.path.exists(vhostPath): public.ExecShell('mkdir ' + vhostPath); + if not os.path.exists(vhostPath): + public.ExecShell('mkdir ' + vhostPath) vhostPath = self.setupPath + '/panel/vhost/nginx' if not os.path.exists(vhostPath): - public.ExecShell('mkdir ' + vhostPath); - public.ExecShell('/etc/init.d/nginx start'); - - result = public.ExecShell('ulimit -n 10240 && nginx -t -c '+self.setupPath+'/nginx/conf/nginx.conf'); + public.ExecShell('mkdir ' + vhostPath) + public.ExecShell('/etc/init.d/nginx start') + + result = public.ExecShell( + 'ulimit -n 10240 && nginx -t -c ' + self.setupPath + '/nginx/conf/nginx.conf') if result[1].find('perserver') != -1: - limit = self.setupPath + '/nginx/conf/nginx.conf'; - nginxConf = public.readFile(limit); - limitConf = "limit_conn_zone $binary_remote_addr zone=perip:10m;\n\t\tlimit_conn_zone $server_name zone=perserver:10m;"; - nginxConf = nginxConf.replace("#limit_conn_zone $binary_remote_addr zone=perip:10m;",limitConf); - public.writeFile(limit,nginxConf) - public.ExecShell('/etc/init.d/nginx start'); - return public.returnMsg(True,'SYS_CONF_NGINX_REP'); - + limit = self.setupPath + '/nginx/conf/nginx.conf' + nginxConf = public.readFile(limit) + limitConf = "limit_conn_zone $binary_remote_addr zone=perip:10m;\n\t\tlimit_conn_zone $server_name zone=perserver:10m;" + nginxConf = nginxConf.replace( + "#limit_conn_zone $binary_remote_addr zone=perip:10m;", limitConf) + public.writeFile(limit, nginxConf) + public.ExecShell('/etc/init.d/nginx start') + return public.returnMsg(True, 'SYS_CONF_NGINX_REP') + if result[1].find('proxy') != -1: import panelSite - panelSite.panelSite().CheckProxy(get); - public.ExecShell('/etc/init.d/nginx start'); - return public.returnMsg(True,'SYS_CONF_NGINX_REP'); - - #return result + panelSite.panelSite().CheckProxy(get) + public.ExecShell('/etc/init.d/nginx start') + return public.returnMsg(True, 'SYS_CONF_NGINX_REP') + + # return result if result[1].find('successful') == -1: - public.WriteLog("TYPE_SOFT",'SYS_EXEC_ERR', (str(result),)); - return public.returnMsg(False,'SYS_CONF_NGINX_ERR',(result[1].replace("\n",'
'),)); - - #执行 - execStr = "/etc/init.d/"+get.name+" "+get.type - if execStr == '/etc/init.d/pure-ftpd reload': execStr = self.setupPath+'/pure-ftpd/bin/pure-pw mkdb '+self.setupPath+'/pure-ftpd/etc/pureftpd.pdb' - if execStr == '/etc/init.d/pure-ftpd start': os.system('pkill -9 pure-ftpd'); - if execStr == '/etc/init.d/tomcat reload': execStr = '/etc/init.d/tomcat stop && /etc/init.d/tomcat start'; - if execStr == '/etc/init.d/tomcat restart': execStr = '/etc/init.d/tomcat stop && /etc/init.d/tomcat start'; - + public.WriteLog("TYPE_SOFT", 'SYS_EXEC_ERR', (str(result),)) + return public.returnMsg(False, 'SYS_CONF_NGINX_ERR', (result[1].replace("\n", '
'),)) + + # 执行 + execStr = "/etc/init.d/" + get.name + " " + get.type + if execStr == '/etc/init.d/pure-ftpd reload': + execStr = self.setupPath + '/pure-ftpd/bin/pure-pw mkdb ' + \ + self.setupPath + '/pure-ftpd/etc/pureftpd.pdb' + if execStr == '/etc/init.d/pure-ftpd start': + os.system('pkill -9 pure-ftpd') + if execStr == '/etc/init.d/tomcat reload': + execStr = '/etc/init.d/tomcat stop && /etc/init.d/tomcat start' + if execStr == '/etc/init.d/tomcat restart': + execStr = '/etc/init.d/tomcat stop && /etc/init.d/tomcat start' + if get.name != 'mysqld': - result = public.ExecShell(execStr); + result = public.ExecShell(execStr) else: - os.system(execStr); - result = []; - result.append(''); - result.append(''); - + os.system(execStr) + result = [] + result.append('') + result.append('') + if result[1].find('nginx.pid') != -1: - public.ExecShell('pkill -9 nginx && sleep 1'); - public.ExecShell('/etc/init.d/nginx start'); + public.ExecShell('pkill -9 nginx && sleep 1') + public.ExecShell('/etc/init.d/nginx start') if get.type != 'test': - public.WriteLog("TYPE_SOFT", 'SYS_EXEC_SUCCESS',(execStr,)); - - if len(result[1]) > 1 and get.name != 'pure-ftpd': return public.returnMsg(False, '

警告消息:

' + result[1].replace('\n','
')); - return public.returnMsg(True,'SYS_EXEC_SUCCESS'); - - def RestartServer(self,get): - if not public.IsRestart(): return public.returnMsg(False,'EXEC_ERR_TASK'); - public.ExecShell("sync && /etc/init.d/bt stop && init 6 &"); - return public.returnMsg(True,'SYS_REBOOT'); - - #释放内存 - def ReMemory(self,get): - os.system('sync'); + public.WriteLog("TYPE_SOFT", 'SYS_EXEC_SUCCESS', (execStr,)) + + if len(result[1]) > 1 and get.name != 'pure-ftpd': + return public.returnMsg(False, '

警告消息:

' + result[1].replace('\n', '
')) + return public.returnMsg(True, 'SYS_EXEC_SUCCESS') + + def RestartServer(self, get): + if not public.IsRestart(): + return public.returnMsg(False, 'EXEC_ERR_TASK') + public.ExecShell("sync && /etc/init.d/bt stop && init 6 &") + return public.returnMsg(True, 'SYS_REBOOT') + + # 释放内存 + def ReMemory(self, get): + os.system('sync') scriptFile = 'script/rememory.sh' if not os.path.exists(scriptFile): - public.downloadFile(web.ctx.session.home + '/script/rememory.sh',scriptFile); - public.ExecShell("/bin/bash " + self.setupPath + '/panel/' + scriptFile); - return self.GetMemInfo(); - - #重启面板 - def ReWeb(self,get): - #if not public.IsRestart(): return public.returnMsg(False,'EXEC_ERR_TASK'); - public.ExecShell('/etc/init.d/bt restart &'); + public.downloadFile(web.ctx.session.home + + '/script/rememory.sh', scriptFile) + public.ExecShell("/bin/bash " + self.setupPath + + '/panel/' + scriptFile) + return self.GetMemInfo() + + # 重启面板 + def ReWeb(self, get): + # if not public.IsRestart(): return + # public.returnMsg(False,'EXEC_ERR_TASK'); + public.ExecShell('/etc/init.d/bt restart &') + return True + + # 修复面板 + def RepPanel(self, get): + vp = '' + if public.readFile('/www/server/panel/class/common.py').find('checkSafe') != -1: + vp = '_pro' + public.ExecShell("wget -O update.sh " + public.get_url() + + "/install/update" + vp + ".sh && bash update.sh") + if hasattr(web.ctx.session, 'getCloudPlugin'): + del(web.ctx.session['getCloudPlugin']) + return True + + # 升级到专业版 + def UpdatePro(self, get): + public.ExecShell("wget -O update.sh " + public.get_url() + + "/install/update_pro.sh && bash update.sh pro") + if hasattr(web.ctx.session, 'getCloudPlugin'): + del(web.ctx.session['getCloudPlugin']) return True - - #修复面板 - def RepPanel(self,get): - vp = ''; - if public.readFile('/www/server/panel/class/common.py').find('checkSafe') != -1: vp = '_pro'; - public.ExecShell("wget -O update.sh " + public.get_url() + "/install/update"+vp+".sh && bash update.sh"); - if hasattr(web.ctx.session,'getCloudPlugin'): del(web.ctx.session['getCloudPlugin']); - return True; - - #升级到专业版 - def UpdatePro(self,get): - public.ExecShell("wget -O update.sh " + public.get_url() + "/install/update_pro.sh && bash update.sh pro"); - if hasattr(web.ctx.session,'getCloudPlugin'): del(web.ctx.session['getCloudPlugin']); - return True; - - - - - - \ No newline at end of file diff --git a/plugins/nginx/info.json b/plugins/nginx/info.json index aa477b3da..5bba3e280 100755 --- a/plugins/nginx/info.json +++ b/plugins/nginx/info.json @@ -15,7 +15,6 @@ "pid": "1", "update": ["1.14.0", "1.12.2", "1.8.1", "1.15.3", "-Tengine2.2.2", "openresty"], "versions": [ - {"status": false, "version": "1.14", "run": false, "no": "", "task": "1"}, {"status": false, "version": "1.14", "run": false, "no": "", "task": "1"}, {"status": false, "version": "1.12", "run": false, "no": "", "task": "1"}, {"status": false, "version": "1.8", "run": false, "no": "", "task": "1"}, diff --git a/static/js/files.js b/static/js/files.js new file mode 100755 index 000000000..0fac35880 --- /dev/null +++ b/static/js/files.js @@ -0,0 +1,1609 @@ +//判断磁盘数量超出宽度 +function IsDiskWidth(){ + var comlistWidth = $("#comlist").width(); + var bodyWidth = $(".file-box").width(); + if(comlistWidth + 530 > bodyWidth){ + $("#comlist").css({"width":bodyWidth-530+"px","height":"34px","overflow":"auto"}); + } + else{ + $("#comlist").removeAttr("style"); + } +} + +//打开回收站 +function Recycle_bin(type){ + $.post('/files?action=Get_Recycle_bin','',function(rdata){ + var body = '' + switch(type){ + case 1: + for(var i=0;i 20) shortwebname = shortwebname.substring(0, 20) + "..."; + if(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;i 20) shortwebname = shortwebname.substring(0, 20) + "..."; + if(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+'\ + \ + ' + + continue; + } + var shortwebname = rdata.files[i].name.replace(/'/,"\\'"); + var shortpath = rdata.files[i].dname; + if(shortwebname.length > 20) shortwebname = shortwebname.substring(0, 20) + "..."; + if(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+'\ + \ + ' + } + $("#RecycleBody").html(body); + return; + break; + case 2: + for(var i=0;i 20) shortwebname = shortwebname.substring(0, 20) + "..."; + if(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+'\ + \ + ' + } + $("#RecycleBody").html(body); + return; + break; + case 3: + for(var i=0;i 20) shortwebname = shortwebname.substring(0, 20) + "..."; + if(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+'\ + \ + ' + } + $("#RecycleBody").html(body); + return; + break; + case 4: + for(var i=0;i 20) shortwebname = shortwebname.substring(0, 20) + "..."; + if(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+'\ + \ + ' + } + } + $("#RecycleBody").html(body); + return; + break; + case 5: + for(var i=0;i 20) shortwebname = shortwebname.substring(0, 20) + "..."; + if(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+'\ + \ + ' + } + } + $("#RecycleBody").html(body); + return; + case 6: + for(var i=0;i 20) shortwebname = shortwebname.substring(0, 20) + "..."; + if(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+'\ + \ + ' + } + } + $("#RecycleBody").html(body); + return; + break; + } + + + var tablehtml = '

\ +
\ + '+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+'

\ +
\ +
\ +
\ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + '+body+'\ +
'+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+'
'; + if(type == "open"){ + layer.open({ + type: 1, + shift: 5, + closeBtn: 2, + area: ['80%','606px'], + title: lan.files.recycle_bin_title, + content: tablehtml + }); + + if(window.location.href.indexOf("database") != -1){ + Recycle_bin(6); + $(".re-con-menu p:last-child").addClass("on").siblings().removeClass("on"); + }else{ + Recycle_bin(1); + } + } + $(".re-con-menu p").click(function(){ + $(this).addClass("on").siblings().removeClass("on"); + }) + }); +} + +//去扩展名不处理 +function getFileName(name){ + var text = name.split("."); + var n = text.length-1; + text = text[n]; + return text; +} +//判断图片文件 +function ReisImage(fileName){ + var exts = ['jpg','jpeg','png','bmp','gif','tiff','ico']; + for(var i=0; i"+lan.files.recycle_bin_close_the+"",{icon:16,time:0,shade: [0.3, '#000']}); + setTimeout(function(){ + getSpeed('.myspeed'); + },1000); + $.post('/files?action=Close_Recycle_bin','',function(rdata){ + layer.close(loadT); + layer.msg(rdata.msg,{icon:rdata.status?1:5}); + $("#RecycleBody").html(''); + }); + }); +} + + +//回收站开关 +function Set_Recycle_bin(db){ + var loadT = layer.msg(lan.public.the,{icon:16,time:0,shade: [0.3, '#000']}); + var data = {} + if(db == 1){ + data = {db:db}; + } + $.post('/files?action=Recycle_bin',data,function(rdata){ + layer.close(loadT); + layer.msg(rdata.msg,{icon:rdata.status?1:5}); + }); +} + + + +//取数据 +function GetFiles(Path) { + var searchtype = Path; + if(isNaN(Path)){ + var p = '1'; + Path = encodeURIComponent(Path) + }else{ + var p = Path; + Path = getCookie('Path'); + } + + var search = ''; + var searchV = $("#SearchValue").val(); + if(searchV.length > 1 && searchtype == "1"){ + search = "&search="+searchV; + } + var showRow = getCookie('showRow'); + if(!showRow) showRow = '100'; + var Body = ''; + var data = 'path=' + Path; + var loadT = layer.load(); + var totalSize = 0; + $.post('/files?action=GetDir&tojs=GetFiles&p=' + p + '&showRow=' + showRow + search, data, function(rdata) { + layer.close(loadT); + + var rows = ['100','200','500','1000','2000']; + var rowOption = ''; + for(var i=0;i'+rows[i]+''; + } + + $("#filePage").html(rdata.PAGE); + $("#filePage div").append("每页"); + $("#filePage .Pcount").css("left","16px"); + if(rdata.DIR == null) rdata.DIR = []; + for (var i = 0; i < rdata.DIR.length; i++) { + var fmp = rdata.DIR[i].split(";"); + var cnametext =fmp[0] + fmp[5]; + fmp[0] = fmp[0].replace(/'/,"\\'"); + if(cnametext.length>20){ + cnametext = cnametext.substring(0,20)+'...' + } + if(isChineseChar(cnametext)){ + if(cnametext.length>10){ + cnametext = cnametext.substring(0,10)+'...' + } + } + var timetext ='--'; + if(getCookie("rank") == "a"){ + $("#set_list").addClass("active"); + $("#set_icon").removeClass("active"); + Body += "\ + \ + " + cnametext + "\ + "+ToSize(fmp[1])+"\ + "+getLocalTime(fmp[2])+"\ + "+fmp[3]+"\ + "+fmp[4]+"\ + \ + "+lan.files.file_menu_copy+" | \ + "+lan.files.file_menu_mv+" | \ + "+lan.files.file_menu_rename+" | \ + "+lan.files.file_menu_auth+" | \ + "+lan.files.file_menu_zip+" | \ + "+lan.files.file_menu_del+"\ + "; + } + else{ + $("#set_icon").addClass("active"); + $("#set_list").removeClass("active"); + Body += ""; + } + } + for (var i = 0; i < rdata.FILES.length; i++) { + if(rdata.FILES[i] == null) continue; + var fmp = rdata.FILES[i].split(";"); + var displayZip = isZip(fmp[0]); + var bodyZip = ''; + var download = ''; + var cnametext =fmp[0] + fmp[5]; + fmp[0] = fmp[0].replace(/'/,"\\'"); + if(cnametext.length>48){ + cnametext = cnametext.substring(0,48)+'...' + } + if(isChineseChar(cnametext)){ + if(cnametext.length>16){ + cnametext = cnametext.substring(0,16)+'...' + } + } + if(displayZip != -1){ + bodyZip = ""+lan.files.file_menu_unzip+" | "; + } + if(isText(fmp[0])){ + bodyZip = ""+lan.files.file_menu_edit+" | "; + } + if(isImage(fmp[0])){ + download = ""+lan.files.file_menu_img+" | "; + }else{ + download = ""+lan.files.file_menu_down+" | "; + } + + totalSize += parseInt(fmp[1]); + if(getCookie("rank")=="a"){ + Body += "\ + " + cnametext + "\ + " + (ToSize(fmp[1])) + "\ + " + ((fmp[2].length > 11)?fmp[2]:getLocalTime(fmp[2])) + "\ + "+fmp[3]+"\ + "+fmp[4]+"\ + \ + "+lan.files.file_menu_copy+" | \ + "+lan.files.file_menu_mv+" | \ + "+lan.files.file_menu_rename+" | \ + "+lan.files.file_menu_auth+" | \ + "+lan.files.file_menu_zip+" | \ + "+bodyZip+download+"\ + "+lan.files.file_menu_del+"\ + "; + } + else{ + Body += ""; + } + } + var dirInfo = '('+lan.files.get_size.replace('{1}',rdata.DIR.length+'').replace('{2}',rdata.DIR.length+'')+''+(ToSize(totalSize))+''+lan.files.get+')'; + $("#DirInfo").html(dirInfo); + if(getCookie("rank")=="a"){ + var tablehtml = '\ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + '+Body+'\ +
'+lan.files.file_name+''+lan.files.file_size+''+lan.files.file_etime+''+lan.files.file_auth+''+lan.files.file_own+''+lan.files.file_act+'
'; + $("#fileCon").removeClass("fileList").html(tablehtml); + $("#tipTools").width($("#fileCon").width()); + } + else{ + $("#fileCon").addClass("fileList").html(Body); + $("#tipTools").width($("#fileCon").width()); + } + $("#DirPathPlace input").val(rdata.PATH); + var BarTools = '
\ + \ + \ +
'; + if (rdata.PATH != '/') { + BarTools += ' '; + } + setCookie('Path',rdata.PATH); + BarTools += ' '; + var copyName = getCookie('copyFileName'); + var cutName = getCookie('cutFileName'); + var isPaste = (copyName == 'null') ? cutName : copyName; + if (isPaste != 'null' && isPaste != undefined) { + BarTools += ' '; + } + + $("#Batch").html(''); + var BatchTools = ''; + var isBatch = getCookie('BatchSelected'); + if (isBatch == 1 || isBatch == '1') { + BatchTools += ' '; + } + $("#Batch").html(BatchTools); + $("#setBox").prop("checked", false); + + $("#BarTools").html(BarTools); + + $("input[name=id]").click(function(){ + if($(this).prop("checked")) { + $(this).prop("checked", true); + $(this).parents("tr").addClass("ui-selected"); + } + else{ + $(this).prop("checked", false); + $(this).parents("tr").removeClass("ui-selected"); + } + showSeclect() + }); + + $("#setBox").click(function() { + if ($(this).prop("checked")) { + $("input[name=id]").prop("checked", true); + $("#filesBody > tr").addClass("ui-selected"); + + } else { + $("input[name=id]").prop("checked", false); + $("#filesBody > tr").removeClass("ui-selected"); + } + showSeclect(); + }); + //阻止冒泡 + $("#filesBody .btlink").click(function(e){ + e.stopPropagation(); + }); + $("input[name=id]").dblclick(function(e){ + e.stopPropagation(); + }); + //禁用右键 + $("#fileCon").bind("contextmenu",function(e){ + return false; + }); + bindselect(); + //绑定右键 + $("#fileCon").mousedown(function(e){ + var count = totalFile(); + if(e.which == 3) { + if(count>1){ + RClickAll(e); + } + else{ + return + } + } + }); + $(".folderBox,.folderBoxTr").mousedown(function(e){ + var count = totalFile(); + if(e.which == 3) { + if(count <= 1){ + var a = $(this); + a.contextify(RClick(a.attr("filetype"),a.attr("data-path"),a.find("input").val())); + } + else{ + RClickAll(e); + } + } + }); + + //每页行数 + $(".showRow").change(function(){ + setCookie('showRow',$(this).val()); + GetFiles(p); + }); + PathPlaceBtn(rdata.PATH); + }); + //setTimeout(function(){getCookie('path');},200); +} +//统计选择数量 +function totalFile(){ + var el = $("input[name='id']"); + var len = el.length; + var count = 0; + for(var i=0;i 1){ + BatchTools = '\ + \ + \ + \ + ' + $("#Batch").html(BatchTools); + }else{ + $("#Batch").html(BatchTools); + //setCookie('BatchSelected', null); + } +} + +//滚动条事件 +$(window).scroll(function () { + if($(window).scrollTop() > 16){ + $("#tipTools").css({"position":"fixed","top":"0","left":"195px","box-shadow":"0 1px 10px 3px #ccc"}); + }else{ + $("#tipTools").css({"position":"absolute","top":"0","left":"0","box-shadow":"none"}); + } +}); +$("#tipTools").width($(".file-box").width()); +$("#PathPlaceBtn").width($(".file-box").width()-700); +$("#DirPathPlace input").width($(".file-box").width()-700); +if($(window).width()<1160){ + $("#PathPlaceBtn").width(290); +} +window.onresize = function(){ + $("#tipTools").width($(".file-box").width()-30); + $("#PathPlaceBtn").width($(".file-box").width()-700); + $("#DirPathPlace input").width($(".file-box").width()-700); + if($(window).width()<1160){ + $("#PathPlaceBtn,#DirPathPlace input").width(290); + } + PathLeft(); + IsDiskWidth() +} + +//批量操作 +function Batch(type,access){ + var path = $("#DirPathPlace input").val(); + var el = document.getElementsByTagName('input'); + var len = el.length; + var data='path='+path+'&type='+type; + var name = 'data'; + + var oldType = getCookie('BatchPaste'); + + for(var i=0;i"+lan.public.the+"",{icon:16,time:0,shade: [0.3, '#000']}); + setTimeout(function(){getSpeed('.myspeed');},1000); + $.post('files?action=SetBatchData',data,function(rdata){ + layer.close(myloadT); + GetFiles(path); + layer.msg(rdata.msg,{icon:1}); + }); +} + +//批量粘贴 +function BatchPaste(){ + var path = $("#DirPathPlace input").val(); + var type = getCookie('BatchPaste'); + var data = 'type='+type+'&path='+path; + + $.post('/files?action=CheckExistsFiles',{dfile:path},function(result){ + if(result.length > 0){ + var tbody = ''; + for(var i=0;i'+ToSize(result[i].size)+''+getLocalTime(result[i].mtime)+''; + } + var mbody = '
\ + '+tbody+'\ +
文件名大小最后修改时间
'; + SafeMessage('即将覆盖以下文件',mbody,function(){ + BatchPasteTo(data,path); + }); + $(".layui-layer-page").css("width","500px"); + }else{ + BatchPasteTo(data,path); + } + }); +} + +function BatchPasteTo(data,path){ + myloadT = layer.msg("
"+lan.public.the+"
",{icon:16,time:0,shade: [0.3, '#000']}); + setTimeout(function(){getSpeed('.myspeed');},1000); + $.post('files?action=BatchPaste',data,function(rdata){ + layer.close(myloadT); + setCookie('BatchSelected', null); + GetFiles(path); + layer.msg(rdata.msg,{icon:1}); + }); +} + + +//取扩展名 +function GetExtName(fileName){ + 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','flv','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','folder-empty','folder-unempty','fromchromefolder','documentfolder','fromphonefolder','mix','musicfolder','picturefolder','videofolder','sefolder','access','mdb','accdb','sql','c','cpp','cs','js','fla','flv','htm','html','java','log','mht','php','url','xml','ai','bmp','cdr','gif','ico','jpeg','jpg','JPG','png','psd','webp','ape','avi','flv','mkv','mov','mp3','mp4','mpeg','mpg','rm','rmvb','swf','wav','webm','wma','wmv','doc','docm','dotx','dotm','dot','rtf','docx','pdf','fdf','ppt','pptm','pot','potm','pptx','txt','xls','csv','xlsm','xlsb','xlsx','7z','gz','cab','iso','rar','zip','bt','file','apk','css']; + var extLastName = extArr[extArr.length - 1]; + for(var i=0; i tr").hover(function(){ + $(this).addClass("hover"); + },function(){ + $(this).removeClass("hover"); + }).click(function(){ + $(this).addClass("on").siblings().removeClass("on"); + }) +} +//取文件名 +function GetFileName(fileNameFull) { + var pName = fileNameFull.split('/'); + return pName[pName.length - 1]; +} +//取磁盘 +function GetDisk() { + var LBody = ''; + $.get('/system?action=GetDiskInfo', function(rdata) { + for (var i = 0; i < rdata.length; i++) { + LBody += " " + (rdata[i].path=='/'?lan.files.path_root:rdata[i].path) + "(" + rdata[i].size[2] + ")"; + } + var trash = ' '+lan.files.recycle_bin_title+''; + $("#comlist").html(LBody+trash); + IsDiskWidth(); + }); +} + +//返回上一级 +function BackDir() { + var str = $("#DirPathPlace input").val().replace('//','/'); + if(str.substr(str.length-1,1) == '/'){ + str = str.substr(0,str.length-1); + } + var Path = str.split("/"); + var back = '/'; + if (Path.length > 2) { + var count = Path.length - 1; + for (var i = 0; i < count; i++) { + back += Path[i] + '/'; + } + if(back.substr(back.length-1,1) == '/'){ + back = back.substr(0,back.length-1); + } + GetFiles(back); + } else { + back += Path[0]; + GetFiles(back); + } + setTimeout('PathPlaceBtn(getCookie("Path"));',200); +} +//新建文件 +function CreateFile(type, path) { + if (type == 1) { + var fileName = $("#newFileName").val(); + layer.msg(lan.public.the, { + icon: 16, + time: 10000 + }); + $.post('/files?action=CreateFile', 'path=' + encodeURIComponent(path + '/' + fileName), function(rdata) { + layer.closeAll(); + layer.msg(rdata.msg, { + icon: rdata.status ? 1 : 2 + }); + if(rdata.status){ + GetFiles($("#DirPathPlace input").val()); + OnlineEditFile(0,path + '/' + fileName); + } + }); + return; + } + layer.open({ + type: 1, + shift: 5, + closeBtn: 2, + area: '320px', + title: lan.files.new_empty_file, + content: '
\ +
\ + \ +
\ +
\ + \ + \ +
\ +
' + }); + $("#newFileName").focus().keyup(function(e){ + if(e.keyCode == 13) $("#CreateFileBtn").click(); + }); +} +//新建目录 +function CreateDir(type, path) { + if (type == 1) { + var dirName = $("#newDirName").val(); + layer.msg(lan.public.the, { + icon: 16, + time: 10000 + }); + $.post('/files?action=CreateDir', 'path=' + encodeURIComponent(path + '/' + dirName), function(rdata) { + layer.closeAll(); + layer.msg(rdata.msg, { + icon: rdata.status ? 1 : 2 + }); + GetFiles($("#DirPathPlace input").val()); + }); + return; + } + layer.open({ + type: 1, + shift: 5, + closeBtn: 2, + area: '320px', + title: lan.files.new_dir, + content: '
\ +
\ + \ +
\ +
\ + \ + \ +
\ +
' + }); + $("#newDirName").focus().keyup(function(e){ + if(e.keyCode == 13) $("#CreateDirBtn").click(); + }); +} + +//删除文件 +function DeleteFile(fileName){ + layer.confirm(lan.get('recycle_bin_confirm',[fileName]),{title:lan.files.del_file,closeBtn:2,icon:3},function(){ + layer.msg(lan.public.the,{icon:16,time:0,shade: [0.3, '#000']}); + $.post('/files?action=DeleteFile', 'path=' + encodeURIComponent(fileName), function(rdata) { + layer.closeAll(); + layer.msg(rdata.msg, { + icon: rdata.status ? 1 : 2 + }); + GetFiles($("#DirPathPlace input").val()); + }); + }); +} + +//删除目录 +function DeleteDir(dirName){ + layer.confirm(lan.get('recycle_bin_confirm_dir',[dirName]),{title:lan.files.del_dir,closeBtn:2,icon:3},function(){ + layer.msg(lan.public.the,{icon:16,time:0,shade: [0.3, '#000']}); + $.post('/files?action=DeleteDir', 'path=' + encodeURIComponent(dirName), function(rdata) { + layer.closeAll(); + layer.msg(rdata.msg, { + icon: rdata.status ? 1 : 2 + }); + GetFiles($("#DirPathPlace input").val()); + }); + }); +} +//批量删除文件 +function AllDeleteFileSub(data,path){ + layer.confirm(lan.files.del_all_msg,{title:lan.files.del_all_file,closeBtn:2,icon:3},function(){ + layer.msg("
"+lan.public.the+"
",{icon:16,time:0,shade: [0.3, '#000']}); + setTimeout(function(){getSpeed('.myspeed');},1000); + $.post('files?action=SetBatchData',data,function(rdata){ + layer.closeAll(); + GetFiles(path); + layer.msg(rdata.msg,{icon:1}); + }); + }); +} + +//重载文件列表 +function ReloadFiles(){ + setInterval(function(){ + var path = $("#DirPathPlace input").val(); + GetFiles(path); + },3000); +} + +//下载文件 +function DownloadFile(action){ + + if(action == 1){ + var fUrl = $("#mUrl").val(); + fUrl = encodeURIComponent(fUrl); + fpath = $("#dpath").val(); + fname = encodeURIComponent($("#dfilename").val()); + layer.closeAll(); + layer.msg(lan.files.down_task,{time:0,icon:16,shade: [0.3, '#000']}); + $.post('/files?action=DownloadFile','path='+fpath+'&url='+fUrl+'&filename='+fname,function(rdata){ + layer.closeAll(); + GetFiles(fpath); + GetTaskCount(); + layer.msg(rdata.msg,{icon:rdata.status?1:2}); + }); + return; + } + var path = $("#DirPathPlace input").val(); + layer.open({ + type: 1, + shift: 5, + closeBtn: 2, + area: '500px', + title: lan.files.down_title, + content: '
\ +
\ + '+lan.files.down_url+':\ +
\ +
\ + '+lan.files.down_to+':\ +
\ +
\ + '+lan.files.file_name+':\ +
\ +
\ + \ + \ +
\ +
' + }); + fly("dlok"); + $("#mUrl").keyup(function(){ + durl = $(this).val() + tmp = durl.split('/') + $("#dfilename").val(tmp[tmp.length-1]) + }); +} + + +//执行SHELL +function ExecShell(action){ + if(action == 1){ + var path = $("#DirPathPlace input").val(); + var exec = encodeURIComponent($("#mExec").val()); + $.post('/files?action=ExecShell','path='+path+'&shell='+exec,function(rdata){ + if(rdata.status){ + $("#mExec").val(''); + GetShellEcho(); + } + else{ + layer.msg(rdata.msg,{icon:rdata.status?1:2}); + } + + }); + return; + } + layer.open({ + type: 1, + shift: 5, + closeBtn: 2, + area: ['70%','600px'], + title: lan.files.shell_title, + content: '
\ +
\ +
\ + '+lan.files.shell_go+'\ +
\ +
' + }); + setTimeout(function(){ + outTimeGet(); + },1000); + +} + +var outTime = null; +//取SHELL输出 +function outTimeGet(){ + outTime = setInterval(function(){ + if(!$("#mExec").attr('name')){ + clearInterval(outTime); + return; + } + GetShellEcho(); + },1000); +} + +function GetShellEcho(){ + $.post('/files?action=GetExecShellMsg','',function(rdata){ + $("#Result").html(rdata); + $(".shellcode").scrollTop($(".shellcode")[0].scrollHeight); + }); +} + +//重命名 +function ReName(type, fileName) { + if (type == 1) { + var path = $("#DirPathPlace input").val(); + var newFileName = encodeURIComponent(path + '/' + $("#newFileName").val()); + var oldFileName = encodeURIComponent(path + '/' + fileName); + layer.msg(lan.public.the, { + icon: 16, + time: 10000 + }); + $.post('/files?action=MvFile', 'sfile=' + oldFileName + '&dfile=' + newFileName, function(rdata) { + layer.closeAll(); + layer.msg(rdata.msg, { + icon: rdata.status ? 1 : 2 + }); + GetFiles(path); + }); + return; + } + layer.open({ + type: 1, + shift: 5, + closeBtn: 2, + area: '320px', + title: lan.files.file_menu_rename, + content: '
\ +
\ + \ +
\ +
\ + \ + \ +
\ +
' + }); + $("#newFileName").focus().keyup(function(e){ + if(e.keyCode == 13) $("#ReNameBtn").click(); + }); +} +//剪切 +function CutFile(fileName) { + var path = $("#DirPathPlace input").val(); + setCookie('cutFileName', fileName); + setCookie('copyFileName', null); + layer.msg(lan.files.mv_ok, { + icon: 1, + time: 1 + }); + GetFiles(path); +} +//复制 +function CopyFile(fileName) { + var path = $("#DirPathPlace input").val(); + setCookie('copyFileName', fileName); + setCookie('cutFileName', null); + layer.msg(lan.files.copy_ok, { + icon: 1, + time: 1 + }); + GetFiles(path); +} +//粘贴 +function PasteFile(fileName) { + var path = $("#DirPathPlace input").val(); + var copyName = getCookie('copyFileName'); + var cutName = getCookie('cutFileName'); + var filename = copyName; + if(cutName != 'null' && cutName != undefined) filename=cutName; + filename = filename.split('/').pop(); + $.post('/files?action=CheckExistsFiles',{dfile:path,filename:filename},function(result){ + if(result.length > 0){ + var tbody = ''; + for(var i=0;i'+ToSize(result[i].size)+''+getLocalTime(result[i].mtime)+''; + } + var mbody = '
\ + '+tbody+'\ +
文件名大小最后修改时间
'; + SafeMessage('即将覆盖以下文件',mbody,function(){ + PasteTo(path,copyName,cutName,fileName); + }); + }else{ + PasteTo(path,copyName,cutName,fileName); + } + }); +} + + +function PasteTo(path,copyName,cutName,fileName){ + if (copyName != 'null' && copyName != undefined) { + layer.msg(lan.files.copy_the, { + icon: 16, + time: 0,shade: [0.3, '#000'] + }); + $.post('/files?action=CopyFile', 'sfile=' + encodeURIComponent(copyName) + '&dfile=' + encodeURIComponent(path +'/'+ fileName), function(rdata) { + layer.closeAll(); + layer.msg(rdata.msg, { + icon: rdata.status ? 1 : 2 + }); + GetFiles(path); + }); + setCookie('copyFileName', null); + setCookie('cutFileName', null); + return; + } + + if (cutName != 'null' && cutName != undefined) { + layer.msg(lan.files.mv_the, { + icon: 16, + time: 0,shade: [0.3, '#000'] + }); + $.post('/files?action=MvFile', 'sfile=' + encodeURIComponent(cutName) + '&dfile=' + encodeURIComponent(path + '/'+fileName), function(rdata) { + layer.closeAll(); + layer.msg(rdata.msg, { + icon: rdata.status ? 1 : 2 + }); + GetFiles(path); + }); + setCookie('copyFileName', null); + setCookie('cutFileName', null); + } +} + + +//压缩目录 +function Zip(dirName,submits) { + var path = $("#DirPathPlace input").val(); + if(submits != undefined){ + if(dirName.indexOf(',') == -1){ + tmp = $("#sfile").val().split('/'); + sfile = encodeURIComponent(tmp[tmp.length-1]); + }else{ + sfile = encodeURIComponent(dirName); + } + + dfile = encodeURIComponent($("#dfile").val()); + layer.closeAll(); + layer.msg(lan.files.zip_the, {icon: 16,time: 0,shade: [0.3, '#000']}); + $.post('/files?action=Zip', 'sfile=' + sfile + '&dfile=' + dfile + '&type=tar&path='+encodeURIComponent(path), function(rdata) { + layer.closeAll(); + if(rdata == null || rdata == undefined){ + layer.msg(lan.files.zip_ok,{icon:1}); + GetFiles(path) + ReloadFiles(); + return; + } + layer.msg(rdata.msg, {icon: rdata.status ? 1 : 2}); + if(rdata.status) GetFiles(path); + }); + return + } + + param = dirName; + if(dirName.indexOf(',') != -1){ + tmp = path.split('/') + dirName = path + '/' + tmp[tmp.length-1] + } + + layer.open({ + type: 1, + shift: 5, + closeBtn: 2, + area: '650px', + title: lan.files.zip_title, + content: '
' + +'
' + +'' + +''+lan.files.zip_to+'' + +'
' + +'
' + +'' + +'' + +'
' + +'
' + }); + + setTimeout(function(){ + $("#dfile").change(function(){ + var dfile = $(this).val() + tmp = dfile.split('.'); + if(tmp[tmp.length-1] != 'gz'){ + var path = $("#DirPathPlace input").val(); + tmp = path.split('/'); + dfile += '/' + tmp[tmp.length-1] + '.tar.gz' + $(this).val(dfile.replace(/\/\//g,'/')) + } + }); + },100); + +} + +//解压目录 +function UnZip(fileName,type) { + var path = $("#DirPathPlace input").val(); + if(type.length ==3){ + var sfile = encodeURIComponent($("#sfile").val()); + var dfile = encodeURIComponent($("#dfile").val()); + var password = encodeURIComponent($("#unpass").val()); + coding = $("select[name='coding']").val(); + layer.closeAll(); + layer.msg(lan.files.unzip_the, {icon: 16,time: 0,shade: [0.3, '#000']}); + $.post('/files?action=UnZip', 'sfile=' + sfile + '&dfile=' + dfile +'&type=' + type + '&coding=' + coding + '&password=' + password, function(rdata) { + layer.closeAll(); + layer.msg(rdata.msg, {icon: rdata.status ? 1 : 2}); + GetFiles(path); + }); + return + } + + type = (type == 1) ? 'tar':'zip' + var umpass = ''; + if(type == 'zip'){ + umpass = '
'+lan.files.zip_pass_title+'
' + } + layer.open({ + type: 1, + shift: 5, + closeBtn: 2, + area: '490px', + title: lan.files.unzip_title, + content: '
' + +'
' + +''+lan.files.unzip_name+'
' + +'
'+lan.files.unzip_to+'
' + umpass + +'
'+lan.files.unzip_coding+'' + +'
' + +'
' + +'' + +'' + +'
' + +'
' + }); +} + +//是否压缩文件 +function isZip(fileName){ + var ext = fileName.split('.'); + var extName = ext[ext.length-1].toLowerCase(); + if( extName == 'zip') return 0; + if( extName == 'gz' || extName == 'tgz') return 1; + return -1; +} + +//是否文本文件 +function isText(fileName){ + var exts = ['rar','zip','tar.gz','gz','iso','xsl','doc','xdoc','jpeg','jpg','png','gif','bmp','tiff','exe','so','7z','bz']; + return isExts(fileName,exts)?false:true; +} + +//是否图片文件 +function isImage(fileName){ + var exts = ['jpg','jpeg','png','bmp','gif','tiff','ico']; + return isExts(fileName,exts); +} + +//是否为指定扩展名 +function isExts(fileName,exts){ + var ext = fileName.split('.'); + if(ext.length < 2) return false; + var extName = ext[ext.length-1].toLowerCase(); + for(var i=0;i' + }); + $(".layui-layer").css("top", "30%"); +} + +//获取文件数据 +function GetFileBytes(fileName, fileSize){ + window.open('/download?filename='+encodeURIComponent(fileName)); +} + + +//上传文件 +function UploadFiles(){ + var path = $("#DirPathPlace input").val()+"/"; + layer.open({ + type:1, + closeBtn: 2, + title:lan.files.up_title, + area: ['500px','500px'], + shadeClose:false, + content:'
\ + \ + \ + \ + \ + \ + '+lan.files.up_coding+':\ + \ + \ + \ +
    ' + }); + UploadStart(); +} + +//设置权限 +function SetChmod(action,fileName){ + if(action == 1){ + var chmod = $("#access").val(); + var chown = $("#chown").val(); + var data = 'filename='+ encodeURIComponent(fileName)+'&user='+chown+'&access='+chmod; + var loadT = layer.msg(lan.public.config,{icon:16,time:0,shade: [0.3, '#000']}); + $.post('files?action=SetFileAccess',data,function(rdata){ + layer.close(loadT); + if(rdata.status) layer.closeAll(); + layer.msg(rdata.msg,{icon:rdata.status?1:2}); + var path = $("#DirPathPlace input").val(); + GetFiles(path) + }); + return; + } + + var toExec = fileName == lan.files.all?'Batch(3,1)':'SetChmod(1,\''+fileName+'\')'; + + $.post('/files?action=GetFileAccess','filename='+encodeURIComponent(fileName),function(rdata){ + layer.open({ + type:1, + closeBtn: 2, + title: lan.files.set_auth + '['+fileName+']', + area: '400px', + shadeClose:false, + content:'
    \ +
    \ + '+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+'\ +
    \ +
    \ + \ + \ +
    \ +
    ' + }); + + onAccess(); + $("#access").keyup(function(){ + onAccess(); + }); + + $("input[type=checkbox]").change(function(){ + var idName = ['owner','group','public']; + var onacc = ''; + for(var n=0;n idName.length) continue; + if(onacc > 7) $("#access").val(access.substr(0,access.length-1)); + switch(onacc){ + case '1': + $("#"+idName[i]+"_x").prop('checked',true); + break; + case '2': + $("#"+idName[i]+"_w").prop('checked',true); + break; + case '3': + $("#"+idName[i]+"_x").prop('checked',true); + $("#"+idName[i]+"_w").prop('checked',true); + break; + case '4': + $("#"+idName[i]+"_r").prop('checked',true); + break; + case '5': + $("#"+idName[i]+"_r").prop('checked',true); + $("#"+idName[i]+"_x").prop('checked',true); + break; + case '6': + $("#"+idName[i]+"_r").prop('checked',true); + $("#"+idName[i]+"_w").prop('checked',true); + break; + case '7': + $("#"+idName[i]+"_r").prop('checked',true); + $("#"+idName[i]+"_w").prop('checked',true); + $("#"+idName[i]+"_x").prop('checked',true); + break; + } + } +} +//右键菜单 +function RClick(type,path,name){ + var displayZip = isZip(type); + var options = {items:[ + {text: lan.files.file_menu_copy, onclick: function() {CopyFile(path)}}, + {text: lan.files.file_menu_mv, onclick: function() {CutFile(path)}}, + {text: lan.files.file_menu_rename, onclick: function() {ReName(0,name)}}, + {text: lan.files.file_menu_auth, onclick: function() {SetChmod(0,path)}}, + {text: lan.files.file_menu_zip, onclick: function() {Zip(path)}} + + ]}; + if(type == "dir"){ + options.items.push({text: lan.files.file_menu_del, onclick: function() {DeleteDir(path)}}); + } + else if(isText(type)){ + options.items.push({text: lan.files.file_menu_edit, onclick: function() {OnlineEditFile(0,path)}},{text: lan.files.file_menu_down, onclick: function() {GetFileBytes(path)}},{text: lan.files.file_menu_del, onclick: function() {DeleteFile(path)}}); + } + else if(displayZip != -1){ + options.items.push({text: lan.files.file_menu_unzip, onclick: function() {UnZip(path,displayZip)}},{text: lan.files.file_menu_down, onclick: function() {GetFileBytes(path)}},{text: lan.files.file_menu_del, onclick: function() {DeleteFile(path)}}); + } + else if(isImage(type)){ + options.items.push({text: lan.files.file_menu_img, onclick: function() {GetImage(path)}},{text: lan.files.file_menu_down, onclick: function() {GetFileBytes(path)}},{text: lan.files.file_menu_del, onclick: function() {DeleteFile(path)}}); + } + else{ + options.items.push({text: lan.files.file_menu_down, onclick: function() {GetFileBytes(path)}},{text: lan.files.file_menu_del, onclick: function() {DeleteFile(path)}}); + } + return options; +} +//右键批量操作 +function RClickAll(e){ + var menu = $("#rmenu"); + var windowWidth = $(window).width(), + windowHeight = $(window).height(), + menuWidth = menu.outerWidth(), + menuHeight = menu.outerHeight(), + x = (menuWidth + e.clientX < windowWidth) ? e.clientX : windowWidth - menuWidth, + y = (menuHeight + e.clientY < windowHeight) ? e.clientY : windowHeight - menuHeight; + + menu.css('top', y) + .css('left', x) + .css('position', 'fixed') + .css("z-index","1") + .show(); +} +//取目录大小 +function GetPathSize(){ + var path = encodeURIComponent($("#DirPathPlace input").val()); + layer.msg("正在计算,请稍候",{icon:16,time:0,shade: [0.3, '#000']}) + $.post("/files?action=GetDirSize","path="+path,function(rdata){ + layer.closeAll(); + $("#pathSize").text(rdata) + }) +} +$("body").not(".def-log").click(function(){ + $("#rmenu").hide() +}); +//指定路径 +$("#DirPathPlace input").keyup(function(e){ + if(e.keyCode == 13) { + GetFiles($(this).val()); + } +}); +function PathPlaceBtn(path){ + var html = ''; + var title = ''; + var Dpath = path; + if(path == '/'){ + html ='
  • '+lan.files.path_root+'
  • '; + } + else{ + Dpath = path.split("/"); + for(var i = 0; i'+Dpath[i]+''; + } + } + html = '
      '+html+'
    '; + $("#PathPlaceBtn").html(html); + $("#PathPlaceBtn ul li a").click(function(e){ + var Gopath = $(this).attr("title"); + if(Gopath.length>1){ + if(Gopath.substr(Gopath.length-1,Gopath.length) =='/'){ + Gopath = Gopath.substr(0,Gopath.length-1); + } + } + GetFiles(Gopath); + e.stopPropagation(); + }); + PathLeft(); +} +//计算当前目录偏移 +function PathLeft(){ + var UlWidth = $("#PathPlaceBtn ul").width(); + var SpanPathWidth = $("#PathPlaceBtn").width() - 50; + var Ml = UlWidth - SpanPathWidth; + if(UlWidth > SpanPathWidth ){ + $("#PathPlaceBtn ul").css("left",-Ml) + } + else{ + $("#PathPlaceBtn ul").css("left",0) + } +} +//路径快捷点击 +$("#PathPlaceBtn").on("click", function(e){ + if($("#DirPathPlace").is(":hidden")){ + $("#DirPathPlace").css("display","inline"); + $("#DirPathPlace input").focus(); + $(this).hide(); + }else{ + $("#DirPathPlace").hide(); + $(this).css("display","inline"); + } + $(document).one("click", function(){ + $("#DirPathPlace").hide(); + $("#PathPlaceBtn").css("display","inline"); + }); + e.stopPropagation(); +}); +$("#DirPathPlace").on("click", function(e){ + e.stopPropagation(); +}); diff --git a/task.py b/task.py index 0700a534d..2b50af4fa 100755 --- a/task.py +++ b/task.py @@ -14,6 +14,7 @@ reload(sys) sys.setdefaultencoding('utf-8') import db import public +import time global pre, timeoutCount, logPath, isTask, oldEdate, isCheck @@ -327,6 +328,7 @@ def systemTask(): count += 1 except Exception, ex: print str(ex) + import time time.sleep(30) systemTask()