forked from aaPanel/BaoTa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
files.py
2516 lines (2270 loc) · 97.1 KB
/
files.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding:utf-8
# +-------------------------------------------------------------------
# | 宝塔Linux面板
# +-------------------------------------------------------------------
# | Copyright (c) 2015-2016 宝塔软件(http://bt.cn) All rights reserved.
# +-------------------------------------------------------------------
# | Author: hwliang <[email protected]>
# +-------------------------------------------------------------------
import sys
import os
import public
import time
import json
import pwd
import cgi
import shutil
import re
from BTPanel import session, request
class files:
run_path = None
download_list = None
download_is_rm = None
# 检查敏感目录
def CheckDir(self, path):
path = path.replace('//', '/')
if path[-1:] == '/':
path = path[:-1]
nDirs = ('',
'/',
'/*',
'/www',
'/root',
'/boot',
'/bin',
'/etc',
'/home',
'/dev',
'/sbin',
'/var',
'/usr',
'/tmp',
'/sys',
'/proc',
'/media',
'/mnt',
'/opt',
'/lib',
'/srv',
'/selinux',
'/www/server',
'/www/server/data',
public.GetConfigValue('logs_path'),
public.GetConfigValue('setup_path'))
return not path in nDirs
# 网站文件操作前置检测
def site_path_check(self, get):
try:
if not 'site_id' in get:
return True
if not self.run_path:
self.run_path, self.path, self.site_name = self.GetSiteRunPath(
get.site_id)
if 'path' in get:
if get.path.find(self.path) != 0:
return False
if 'sfile' in get:
if get.sfile.find(self.path) != 0:
return False
if 'dfile' in get:
if get.dfile.find(self.path) != 0:
return False
return True
except:
return True
# 网站目录后续安全处理
def site_path_safe(self, get):
try:
if not 'site_id' in get:
return True
run_path, path, site_name = self.GetSiteRunPath(get.site_id)
if not os.path.exists(run_path):
os.makedirs(run_path)
ini_path = run_path + '/.user.ini'
if os.path.exists(ini_path):
return True
sess_path = '/www/php_session/%s' % site_name
if not os.path.exists(sess_path):
os.makedirs(sess_path)
ini_conf = '''open_basedir={}/:/tmp/:/proc/:{}/
session.save_path={}/
session.save_handler = files'''.format(path, sess_path, sess_path)
public.writeFile(ini_path, ini_conf)
public.ExecShell("chmod 644 %s" % ini_path)
public.ExecShell("chdir +i %s" % ini_path)
return True
except:
return False
# 取当站点前运行目录
def GetSiteRunPath(self, site_id):
try:
find = public.M('sites').where(
'id=?', (site_id,)).field('path,name').find()
siteName = find['name']
sitePath = find['path']
if public.get_webserver() == 'nginx':
filename = '/www/server/panel/vhost/nginx/' + siteName + '.conf'
if os.path.exists(filename):
conf = public.readFile(filename)
rep = '\s*root\s+(.+);'
tmp1 = re.search(rep, conf)
if tmp1:
path = tmp1.groups()[0]
else:
filename = '/www/server/panel/vhost/apache/' + siteName + '.conf'
if os.path.exists(filename):
conf = public.readFile(filename)
rep = '\s*DocumentRoot\s*"(.+)"\s*\n'
tmp1 = re.search(rep, conf)
if tmp1:
path = tmp1.groups()[0]
return path, sitePath, siteName
except:
return sitePath, sitePath, siteName
# 检测文件名
def CheckFileName(self, filename):
nots = ['\\', '&', '*', '|', ';', '"', "'", '<', '>']
if filename.find('/') != -1:
filename = filename.split('/')[-1]
for n in nots:
if n in filename:
return False
return True
# 名称输出过滤
def xssencode(self, text):
list = ['<', '>']
ret = []
for i in text:
if i in list:
i = ''
ret.append(i)
str_convert = ''.join(ret)
if sys.version_info[0] == 3:
import html
text2 = html.escape(str_convert, quote=True)
else:
text2 = cgi.escape(str_convert, quote=True)
reps = {'&':'&'}
for rep in reps.keys():
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
from BTPanel import request
if sys.version_info[0] == 2:
get.path = get.path.encode('utf-8')
if not os.path.exists(get.path):
os.makedirs(get.path)
f = request.files['zunfile']
filename = os.path.join(get.path, f.filename)
if sys.version_info[0] == 2:
filename = filename.encode('utf-8')
s_path = get.path
if os.path.exists(filename):
s_path = filename
p_stat = os.stat(s_path)
f.save(filename)
os.chown(filename, p_stat.st_uid, p_stat.st_gid)
os.chmod(filename, p_stat.st_mode)
public.WriteLog('TYPE_FILE', 'FILE_UPLOAD_SUCCESS',
(filename, get['path']))
return public.returnMsg(True, 'FILE_UPLOAD_SUCCESS')
def f_name_check(self,filename):
'''
@name 文件名检测2
@author hwliang<2021-03-16>
@param filename<string> 文件名
@return bool
'''
f_strs = [';','&','<','>']
for fs in f_strs:
if filename.find(fs) != -1:
return False
return True
# 上传前检查文件是否存在
def upload_file_exists(self,args):
'''
@name 上传前检查文件是否存在
@author hwliang<2021-11-3>
@param filename<string> 文件名
@return dict
'''
filename = args.filename.strip()
if not os.path.exists(filename):
return public.returnMsg(False,'指定文件不存在')
file_info = {}
_stat = os.stat(filename)
file_info['size'] = _stat.st_size
file_info['mtime'] = int(_stat.st_mtime)
file_info['isfile'] = os.path.isfile(filename)
return public.returnMsg(True,file_info)
def get_real_len(self,string):
'''
@name 获取含中文的字符串字精确长度
@author hwliang<2021-11-3>
@param string<str>
@return int
'''
real_len = len(string)
for s in string:
if '\u2E80' <= s <= '\uFE4F':
real_len += 1
return real_len
# 上传文件2
def upload(self, args):
if not 'f_name' in args:
args.f_name = request.form.get('f_name')
args.f_path = request.form.get('f_path')
args.f_size = request.form.get('f_size')
args.f_start = request.form.get('f_start')
if sys.version_info[0] == 2:
args.f_name = args.f_name.encode('utf-8')
args.f_path = args.f_path.encode('utf-8')
try:
if self.get_real_len(args.f_name) > 128: return public.returnMsg(False,'文件名长度超过128个字节')
except:
pass
if not self.f_name_check(args.f_name): return public.returnMsg(False,'文件名中包含特殊字符!')
if args.f_path == '/':
return public.returnMsg(False,'不能直接上传文件到系统根目录!')
if args.f_name.find('./') != -1 or args.f_path.find('./') != -1:
return public.returnMsg(False, '错误的参数')
if not os.path.exists(args.f_path):
os.makedirs(args.f_path, 493)
if not 'dir_mode' in args or not 'file_mode' in args:
self.set_mode(args.f_path)
save_path = os.path.join(
args.f_path, args.f_name + '.' + str(int(args.f_size)) + '.upload.tmp')
d_size = 0
if os.path.exists(save_path):
d_size = os.path.getsize(save_path)
if d_size != int(args.f_start):
return d_size
try:
f = open(save_path, 'ab')
if 'b64_data' in args:
import base64
b64_data = base64.b64decode(args.b64_data)
f.write(b64_data)
else:
upload_files = request.files.getlist("blob")
for tmp_f in upload_files:
f.write(tmp_f.read())
f.close()
except Exception as ex:
ex = str(ex)
if ex.find('No space left on device') != -1:
return public.returnMsg(False, '磁盘空间不足')
f_size = os.path.getsize(save_path)
if f_size != int(args.f_size):
return f_size
new_name = os.path.join(args.f_path, args.f_name)
if os.path.exists(new_name):
if new_name.find('.user.ini') != -1:
public.ExecShell("chattr -i " + new_name)
try:
os.remove(new_name)
except:
public.ExecShell("rm -f %s" % new_name)
os.renames(save_path, new_name)
if 'dir_mode' in args and 'file_mode' in args:
mode_tmp1 = args.dir_mode.split(',')
public.set_mode(args.f_path, mode_tmp1[0])
public.set_own(args.f_path, mode_tmp1[1])
mode_tmp2 = args.file_mode.split(',')
public.set_mode(new_name, mode_tmp2[0])
public.set_own(new_name, mode_tmp2[1])
else:
self.set_mode(new_name)
if new_name.find('.user.ini') != -1:
public.ExecShell("chattr +i " + new_name)
public.WriteLog('TYPE_FILE', 'FILE_UPLOAD_SUCCESS',
(args.f_name, args.f_path))
return public.returnMsg(True, '上传成功!')
# 设置文件和目录权限
def set_mode(self, path):
s_path = os.path.dirname(path)
p_stat = os.stat(s_path)
os.chown(path, p_stat.st_uid, p_stat.st_gid)
os.chmod(path, p_stat.st_mode)
# 是否包含composer.json
def is_composer_json(self,path):
if os.path.exists(path + '/composer.json'):
return '1'
return '0'
def __check_favorite(self,filepath,favorites_info):
for favorite in favorites_info:
if filepath == favorite['path']:
return '1'
return '0'
def __check_share(self,filename):
my_table = 'download_token'
result = public.M(my_table).where('filename=?',(filename,)).getField('id')
if result:
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'):
# return public.returnMsg(False,'错误的参数!')
get.path = '/www/wwwroot'
if sys.version_info[0] == 2:
get.path = get.path.encode('utf-8')
if get.path == '':
get.path = '/www'
# 转换包含~的路径
if get.path.find('~') != -1:
get.path = os.path.expanduser(get.path)
get.path = self.xssdecode(get.path)
if not os.path.exists(get.path):
get.path = '/www/wwwroot'
#return public.ReturnMsg(False, '指定目录不存在!')
if get.path == '/www/Recycle_bin':
return public.returnMsg(False, '此为回收站目录,请在右上角按【回收站】按钮打开')
if not os.path.isdir(get.path):
get.path = os.path.dirname(get.path)
if not os.path.isdir(get.path):
return public.returnMsg(False, '这不是一个目录!')
import pwd
dirnames = []
filenames = []
search = None
if hasattr(get, 'search'):
search = get.search.strip().lower()
if hasattr(get, 'all'):
return self.SearchFiles(get)
# 包含分页类
import page
# 实例化分页类
page = page.Page()
info = {}
info['count'] = self.GetFilesCount(get.path, search)
info['row'] = 100
if 'disk' in get:
if get.disk == 'true': info['row'] = 2000
if 'share' in get and get.share:
info['row'] = 5000
info['p'] = 1
if hasattr(get, 'p'):
try:
info['p'] = int(get['p'])
except:
info['p'] = 1
info['uri'] = {}
info['return_js'] = ''
if hasattr(get, 'tojs'):
info['return_js'] = get.tojs
if hasattr(get, 'showRow'):
info['row'] = int(get.showRow)
# 获取分页数据
data = {}
data['PAGE'] = page.GetPage(info, '1,2,3,4,5,6,7,8')
i = 0
n = 0
data['STORE'] = self.get_files_store(None)
data['FILE_RECYCLE'] = os.path.exists('data/recycle_bin.pl')
if not hasattr(get, 'reverse'):
for filename in os.listdir(get.path):
filename = self.xssencode(filename)
if search:
if filename.lower().find(search) == -1:
continue
i += 1
if n >= page.ROW:
break
if i < page.SHIFT:
continue
try:
if sys.version_info[0] == 2:
filename = filename.encode('utf-8')
else:
filename.encode('utf-8')
filePath = get.path+'/'+filename
link = ''
if os.path.islink(filePath):
filePath = os.readlink(filePath)
link = ' -> ' + filePath
if not os.path.exists(filePath):
filePath = get.path + '/' + filePath
if not os.path.exists(filePath):
continue
stat = os.stat(filePath)
accept = str(oct(stat.st_mode)[-3:])
mtime = str(int(stat.st_mtime))
user = ''
try:
user = pwd.getpwuid(stat.st_uid).pw_name
except:
user = str(stat.st_uid)
size = str(stat.st_size)
# 判断文件是否已经被收藏
favorite = self.__check_favorite(filePath,data['STORE'])
if os.path.isdir(filePath):
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(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
except:
continue
data['DIR'] = sorted(dirnames)
data['FILES'] = sorted(filenames)
else:
reverse = bool(get.reverse)
if get.reverse == 'False':
reverse = False
for file_info in self.__list_dir(get.path, get.sort, reverse):
filename = os.path.join(get.path, file_info[0])
if search:
if file_info[0].lower().find(search) == -1:
continue
i += 1
if n >= page.ROW:
break
if i < page.SHIFT:
continue
if not os.path.exists(filename): continue
file_info = self.__format_stat(filename, get.path)
if not file_info: continue
favorite = self.__check_favorite(filename, data['STORE'])
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)
if os.path.isdir(filename):
dirnames.append(r_file)
else:
filenames.append(r_file)
n += 1
data['DIR'] = dirnames
data['FILES'] = filenames
data['PATH'] = str(get.path)
for i in range(len(data['DIR'])):
data['DIR'][i] += ';' + self.get_file_ps( os.path.join(data['PATH'] , data['DIR'][i].split(';')[0]))
for i in range(len(data['FILES'])):
data['FILES'][i] += ';' + self.get_file_ps( os.path.join(data['PATH'] , data['FILES'][i].split(';')[0]))
if hasattr(get, 'disk'):
import system
data['DISK'] = system.system().GetDiskInfo()
return data
def get_file_ps(self,filename):
'''
@name 获取文件或目录备注
@author hwliang<2020-10-22>
@param filename<string> 文件或目录全路径
@return string
'''
ps_path = '/www/server/panel/data/files_ps'
f_key1 = '/'.join((ps_path,public.md5(filename)))
if os.path.exists(f_key1):
return public.readFile(f_key1)
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数据库默认数据目录,请勿删除!',
'/www/server/mysql':'MySQL程序目录',
'/www/server/redis':'Redis程序目录',
'/www/server/mongodb':'MongoDB程序目录',
'/www/server/nvm':'PM2/NVM/NPM程序目录',
'/www/server/pass':'网站BasicAuth认证密码存储目录',
'/www/server/speed':'网站加速数据目录',
'/www/server/docker':'Docker插件程序与数据目录',
'/www/server/total':'网站监控报表数据目录',
'/www/server/btwaf':'WAF防火墙数据目录',
'/www/server/pure-ftpd':'ftp程序目录',
'/www/server/phpmyadmin':'phpMyAdmin程序目录',
'/www/server/rar':'rar扩展库目录,删除后将失去对RAR压缩文件的支持',
'/www/server/stop':'网站停用页面目录,请勿删除!',
'/www/server/nginx':'Nginx程序目录',
'/www/server/apache':'Apache程序目录',
'/www/server/cron':'计划任务脚本与日志目录',
'/www/server/php':'PHP目录,所有PHP版本的解释器都在此目录下',
'/www/server/tomcat':'Tomcat程序目录',
'/www/php_session':'PHP-SESSION隔离目录'
}
if filename in pss: return pss[filename]
return ''
def set_file_ps(self,args):
'''
@name 设置文件或目录备注
@author hwliang<2020-10-22>
@param filename<string> 文件或目录全路径
@param ps_type<int> 备注类型 0.完整路径 1.文件名称
@param ps_body<string> 备注内容
@return dict
'''
filename = args.filename.strip()
ps_type = int(args.ps_type)
ps_body = public.xssencode(args.ps_body)
ps_path = '/www/server/panel/data/files_ps'
if not os.path.exists(ps_path):
os.makedirs(ps_path,384)
if ps_type == 1:
f_name = os.path.basename(filename)
else:
f_name = filename
ps_key = public.md5(f_name)
f_key = '/'.join((ps_path,ps_key))
if ps_body:
public.writeFile(f_key,ps_body)
public.WriteLog('文件管理','设置文件名[{}],备注为: {}'.format(f_name,ps_body))
else:
if os.path.exists(f_key):
os.remove(f_key)
public.WriteLog('文件管理','清除文件备注[{}]'.format(f_name))
return public.returnMsg(True,'设置成功')
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):
'''
@name 获取文件列表,并排序
@author hwliang<2020-08-01>
@param path<string> 路径
@param my_sort<string> 排序字段
@param reverse<bool> 是否降序
@param list
'''
if not os.path.exists(path):
return []
py_v = sys.version_info[0]
tmp_files = []
for f_name in os.listdir(path):
try:
if py_v == 2:
f_name = f_name.encode('utf-8')
else:
f_name.encode('utf-8')
#使用.join拼接效率更高
filename = "/".join((path,f_name))
sort_key = 1
sort_val = None
#此处直接做异常处理比先判断文件是否存在更高效
if my_sort == 'name':
sort_key = 0
elif my_sort == 'size':
sort_val = os.stat(filename).st_size
elif my_sort == 'mtime':
sort_val = os.stat(filename).st_mtime
elif my_sort == 'accept':
sort_val = os.stat(filename).st_mode
elif my_sort == 'user':
sort_val = os.stat(filename).st_uid
except:
continue
#使用list[tuple]排序效率更高
# if f_name and sort_val:
tmp_files.append((f_name,sort_val))
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):
try:
stat = self.__get_stat(filename, path)
if not stat:
return None
tmp_stat = stat.split(';')
file_info = {'name': self.xssencode(tmp_stat[0].replace('/', '')), 'size': int(tmp_stat[1]), 'mtime': int(
tmp_stat[2]), 'accept': int(tmp_stat[3]), 'user': tmp_stat[4], 'link': tmp_stat[5]}
return file_info
except:
return None
def SearchFiles(self, get):
if not hasattr(get, 'path'):
get.path = '/www/wwwroot'
if sys.version_info[0] == 2:
get.path = get.path.encode('utf-8')
if not os.path.exists(get.path):
get.path = '/www'
search = get.search.strip().lower()
my_dirs = []
my_files = []
count = 0
max = 3000
for d_list in os.walk(get.path):
if count >= max:
break
for d in d_list[1]:
if count >= max:
break
d = self.xssencode(d)
if d.lower().find(search) != -1:
filename = d_list[0] + '/' + d
if not os.path.exists(filename):
continue
my_dirs.append(self.__get_stat(filename, get.path))
count += 1
for f in d_list[2]:
if count >= max:
break
f = self.xssencode(f)
if f.lower().find(search) != -1:
filename = d_list[0] + '/' + f
if not os.path.exists(filename):
continue
my_files.append(self.__get_stat(filename, get.path))
count += 1
data = {}
data['DIR'] = sorted(my_dirs)
data['FILES'] = sorted(my_files)
data['PATH'] = str(get.path)
data['PAGE'] = public.get_page(
len(my_dirs) + len(my_files), 1, max, 'GetFiles')['page']
data['STORE'] = self.get_files_store(None)
return data
def __get_stat(self, filename, path=None):
stat = os.stat(filename)
accept = str(oct(stat.st_mode)[-3:])
mtime = str(int(stat.st_mtime))
user = ''
try:
user = pwd.getpwuid(stat.st_uid).pw_name
except:
user = str(stat.st_uid)
size = str(stat.st_size)
link = ''
down_url = self.get_download_id(filename)
if os.path.islink(filename):
link = ' -> ' + os.readlink(filename)
tmp_path = (path + '/').replace('//', '/')
if path and tmp_path != '/':
filename = filename.replace(tmp_path, '',1)
favorite = self.__check_favorite(filename, self.get_files_store(None))
return filename + ';' + size + ';' + mtime + ';' + accept + ';' + user + ';' + link+';'+ down_url+';'+ \
self.is_composer_json(filename)+';'+favorite+';'+self.__check_share(filename)
#获取指定目录下的所有视频或音频文件
def get_videos(self,args):
path = args.path.strip()
v_data = []
if not os.path.exists(path): return v_data
import mimetypes
for fname in os.listdir(path):
try:
filename = os.path.join(path,fname)
if not os.path.exists(filename): continue
if not os.path.isfile(filename): continue
v_tmp = {}
v_tmp['name'] = fname
v_tmp['type'] = mimetypes.guess_type(filename)[0]
v_tmp['size'] = os.path.getsize(filename)
if not v_tmp['type'].split('/')[0] in ['video']:
continue
v_data.append(v_tmp)
except:continue
return sorted(v_data,key=lambda x:x['name'])
# 计算文件数量
def GetFilesCount(self, path, search):
if os.path.isfile(path):
return 1
if not os.path.exists(path):
return 0
i = 0
for name in os.listdir(path):
if search:
if name.lower().find(search) == -1:
continue
i += 1
return i
# 创建文件
def CreateFile(self, get):
if sys.version_info[0] == 2:
get.path = get.path.encode('utf-8').strip()
try:
if get.path[-1] == '.':
return public.returnMsg(False, '文件结尾不建议使用 ".",因为可能存在安全隐患')
if not self.CheckFileName(get.path):
return public.returnMsg(False, '文件名中不能包含特殊字符!')
if os.path.exists(get.path):
return public.returnMsg(False, 'FILE_EXISTS')
path = os.path.dirname(get.path)
if not os.path.exists(path):
os.makedirs(path)
open(get.path, 'w+').close()
self.SetFileAccept(get.path)
public.WriteLog('TYPE_FILE', 'FILE_CREATE_SUCCESS', (get.path,))
return public.returnMsg(True, 'FILE_CREATE_SUCCESS')
except:
return public.returnMsg(False, 'FILE_CREATE_ERR')
#创建软链
def CreateLink(self,get):
'''
@name 创建软链接
@author hwliang<2021-03-23>
@param get<dict_obj{
sfile<string> 源文件
dfile<string> 软链文件名
}>
@return dict
'''
if not 'sfile' in get: return public.returnMsg(False,'参数错误')
if not os.path.exists(get.sfile): return public.returnMsg(False,'指定文件不存在,无法创建软链!')
if os.path.exists(get.dfile): return public.returnMsg(False,'指定软链文件名已存在,请使用其它文件名,或先删除!')
if get.dfile[0] != '/': return public.returnMsg(False,'指定软链文件名必需包含完整路径(全路径)')
public.ExecShell("ln -sf {} {}".format(get.sfile,get.dfile))
if not os.path.exists(get.dfile): return public.returnMsg(False,'软链文件创建失败!')
public.WriteLog('文件管理','创建软链: {} -> {}'.format(get.dfile,get.sfile))
return public.returnMsg(True,'软链文件创建成功!')
# 创建目录
def CreateDir(self, get):
if sys.version_info[0] == 2:
get.path = get.path.encode('utf-8').strip()
try:
if get.path[-1] == '.':
return public.returnMsg(False, '目录结尾不建议使用 ".",因为可能存在安全隐患')
if not self.CheckFileName(get.path):
return public.returnMsg(False, '目录名中不能包含特殊字符!')
if os.path.exists(get.path):
return public.returnMsg(False, 'DIR_EXISTS')
os.makedirs(get.path)
self.SetFileAccept(get.path)
public.WriteLog('TYPE_FILE', 'DIR_CREATE_SUCCESS', (get.path,))
return public.returnMsg(True, 'DIR_CREATE_SUCCESS')
except:
return public.returnMsg(False, 'DIR_CREATE_ERR')
# 删除目录
def DeleteDir(self, get):
if sys.version_info[0] == 2:
get.path = get.path.encode('utf-8')
if get.path == '/www/Recycle_bin':
return public.returnMsg(False, '不能直接操作回收站目录,请在右上角按【回收站】按钮打开')
if not os.path.exists(get.path):
return public.returnMsg(False, 'DIR_NOT_EXISTS')
# 检查是否敏感目录
if not self.CheckDir(get.path):
return public.returnMsg(False, 'FILE_DANGER')
try:
# 检查是否存在.user.ini
# if os.path.exists(get.path+'/.user.ini'):
# public.ExecShell("chattr -i '"+get.path+"/.user.ini'")
public.ExecShell("chattr -R -i " + get.path)
if hasattr(get, 'empty'):
if not self.delete_empty(get.path):
return public.returnMsg(False, 'DIR_ERR_NOT_EMPTY')
if os.path.exists('data/recycle_bin.pl') and session.get('debug') != 1:
if self.Mv_Recycle_bin(get):
self.site_path_safe(get)
self.remove_file_ps(get)
return public.returnMsg(True, 'DIR_MOVE_RECYCLE_BIN')
import shutil
shutil.rmtree(get.path)
self.site_path_safe(get)
public.WriteLog('TYPE_FILE', 'DIR_DEL_SUCCESS', (get.path,))
self.remove_file_ps(get)
return public.returnMsg(True, 'DIR_DEL_SUCCESS')
except:
return public.returnMsg(False, 'DIR_DEL_ERR')
# 删除 空目录
def delete_empty(self, path):
if sys.version_info[0] == 2:
path = path.encode('utf-8')
if len(os.listdir(path)) > 0:
return False
return True
# 删除文件
def DeleteFile(self, get):
if sys.version_info[0] == 2:
get.path = get.path.encode('utf-8')
if not os.path.exists(get.path):
return public.returnMsg(False, 'FILE_NOT_EXISTS')
# 检查是否为.user.ini
if get.path.find('.user.ini') != -1:
public.ExecShell("chattr -i '"+get.path+"'")
try:
if os.path.exists('data/recycle_bin.pl') and session.get('debug') != 1:
if self.Mv_Recycle_bin(get):
self.site_path_safe(get)
self.remove_file_ps(get)
return public.returnMsg(True, 'FILE_MOVE_RECYCLE_BIN')
os.remove(get.path)
self.site_path_safe(get)
public.WriteLog('TYPE_FILE', 'FILE_DEL_SUCCESS', (get.path,))
self.remove_file_ps(get)
return public.returnMsg(True, 'FILE_DEL_SUCCESS')
except:
return public.returnMsg(False, 'FILE_DEL_ERR')
def remove_file_ps(self,get):
'''
@name 删除文件或目录的备注信息
'''
get.filename = get.path
get.ps_body = ''
get.ps_type = '0'
self.set_file_ps(get)
# 移动到回收站
def Mv_Recycle_bin(self, get):
rPath = '/www/Recycle_bin/'
if not os.path.exists(rPath):
public.ExecShell('mkdir -p ' + rPath)
rFile = rPath + \
get.path.replace('/', '_bt_') + '_t_' + str(time.time())
try:
import shutil
shutil.move(get.path, rFile)
public.WriteLog('TYPE_FILE', 'FILE_MOVE_RECYCLE_BIN', (get.path,))
return True
except:
public.WriteLog(
'TYPE_FILE', 'FILE_MOVE_RECYCLE_BIN_ERR', (get.path,))
return False
# 从回收站恢复
def Re_Recycle_bin(self, get):
rPath = '/www/Recycle_bin/'
if sys.version_info[0] == 2:
get.path = get.path.encode('utf-8')
dFile = get.path.replace('_bt_', '/').split('_t_')[0]
get.path = rPath + get.path
if dFile.find('BTDB_') != -1:
import database
return database.database().RecycleDB(get.path)
try:
import shutil
shutil.move(get.path, dFile)
public.WriteLog('TYPE_FILE', 'FILE_RE_RECYCLE_BIN', (dFile,))
return public.returnMsg(True, 'FILE_RE_RECYCLE_BIN')
except:
public.WriteLog('TYPE_FILE', 'FILE_RE_RECYCLE_BIN_ERR', (dFile,))
return public.returnMsg(False, 'FILE_RE_RECYCLE_BIN_ERR')
# 获取回收站信息
def Get_Recycle_bin(self, get):
rPath = '/www/Recycle_bin/'
if not os.path.exists(rPath):
public.ExecShell('mkdir -p ' + rPath)
data = {}
data['dirs'] = []
data['files'] = []
data['status'] = os.path.exists('data/recycle_bin.pl')
data['status_db'] = os.path.exists('data/recycle_bin_db.pl')
for file in os.listdir(rPath):
file = self.xssencode(file)
try:
tmp = {}
fname = rPath + file
if sys.version_info[0] == 2:
fname = fname.encode('utf-8')
else:
fname.encode('utf-8')
tmp1 = file.split('_bt_')
tmp2 = tmp1[len(tmp1)-1].split('_t_')
tmp['rname'] = file
tmp['dname'] = file.replace('_bt_', '/').split('_t_')[0]
if tmp['dname'].find('@') != -1:
tmp['dname'] = "BTDB_" + tmp['dname'][5:].replace('@',"\\u").encode().decode("unicode_escape")
tmp['name'] = tmp2[0]
tmp['time'] = int(float(tmp2[1]))
if os.path.islink(fname):
filePath = os.readlink(fname)
if os.path.exists(filePath):
tmp['size'] = os.path.getsize(filePath)
else:
tmp['size'] = 0
else:
tmp['size'] = os.path.getsize(fname)
if os.path.isdir(fname):
if file[:5] == 'BTDB_':
tmp['size'] = public.get_path_size(fname)
data['dirs'].append(tmp)
else:
data['files'].append(tmp)
except:
continue
data['dirs'] = sorted(data['dirs'],key = lambda x: x['time'],reverse=True)
data['files'] = sorted(data['files'],key = lambda x: x['time'],reverse=True)
return data