elw2p.py-r2ed3cac49e.patch

Troex Nevelin, 02.07.2010 02:41

Download (15.8 kB)

 
elw2p.py 2010-07-01 02:54:39.889555347 +0400
3 3
# Connector for elFinder File Manager
4 4
# author Troex Nevelin <troex@fury.scancode.ru>
5 5

  
6
import cgi
6
#import cgi
7 7
import hashlib
8
import json
9 8
import mimetypes
10
import os
11 9
import os.path
12 10
import re
13 11
import shutil
14
import sys
15 12
import time
16 13
from datetime import datetime
14
from gluon.contrib import simplejson as json
15

  
17 16

  
18 17
class connector():
19 18
	"""Connector for elFinder"""
......
61 60
		'rm': '__rm',
62 61
		'duplicate': '__duplicate',
63 62
		'read': '__read',
64
		'edit': '__edit',
63
		'edit': '__edit', 
65 64
		'extract': '__extract',
66 65
		'archive': '__archive',
67 66
		'resize': '__resize',
......
72 71
	_mimeType = {
73 72
		# text
74 73
		'txt': 'text/plain',
75
		'conf': 'text/plain',
76
		'ini': 'text/plain',
77 74
		'php': 'text/x-php',
78 75
		'html': 'text/html',
79 76
		'htm': 'text/html',
......
105 102
	_sp = None
106 103
	_today = 0
107 104
	_yesterday = 0
105
# add 
106
	status1 = 200
107
	cont = None
108
	head={}
108 109

  
109 110
	def __init__(self, opts):
110 111
		self._response['debug'] = {}
......
113 114
			t = datetime.fromtimestamp(self._time)
114 115
			self._today = time.mktime(datetime(t.year, t.month, t.day).timetuple())
115 116
			self._yesterday = self._today - 86400
116
			import cgitb
117
			cgitb.enable()
117
#			import cgitb
118
#			cgitb.enable()
118 119

  
119 120
		for opt in opts:
120 121
			self._options[opt] = opts.get(opt)
......
135 136

  
136 137

  
137 138
	def run(self):
139
		print "it is function run"
138 140
		rootOk = True
139 141
		if not os.path.exists(self._options['root']) or self._options['root'] == '':
140 142
			rootOk = False
......
142 144
		elif not self.__isAllowed(self._options['root'], 'read'):
143 145
			rootOk = False
144 146
			self._response['error'] = 'Access denied'
145

  
146
		possible_fields = ['cmd', 'target', 'targets[]', 'current', 'tree', 'name', 
147
			'content', 'src', 'dst', 'cut', 'init', 'type', 'width', 'height']
148
		self._form = cgi.FieldStorage()
149
		for field in possible_fields:
150
			if field in self._form:
151
				self._request[field] = self._form.getvalue(field)
152

  
147
#		print "this is variables in class"
148
		print self._request
153 149
		if rootOk is True:
154 150
			if 'cmd' in self._request:
155 151
				if self._request['cmd'] in self._commands:
......
192 188
				del self._response['debug']
193 189

  
194 190
		if ('cmd' in self._request and self._request['cmd'] == 'upload') or self._options['debug']:
195
			print 'Content-type: text/html\n'
191
			self.head['Content-type'] = 'text/html'
192
#			print 'Content-type: text/html\n'
196 193
		else:
197
			print 'Content-type: application/json\n'
198

  
199
		print json.dumps(self._response, indent = bool(self._options['debug']))
200
		return  # sys.exit(0)
194
			self.head ['Content-type'] = 'application/json'
195
#			print 'Content-type: application/json\n'
201 196

  
197
		self.cont = self._response
198
#     print json.dumps(self._response, indent = bool(self._options['debug']))
199
		self.status1 =200
200
		return 
202 201

  
203 202
	def __open(self):
204 203
		"""Open file or directory"""
......
206 205
		if 'current' in self._request:
207 206
			curDir = self.__findDir(self._request['current'], None)
208 207
			curFile = self.__find(self._request['target'], curDir)
209

  
210 208
			if not curDir or not curFile or os.path.isdir(curFile):
211
				print 'HTTP/1.x 404 Not Found\n\n'
212
				sys.exit('File not found')
209
#				print "directory not found"
210
				self.cont = 'File not found'
211
				self.status1 = 404
212
				self.head['Content-type'] = 'text/html'
213
				return  
214
#				print 'HTTP/1.x 404 Not Found\n\n'
215
#				sys.exit('File not found')
216

  
213 217
			if not self.__isAllowed(curDir, 'read') or not self.__isAllowed(curFile, 'read'):
214
				print 'HTTP/1.x 403 Access Denied\n\n'
215
				sys.exit('Access denied')
218
#				print "Access denied"
219
				self.cont = 'File not found'
220
				self.status1 = 403
221
				self.head['Content-type'] = 'text/html'
222
				return  
223
#				print 'HTTP/1.x 403 Access Denied\n\n'
224
#				sys.exit('Access denied')
216 225

  
217 226
			if os.path.islink(curFile):
218 227
				curFile = self.__readlink(curFile)
219 228
				if not curFile or os.path.isdir(curFile):
220
					print 'HTTP/1.x 404 Not Found\n\n'
221
					sys.exit('File not found')
229
#					print "directory not found 2"
230
					self.cont = 'File not found'
231
					self.status1= 404
232
					self.head['Content-type'] = 'text/html'
233
					return 
234
#					print 'HTTP/1.x 404 Not Found\n\n'
235
#					sys.exit('File not found')
236

  
222 237
				if (
223 238
					not self.__isAllowed(os.path.dirname(curFile), 'read')
224 239
					or not self.__isAllowed(curFile, 'read')
225 240
					):
226
					print 'HTTP/1.x 403 Access Denied\n\n'
227
					sys.exit('Access denied')
241
#					print 'Access denied 2'
242
					self.cont = 'File not found'
243
					self.status1= 403
244
					self.head['Content-type']  = 'text/html'
245
					return 
246
#					print 'HTTP/1.x 403 Access Denied\n\n'
247
#					sys.exit('Access denied')
228 248

  
229 249
			mime = self.__mimetype(curFile)
230 250
			parts = mime.split('/', 2)
......
232 252
			elif parts[0] == 'text': disp = 'inline'
233 253
			else: disp = 'attachments'
234 254

  
235
			print 'Content-Type: ' + mime
236
			print 'Content-Disposition: ' + disp + '; filename=' + os.path.basename(curFile)
237
			print 'Content-Location: ' + curFile.replace(self._options['root'], '')
238
			print 'Content-Transfer-Encoding: binary'
239
			print 'Content-Length: ' + str(os.lstat(curFile).st_size)
240
			print 'Connection: close\n'
241
			print open(curFile, 'r').read()
242
			sys.exit(0);
255
#			my_data = open(curFile, 'r')
256
#			response = HttpResponse(my_data)
257

  
258

  
259
#			print 'Content-Type: ' + mime
260
			self.head['Content-Type'] = mime
261

  
262
#			print 'Content-Disposition: ' + disp + '; filename=' + os.path.basename(curFile)
263
			self.head["Content-Disposition"] = disp + '; filename=' + os.path.basename(curFile)
264

  
265
#			print 'Content-Location: ' + curFile.replace(self._options['root'], '')
266
			self.head["Content-Location"] =  curFile.replace(self._options['root'], '')
267

  
268
#			print 'Content-Transfer-Encoding: binary'
269
			self.head["Content-Transfer-Encoding"] =  'binary'
270

  
271
#			print 'Content-Length: ' + str(os.lstat(curFile).st_size)
272
			self.head["Content-Length"] =  str(os.lstat(curFile).st_size)
273

  
274
#			print 'Connection: close\n'
275
			self.head["Connection"] =  'close'
276

  
277
			file_read = open(curFile, 'r').read()
278
#			sys.exit(0);
279
#			print 'send response'
280
			self.status1 =200
281
			self.cont = file_read
282
			return 
243 283
		# try dir
244 284
		else:
285
			print "brunch not current"
245 286
			path = self._options['root']
287
			print "it root path = " + path 
246 288

  
247 289
			if 'target' in self._request:
248 290
				target = self.__findDir(self._request['target'], None)
......
251 293
				elif not self.__isAllowed(target, 'read'):
252 294
					self._response['error'] = 'Access denied'
253 295
				else:
296
					print "it path target = " + target
254 297
					path = target
255 298

  
256 299
			self.__content(path, 'tree' in self._request)
......
343 386

  
344 387

  
345 388
	def __rm(self):
389
		"""Delete files and directory"""
346 390
		current = rmList = None
347 391
		curDir = rmFile = None
348 392
		if 'current' in self._request and 'targets[]' in self._request:
......
366 410

  
367 411

  
368 412
	def __upload(self):
413
		"""load files"""
414
		print "this is function upload"
369 415
		try: # Windows needs stdio set for binary mode.
370 416
			import msvcrt
371 417
			msvcrt.setmode (0, os.O_BINARY) # stdin  = 0
372 418
			msvcrt.setmode (1, os.O_BINARY) # stdout = 1
373 419
		except ImportError:
420
			print "try on load msvcrt no good"
374 421
			pass
375 422

  
376 423
		if 'current' in self._request:
377 424
			curDir = self.__findDir(self._request['current'], None)
378 425
			if not curDir:
426
				print "curDir invalid parameter"
379 427
				self._response['error'] = 'Invalid parameters'
380 428
				return
381 429
			if not self.__isAllowed(curDir, 'write'):
430
				print "curDir Access denied"
382 431
				self._response['error'] = 'Access denied'
383 432
				return
384 433
			if not 'upload[]' in self._form:
434
				print "No files to upload"
385 435
				self._response['error'] = 'No file to upload'
386 436
				return
387 437

  
......
440 490

  
441 491

  
442 492
	def __paste(self):
493
		"""copy or remove files/directories"""
443 494
		if 'current' in self._request and 'src' in self._request and 'dst' in self._request:
444 495
			curDir = self.__findDir(self._request['current'], None)
445 496
			src = self.__findDir(self._request['src'], None)
......
500 551
			self.__content(curDir, True)
501 552
		else:
502 553
			self._response['error'] = 'Invalid parameters'
503

  
504 554
		return
505 555

  
506 556

  
507 557
	def __duplicate(self):
558
		"""create copy files/directories"""
508 559
		if 'current' in self._request and 'target' in self._request:
509 560
			curDir = self.__findDir(self._request['current'], None)
510 561
			target = self.__find(self._request['target'], curDir)
......
523 574

  
524 575

  
525 576
	def __resize(self):
577
		"""scale size of picture"""
526 578
		if not (
527 579
			'current' in self._request and 'target' in self._request
528 580
			and 'width' in self._request and 'height' in self._request
......
562 614

  
563 615

  
564 616
	def __thumbnails(self):
617
		"""class internal proc"""
618
		print "Thumbnails ran"
565 619
		if 'current' in self._request:
566 620
			curDir = self.__findDir(self._request['current'], None)
567 621
			if not curDir or curDir == self._options['tmbDir']:
......
757 811
			'dirs': []
758 812
		}
759 813
		if self.__isAllowed(path, 'read'):
760
			for d in sorted(os.listdir(path)):
814
			for d in os.listdir(path):
761 815
				pd = os.path.join(path, d)
762 816
				if os.path.isdir(pd) and not os.path.islink(pd) and self.__isAccepted(d):
763 817
					tree['dirs'].append(self.__tree(pd))
......
884 938
			return False
885 939
		return True
886 940

  
941
##Original
942
#def __findDir(self, fhash, path):
943
#		"""Find directory by hash"""
944
#		fhash = str(fhash)
945
#		if not path:
946
#			path = self._options['root']
947
#			if fhash == self.__hash(path):
948
#				return path
949
#
950
#		if not os.path.isdir(path):
951
#			return None
952
#
953
#		for d in os.listdir(path):
954
#			pd = os.path.join(path, d)
955
#			if os.path.isdir(pd) and not os.path.islink(pd):
956
#				if fhash == self.__hash(pd):
957
#					return pd
958
#				else:
959
#					ret = self.__findDir(fhash, pd)
960
#					if ret:
961
#						return ret
962
#
963
#		return None
887 964

  
965

  
966
###TODO: Removing Hash on __findDir
888 967
	def __findDir(self, fhash, path):
889 968
		"""Find directory by hash"""
890 969
		fhash = str(fhash)
891 970
		if not path:
892 971
			path = self._options['root']
893 972
			if fhash == self.__hash(path):
894
				return path
973
				return fhash
895 974

  
896 975
		if not os.path.isdir(path):
897 976
			return None
......
921 1000

  
922 1001

  
923 1002
	def __read(self):
1003
		"""read file content"""
1004
#		print " function _read"
924 1005
		if 'current' in self._request and 'target' in self._request:
925 1006
			curDir = self.__findDir(self._request['current'], None)
926 1007
			curFile = self.__find(self._request['target'], curDir)
927 1008
			if curDir and curFile:
928 1009
				if self.__isAllowed(curFile, 'read'):
929
					self._response['content'] = open(curFile, 'r').read()
1010
					fff = open(curFile, 'r')
1011
					self._response['content'] = fff.read()
1012
					fff.close()
930 1013
				else:
931 1014
					self._response['error'] = 'Access denied'
932 1015
				return
933

  
934 1016
		self._response['error'] = 'Invalid parameters'
935 1017
		return
936 1018

  
937 1019

  
938 1020
	def __edit(self):
1021
		"""save content in file"""
939 1022
		error = ''
940 1023
		if 'current' in self._request and 'target' in self._request and 'content' in self._request:
941 1024
			curDir = self.__findDir(self._request['current'], None)
......
944 1027
			if curFile and curDir:
945 1028
				if self.__isAllowed(curFile, 'write'):
946 1029
					try:
947
						f = open(curFile, 'w+')
948
						f.write(self._request['content'])
949
						f.close()
1030
						safe_file_uni = self._request['content']
1031
						safe_file= safe_file_uni.encode('utf-8')
1032
						ffff = open(curFile, 'w+')
1033
						ffff.write(safe_file)
1034
						ffff.close()
950 1035
						self._response['target'] = self.__info(curFile)
951 1036
					except:
952 1037
						self._response['error'] = 'Unable to write to file'
953 1038
				else:
954 1039
					self._response['error'] = 'Access denied'
955 1040
			return
956

  
957 1041
		self._response['error'] = 'Invalid parameters'
958 1042
		return
959 1043

  
960 1044

  
961 1045
	def __archive(self):
1046
		"""compress fili or directory"""
962 1047
		self.__checkArchivers()
963 1048

  
964 1049
		if (
......
1019 1104
			self._response['select'] = [self.__hash(archivePath)]
1020 1105
		else:
1021 1106
			self._response['error'] = 'Unable to create archive'
1022

  
1023 1107
		return
1024 1108

  
1025 1109

  
1026 1110
	def __extract(self):
1111
		"""uncompress archive"""
1027 1112
		if not 'current' in self._request or not 'target' in self._request:
1028 1113
			self._response['error'] = 'Invalid parameters'
1029 1114
			return
......
1064 1149

  
1065 1150
	def __ping(self):
1066 1151
		"""Workaround for Safari"""
1067
		print 'Connection: close\n'
1068
		sys.exit(0)
1152
#		print 'Connection: close\n'
1153
#		sys.exit(0)
1154
		self.status1 = 200
1155
		self.head['Connection'] = 'close'
1156
		_content = ''
1157
		return
1069 1158

  
1070 1159

  
1071 1160
	def __mimetype(self, path):
......
1093 1182

  
1094 1183

  
1095 1184
	def __tmb(self, path, tmb):
1185
		"""create icon for picture"""
1096 1186
		try:
1097 1187
			im = self._im.open(path).copy()
1098 1188
			size = self._options['tmbSize'], self._options['tmbSize']
......
1258 1348

  
1259 1349
		return self._options['defaults'][access]
1260 1350

  
1261

  
1351
###TODO: Try to Remove Hashing
1262 1352
	def __hash(self, path):
1263 1353
		"""Hash of the path"""
1264
		m = hashlib.md5()
1265
		m.update(path)
1266
		return str(m.hexdigest())
1354
#		m = hashlib.md5()
1355
#		m.update(path)
1356
#		return str(m.hexdigest())
1357
		return path
1267 1358

  
1268 1359

  
1269 1360
	def __path2url(self, path):
......
1284 1375

  
1285 1376

  
1286 1377
	def __initImgLib(self):
1287
		if not self._options['imgLib'] is False and self._im is None:
1288
			try:
1289
				import Image
1290
				Image
1291
				self._im = Image
1292
				self._options['imgLib'] = 'PIL'
1293
			except:
1294
				self._options['imgLib'] = False
1295
				self._im = False
1378
		self._options['imgLib'] = False
1296 1379

  
1297
		self.__debug('imgLib', self._options['imgLib'])
1298 1380
		return self._options['imgLib']
1299 1381

  
1300 1382

  
......
1327 1409
		e = archive['extract']
1328 1410

  
1329 1411
		tar = self.__runSubProcess(['tar', '--version'])
1330
		gzip = self.__runSubProcess(['gzip', '--version'])
1331
		bzip2 = self.__runSubProcess(['bzip2', '--version'])
1332
		zipc = self.__runSubProcess(['zip', '--version'])
1333
		unzip = self.__runSubProcess(['unzip', '--help'])
1334
		rar = self.__runSubProcess(['rar', '--version'], validReturn = [0, 7])
1335
		unrar = self.__runSubProcess(['unrar'], validReturn = [0, 7])
1336
		p7z = self.__runSubProcess(['7z', '--help'])
1337
		p7za = self.__runSubProcess(['7za', '--help'])
1338
		p7zr = self.__runSubProcess(['7zr', '--help'])
1412

  
1339 1413

  
1340 1414
		# tar = False
1341 1415
		tar = gzip = bzip2 = zipc = unzip = rar = unrar = False
......
1346 1420
			c.update({mime: {'cmd': 'tar', 'argc': '-cf', 'ext': 'tar'}})
1347 1421
			e.update({mime: {'cmd': 'tar', 'argc': '-xf', 'ext': 'tar'}})
1348 1422

  
1349
		if tar and gzip:
1350
			mime = 'application/x-gzip'
1351
			c.update({mime: {'cmd': 'tar', 'argc': '-czf', 'ext': 'tar.gz'}})
1352
			e.update({mime: {'cmd': 'tar', 'argc': '-xzf', 'ext': 'tar.gz'}})
1353

  
1354
		if tar and bzip2:
1355
			mime = 'application/x-bzip2'
1356
			c.update({mime: {'cmd': 'tar', 'argc': '-cjf', 'ext': 'tar.bz2'}})
1357
			e.update({mime: {'cmd': 'tar', 'argc': '-xjf', 'ext': 'tar.bz2'}})
1358

  
1359
		mime = 'application/zip'
1360
		if zipc:
1361
			c.update({mime: {'cmd': 'zip', 'argc': '-r9', 'ext': 'zip'}})
1362
		if unzip:
1363
			e.update({mime: {'cmd': 'unzip', 'argc': '', 'ext': 'zip'}})
1364

  
1365
		mime = 'application/x-rar'
1366
		if rar:
1367
			c.update({mime: {'cmd': 'rar', 'argc': 'a -inul', 'ext': 'rar'}})
1368
			e.update({mime: {'cmd': 'rar', 'argc': 'x -y', 'ext': 'rar'}})
1369
		elif unrar:
1370
			e.update({mime: {'cmd': 'unrar', 'argc': 'x -y', 'ext': 'rar'}})
1371

  
1372
		p7zip = None
1373
		if p7z:
1374
			p7zip = '7z'
1375
		elif p7za:
1376
			p7zip = '7za'
1377
		elif p7zr:
1378
			p7zip = '7zr'
1379

  
1380
		if p7zip:
1381
			mime = 'application/x-7z-compressed'
1382
			c.update({mime: {'cmd': p7zip, 'argc': 'a -t7z', 'ext': '7z'}})
1383
			e.update({mime: {'cmd': p7zip, 'argc': 'e -y', 'ext': '7z'}})
1384

  
1385
			mime = 'application/x-tar'
1386
			if not mime in c:
1387
				c.update({mime: {'cmd': p7zip, 'argc': 'a -ttar', 'ext': 'tar'}})
1388
			if not mime in e:
1389
				e.update({mime: {'cmd': p7zip, 'argc': 'e -y', 'ext': 'tar'}})
1390

  
1391
			mime = 'application/x-gzip'
1392
			if not mime in c:
1393
				c.update({mime: {'cmd': p7zip, 'argc': 'a -tgzip', 'ext': 'gz'}})
1394
			if not mime in e:
1395
				e.update({mime: {'cmd': p7zip, 'argc': 'e -y', 'ext': 'tar.gz'}})
1396

  
1397
			mime = 'application/x-bzip2'
1398
			if not mime in c:
1399
				c.update({mime: {'cmd': p7zip, 'argc': 'a -tbzip2', 'ext': 'bz2'}})
1400
			if not mime in e:
1401
				e.update({mime: {'cmd': p7zip, 'argc': 'e -y', 'ext': 'tar.bz2'}})
1402

  
1403
			mime = 'application/zip'
1404
			if not mime in c:
1405
				c.update({mime: {'cmd': p7zip, 'argc': 'a -tzip', 'ext': 'zip'}})
1406
			if not mime in e:
1407
				e.update({mime: {'cmd': p7zip, 'argc': 'e -y', 'ext': 'zip'}})
1408 1423

  
1409 1424
		if not self._options['archiveMimes']:
1410 1425
			self._options['archiveMimes'] = c.keys()