PageRenderTime 38ms CodeModel.GetById 12ms app.highlight 21ms RepoModel.GetById 1ms app.codeStats 0ms

/pigeoncms/Plugins/fckeditor/editor/filemanager/connectors/py/fckcommands.py

http://pigeoncms.googlecode.com/
Python | 202 lines | 191 code | 1 blank | 10 comment | 0 complexity | a6a792e6970311c26adf71b5d927076e MD5 | raw file
  1#!/usr/bin/env python
  2
  3"""
  4FCKeditor - The text editor for Internet - http://www.fckeditor.net
  5Copyright (C) 2003-2009 Frederico Caldeira Knabben
  6
  7== BEGIN LICENSE ==
  8
  9Licensed under the terms of any of the following licenses at your
 10choice:
 11
 12- GNU General Public License Version 2 or later (the "GPL")
 13http://www.gnu.org/licenses/gpl.html
 14
 15- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
 16http://www.gnu.org/licenses/lgpl.html
 17
 18- Mozilla Public License Version 1.1 or later (the "MPL")
 19http://www.mozilla.org/MPL/MPL-1.1.html
 20
 21== END LICENSE ==
 22
 23Connector for Python (CGI and WSGI).
 24
 25"""
 26
 27import os
 28try: # Windows needs stdio set for binary mode for file upload to work.
 29	import msvcrt
 30	msvcrt.setmode (0, os.O_BINARY) # stdin  = 0
 31	msvcrt.setmode (1, os.O_BINARY) # stdout = 1
 32except ImportError:
 33	pass
 34
 35from fckutil import *
 36from fckoutput import *
 37import config as Config
 38
 39class GetFoldersCommandMixin (object):
 40	def getFolders(self, resourceType, currentFolder):
 41		"""
 42		Purpose: command to recieve a list of folders
 43		"""
 44		# Map the virtual path to our local server
 45		serverPath = mapServerFolder(self.userFilesFolder,currentFolder)
 46		s = """<Folders>"""	 # Open the folders node
 47		for someObject in os.listdir(serverPath):
 48			someObjectPath = mapServerFolder(serverPath, someObject)
 49			if os.path.isdir(someObjectPath):
 50				s += """<Folder name="%s" />""" % (
 51						convertToXmlAttribute(someObject)
 52						)
 53		s += """</Folders>""" # Close the folders node
 54		return s
 55
 56class GetFoldersAndFilesCommandMixin (object):
 57	def getFoldersAndFiles(self, resourceType, currentFolder):
 58		"""
 59		Purpose: command to recieve a list of folders and files
 60		"""
 61		# Map the virtual path to our local server
 62		serverPath = mapServerFolder(self.userFilesFolder,currentFolder)
 63		# Open the folders / files node
 64		folders = """<Folders>"""
 65		files = """<Files>"""
 66		for someObject in os.listdir(serverPath):
 67			someObjectPath = mapServerFolder(serverPath, someObject)
 68			if os.path.isdir(someObjectPath):
 69				folders += """<Folder name="%s" />""" % (
 70						convertToXmlAttribute(someObject)
 71						)
 72			elif os.path.isfile(someObjectPath):
 73				size = os.path.getsize(someObjectPath)
 74				if size > 0:
 75					size = round(size/1024)
 76					if size < 1:
 77						size = 1
 78				files += """<File name="%s" size="%d" />""" % (
 79						convertToXmlAttribute(someObject),
 80						size
 81						)
 82		# Close the folders / files node
 83		folders += """</Folders>"""
 84		files += """</Files>"""
 85		return folders + files
 86
 87class CreateFolderCommandMixin (object):
 88	def createFolder(self, resourceType, currentFolder):
 89		"""
 90		Purpose: command to create a new folder
 91		"""
 92		errorNo = 0; errorMsg ='';
 93		if self.request.has_key("NewFolderName"):
 94			newFolder = self.request.get("NewFolderName", None)
 95			newFolder = sanitizeFolderName (newFolder)
 96			try:
 97				newFolderPath = mapServerFolder(self.userFilesFolder, combinePaths(currentFolder, newFolder))
 98				self.createServerFolder(newFolderPath)
 99			except Exception, e:
100				errorMsg = str(e).decode('iso-8859-1').encode('utf-8') # warning with encodigns!!!
101				if hasattr(e,'errno'):
102					if e.errno==17: #file already exists
103						errorNo=0
104					elif e.errno==13: # permission denied
105						errorNo = 103
106					elif e.errno==36 or e.errno==2 or e.errno==22: # filename too long / no such file / invalid name
107						errorNo = 102
108				else:
109					errorNo = 110
110		else:
111			errorNo = 102
112		return self.sendErrorNode ( errorNo, errorMsg )
113
114	def createServerFolder(self, folderPath):
115		"Purpose: physically creates a folder on the server"
116		# No need to check if the parent exists, just create all hierachy
117
118		try:
119			permissions = Config.ChmodOnFolderCreate
120			if not permissions:
121				os.makedirs(folderPath)
122		except AttributeError: #ChmodOnFolderCreate undefined
123			permissions = 0755
124
125		if permissions:
126			oldumask = os.umask(0)
127			os.makedirs(folderPath,mode=0755)
128			os.umask( oldumask )
129
130class UploadFileCommandMixin (object):
131	def uploadFile(self, resourceType, currentFolder):
132		"""
133		Purpose: command to upload files to server (same as FileUpload)
134		"""
135		errorNo = 0
136		if self.request.has_key("NewFile"):
137			# newFile has all the contents we need
138			newFile = self.request.get("NewFile", "")
139			# Get the file name
140			newFileName = newFile.filename
141			newFileName = sanitizeFileName( newFileName )
142			newFileNameOnly = removeExtension(newFileName)
143			newFileExtension = getExtension(newFileName).lower()
144			allowedExtensions = Config.AllowedExtensions[resourceType]
145			deniedExtensions = Config.DeniedExtensions[resourceType]
146
147			if (allowedExtensions):
148				# Check for allowed
149				isAllowed = False
150				if (newFileExtension in allowedExtensions):
151					isAllowed = True
152			elif (deniedExtensions):
153				# Check for denied
154				isAllowed = True
155				if (newFileExtension in deniedExtensions):
156					isAllowed = False
157			else:
158				# No extension limitations
159				isAllowed = True
160
161			if (isAllowed):
162				# Upload to operating system
163				# Map the virtual path to the local server path
164				currentFolderPath = mapServerFolder(self.userFilesFolder, currentFolder)
165				i = 0
166				while (True):
167					newFilePath = os.path.join (currentFolderPath,newFileName)
168					if os.path.exists(newFilePath):
169						i += 1
170						newFileName = "%s(%d).%s" % (
171								newFileNameOnly, i, newFileExtension
172								)
173						errorNo= 201 # file renamed
174					else:
175						# Read file contents and write to the desired path (similar to php's move_uploaded_file)
176						fout = file(newFilePath, 'wb')
177						while (True):
178							chunk = newFile.file.read(100000)
179							if not chunk: break
180							fout.write (chunk)
181						fout.close()
182
183						if os.path.exists ( newFilePath ):
184							doChmod = False
185							try:
186								doChmod = Config.ChmodOnUpload
187								permissions = Config.ChmodOnUpload
188							except AttributeError: #ChmodOnUpload undefined
189								doChmod = True
190								permissions = 0755
191							if ( doChmod ):
192								oldumask = os.umask(0)
193								os.chmod( newFilePath, permissions )
194								os.umask( oldumask )
195
196						newFileUrl = combinePaths(self.webUserFilesFolder, currentFolder) + newFileName
197
198						return self.sendUploadResults( errorNo , newFileUrl, newFileName )
199			else:
200				return self.sendUploadResults( errorNo = 202, customMsg = "" )
201		else:
202			return self.sendUploadResults( errorNo = 202, customMsg = "No File" )