initial commit

This commit is contained in:
Siwat Sirichai 2025-06-08 16:22:20 +07:00
commit 252dac3143
1516 changed files with 694271 additions and 0 deletions

View file

@ -0,0 +1,62 @@
<%
' FCKeditor - The text editor for Internet - http://www.fckeditor.net
' Copyright (C) 2003-2007 Frederico Caldeira Knabben
'
' == BEGIN LICENSE ==
'
' Licensed under the terms of any of the following licenses at your
' choice:
'
' - GNU General Public License Version 2 or later (the "GPL")
' http://www.gnu.org/licenses/gpl.html
'
' - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
' http://www.gnu.org/licenses/lgpl.html
'
' - Mozilla Public License Version 1.1 or later (the "MPL")
' http://www.mozilla.org/MPL/MPL-1.1.html
'
' == END LICENSE ==
'
' This file include the functions that create the base XML output.
%>
<%
Sub SetXmlHeaders()
' Cleans the response buffer.
Response.Clear()
' Prevent the browser from caching the result.
Response.CacheControl = "no-cache"
' Set the response format.
Response.CharSet = "UTF-8"
Response.ContentType = "text/xml"
End Sub
Sub CreateXmlHeader( command, resourceType, currentFolder, url )
' Create the XML document header.
Response.Write "<?xml version=""1.0"" encoding=""utf-8"" ?>"
' Create the main "Connector" node.
Response.Write "<Connector command=""" & command & """ resourceType=""" & resourceType & """>"
' Add the current folder node.
Response.Write "<CurrentFolder path=""" & ConvertToXmlAttribute( currentFolder ) & """ url=""" & ConvertToXmlAttribute( url ) & """ />"
End Sub
Sub CreateXmlFooter()
Response.Write "</Connector>"
End Sub
Sub SendError( number, text )
SetXmlHeaders
' Create the XML document header.
Response.Write "<?xml version=""1.0"" encoding=""utf-8"" ?>"
Response.Write "<Connector><Error number=""" & number & """ text=""" & Server.HTMLEncode( text ) & """ /></Connector>"
Response.End
End Sub
%>

View file

@ -0,0 +1,353 @@
<%
' FCKeditor - The text editor for Internet - http://www.fckeditor.net
' Copyright (C) 2003-2007 Frederico Caldeira Knabben
'
' == BEGIN LICENSE ==
'
' Licensed under the terms of any of the following licenses at your
' choice:
'
' - GNU General Public License Version 2 or later (the "GPL")
' http://www.gnu.org/licenses/gpl.html
'
' - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
' http://www.gnu.org/licenses/lgpl.html
'
' - Mozilla Public License Version 1.1 or later (the "MPL")
' http://www.mozilla.org/MPL/MPL-1.1.html
'
' == END LICENSE ==
'
' These are the classes used to handle ASP upload without using third
' part components (OCX/DLL).
%>
<%
'**********************************************
' File: NetRube_Upload.asp
' Version: NetRube Upload Class Version 2.3 Build 20070528
' Author: NetRube
' Email: NetRube@126.com
' Date: 05/28/2007
' Comments: The code for the Upload.
' This can free usage, but please
' not to delete this copyright information.
' If you have a modification version,
' Please send out a duplicate to me.
'**********************************************
' 文件名: NetRube_Upload.asp
' 版本: NetRube Upload Class Version 2.3 Build 20070528
' 作者: NetRube(网络乡巴佬)
' 电子邮件: NetRube@126.com
' 日期: 2007年05月28日
' 声明: 文件上传类
' 本上传类可以自由使用,但请保留此版权声明信息
' 如果您对本上传类进行修改增强,
' 请发送一份给俺。
'**********************************************
Class NetRube_Upload
Public File, Form
Private oSourceData
Private nMaxSize, nErr, sAllowed, sDenied, sHtmlExtensions
Private Sub Class_Initialize
nErr = 0
nMaxSize = 1048576
Set File = Server.CreateObject("Scripting.Dictionary")
File.CompareMode = 1
Set Form = Server.CreateObject("Scripting.Dictionary")
Form.CompareMode = 1
Set oSourceData = Server.CreateObject("ADODB.Stream")
oSourceData.Type = 1
oSourceData.Mode = 3
oSourceData.Open
End Sub
Private Sub Class_Terminate
Form.RemoveAll
Set Form = Nothing
File.RemoveAll
Set File = Nothing
oSourceData.Close
Set oSourceData = Nothing
End Sub
Public Property Get Version
Version = "NetRube Upload Class Version 2.3 Build 20070528"
End Property
Public Property Get ErrNum
ErrNum = nErr
End Property
Public Property Let MaxSize(nSize)
nMaxSize = nSize
End Property
Public Property Let Allowed(sExt)
sAllowed = sExt
End Property
Public Property Let Denied(sExt)
sDenied = sExt
End Property
Public Property Let HtmlExtensions(sExt)
sHtmlExtensions = sExt
End Property
Public Sub GetData
Dim aCType
aCType = Split(Request.ServerVariables("HTTP_CONTENT_TYPE"), ";")
if ( uBound(aCType) < 0 ) then
nErr = 1
Exit Sub
end if
If aCType(0) <> "multipart/form-data" Then
nErr = 1
Exit Sub
End If
Dim nTotalSize
nTotalSize = Request.TotalBytes
If nTotalSize < 1 Then
nErr = 2
Exit Sub
End If
If nMaxSize > 0 And nTotalSize > nMaxSize Then
nErr = 3
Exit Sub
End If
'Thankful long(yrl031715@163.com)
'Fix upload large file.
'**********************************************
' 修正作者long
' 联系邮件: yrl031715@163.com
' 修正时间2007年5月6日
' 修正说明由于iis6的Content-Length 头信息中包含的请求长度超过了 AspMaxRequestEntityAllowed 的值默认200K, IIS 将返回一个 403 错误信息.
' 直接导致在iis6下调试FCKeditor上传功能时一旦文件超过200K,上传文件时文件管理器失去响应,受此影响,文件的快速上传功能也存在在缺陷。
' 在参考 宝玉 的 Asp无组件上传带进度条 演示程序后作出如下修改以修正在iis6下的错误。
Dim nTotalBytes, nPartBytes, ReadBytes
ReadBytes = 0
nTotalBytes = Request.TotalBytes
'循环分块读取
Do While ReadBytes < nTotalBytes
'分块读取
nPartBytes = 64 * 1024 '分成每块64k
If nPartBytes + ReadBytes > nTotalBytes Then
nPartBytes = nTotalBytes - ReadBytes
End If
oSourceData.Write Request.BinaryRead(nPartBytes)
ReadBytes = ReadBytes + nPartBytes
Loop
'**********************************************
oSourceData.Position = 0
Dim oTotalData, oFormStream, sFormHeader, sFormName, bCrLf, nBoundLen, nFormStart, nFormEnd, nPosStart, nPosEnd, sBoundary
oTotalData = oSourceData.Read
bCrLf = ChrB(13) & ChrB(10)
sBoundary = MidB(oTotalData, 1, InStrB(1, oTotalData, bCrLf) - 1)
nBoundLen = LenB(sBoundary) + 2
nFormStart = nBoundLen
Set oFormStream = Server.CreateObject("ADODB.Stream")
Do While (nFormStart + 2) < nTotalSize
nFormEnd = InStrB(nFormStart, oTotalData, bCrLf & bCrLf) + 3
With oFormStream
.Type = 1
.Mode = 3
.Open
oSourceData.Position = nFormStart
oSourceData.CopyTo oFormStream, nFormEnd - nFormStart
.Position = 0
.Type = 2
.CharSet = "UTF-8"
sFormHeader = .ReadText
.Close
End With
nFormStart = InStrB(nFormEnd, oTotalData, sBoundary) - 1
nPosStart = InStr(22, sFormHeader, " name=", 1) + 7
nPosEnd = InStr(nPosStart, sFormHeader, """")
sFormName = Mid(sFormHeader, nPosStart, nPosEnd - nPosStart)
If InStr(45, sFormHeader, " filename=", 1) > 0 Then
Set File(sFormName) = New NetRube_FileInfo
File(sFormName).FormName = sFormName
File(sFormName).Start = nFormEnd
File(sFormName).Size = nFormStart - nFormEnd - 2
nPosStart = InStr(nPosEnd, sFormHeader, " filename=", 1) + 11
nPosEnd = InStr(nPosStart, sFormHeader, """")
File(sFormName).ClientPath = Mid(sFormHeader, nPosStart, nPosEnd - nPosStart)
File(sFormName).Name = Mid(File(sFormName).ClientPath, InStrRev(File(sFormName).ClientPath, "\") + 1)
File(sFormName).Ext = LCase(Mid(File(sFormName).Name, InStrRev(File(sFormName).Name, ".") + 1))
nPosStart = InStr(nPosEnd, sFormHeader, "Content-Type: ", 1) + 14
nPosEnd = InStr(nPosStart, sFormHeader, vbCr)
File(sFormName).MIME = Mid(sFormHeader, nPosStart, nPosEnd - nPosStart)
Else
With oFormStream
.Type = 1
.Mode = 3
.Open
oSourceData.Position = nFormEnd
oSourceData.CopyTo oFormStream, nFormStart - nFormEnd - 2
.Position = 0
.Type = 2
.CharSet = "UTF-8"
Form(sFormName) = .ReadText
.Close
End With
End If
nFormStart = nFormStart + nBoundLen
Loop
oTotalData = ""
Set oFormStream = Nothing
End Sub
Public Sub SaveAs(sItem, sFileName)
If File(sItem).Size < 1 Then
nErr = 2
Exit Sub
End If
If Not IsAllowed(File(sItem).Ext) Then
nErr = 4
Exit Sub
End If
If InStr( LCase( sFileName ), "::$data" ) > 0 Then
nErr = 4
Exit Sub
End If
Dim sFileExt, iFileSize
sFileExt = File(sItem).Ext
iFileSize = File(sItem).Size
' Check XSS.
If Not IsHtmlExtension( sFileExt ) Then
' Calculate the size of data to load (max 1Kb).
Dim iXSSSize
iXSSSize = iFileSize
If iXSSSize > 1024 Then
iXSSSize = 1024
End If
' Read the data.
Dim sData
oSourceData.Position = File(sItem).Start
sData = oSourceData.Read( iXSSSize ) ' Byte Array
sData = ByteArray2Text( sData ) ' String
' Sniff HTML data.
If SniffHtml( sData ) Then
nErr = 4
Exit Sub
End If
End If
Dim oFileStream
Set oFileStream = Server.CreateObject("ADODB.Stream")
With oFileStream
.Type = 1
.Mode = 3
.Open
oSourceData.Position = File(sItem).Start
oSourceData.CopyTo oFileStream, File(sItem).Size
.Position = 0
.SaveToFile sFileName, 2
.Close
End With
Set oFileStream = Nothing
End Sub
Private Function IsAllowed(sExt)
Dim oRE
Set oRE = New RegExp
oRE.IgnoreCase = True
oRE.Global = True
If sDenied = "" Then
oRE.Pattern = sAllowed
IsAllowed = (sAllowed = "") Or oRE.Test(sExt)
Else
oRE.Pattern = sDenied
IsAllowed = Not oRE.Test(sExt)
End If
Set oRE = Nothing
End Function
Private Function IsHtmlExtension( sExt )
If sHtmlExtensions = "" Then
Exit Function
End If
Dim oRE
Set oRE = New RegExp
oRE.IgnoreCase = True
oRE.Global = True
oRE.Pattern = sHtmlExtensions
IsHtmlExtension = oRE.Test(sExt)
Set oRE = Nothing
End Function
Private Function SniffHtml( sData )
Dim oRE
Set oRE = New RegExp
oRE.IgnoreCase = True
oRE.Global = True
Dim aPatterns
aPatterns = Array( "<!DOCTYPE\W*X?HTML", "<(body|head|html|img|pre|script|table|title)", "type\s*=\s*[\'""]?\s*(?:\w*/)?(?:ecma|java)", "(?:href|src|data)\s*=\s*[\'""]?\s*(?:ecma|java)script:", "url\s*\(\s*[\'""]?\s*(?:ecma|java)script:" )
Dim i
For i = 0 to UBound( aPatterns )
oRE.Pattern = aPatterns( i )
If oRE.Test( sData ) Then
SniffHtml = True
Exit Function
End If
Next
SniffHtml = False
End Function
' Thanks to http://www.ericphelps.com/q193998/index.htm
Private Function ByteArray2Text(varByteArray)
Dim strData, strBuffer, lngCounter
strData = ""
strBuffer = ""
For lngCounter = 0 to UBound(varByteArray)
strBuffer = strBuffer & Chr(255 And Ascb(Midb(varByteArray,lngCounter + 1, 1)))
'Keep strBuffer at 1k bytes maximum
If lngCounter Mod 1024 = 0 Then
strData = strData & strBuffer
strBuffer = ""
End If
Next
ByteArray2Text = strData & strBuffer
End Function
End Class
Class NetRube_FileInfo
Dim FormName, ClientPath, Path, Name, Ext, Content, Size, MIME, Start
End Class
%>

View file

@ -0,0 +1,198 @@
<%
' FCKeditor - The text editor for Internet - http://www.fckeditor.net
' Copyright (C) 2003-2007 Frederico Caldeira Knabben
'
' == BEGIN LICENSE ==
'
' Licensed under the terms of any of the following licenses at your
' choice:
'
' - GNU General Public License Version 2 or later (the "GPL")
' http://www.gnu.org/licenses/gpl.html
'
' - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
' http://www.gnu.org/licenses/lgpl.html
'
' - Mozilla Public License Version 1.1 or later (the "MPL")
' http://www.mozilla.org/MPL/MPL-1.1.html
'
' == END LICENSE ==
'
' This file include the functions that handle the Command requests
' in the ASP Connector.
%>
<%
Sub GetFolders( resourceType, currentFolder )
' Map the virtual path to the local server path.
Dim sServerDir
sServerDir = ServerMapFolder( resourceType, currentFolder, "GetFolders" )
' Open the "Folders" node.
Response.Write "<Folders>"
Dim oFSO, oCurrentFolder, oFolders, oFolder
Set oFSO = Server.CreateObject( "Scripting.FileSystemObject" )
if not (oFSO.FolderExists( sServerDir ) ) then
Set oFSO = Nothing
SendError 102, currentFolder
end if
Set oCurrentFolder = oFSO.GetFolder( sServerDir )
Set oFolders = oCurrentFolder.SubFolders
For Each oFolder in oFolders
Response.Write "<Folder name=""" & ConvertToXmlAttribute( oFolder.name ) & """ />"
Next
Set oFSO = Nothing
' Close the "Folders" node.
Response.Write "</Folders>"
End Sub
Sub GetFoldersAndFiles( resourceType, currentFolder )
' Map the virtual path to the local server path.
Dim sServerDir
sServerDir = ServerMapFolder( resourceType, currentFolder, "GetFoldersAndFiles" )
Dim oFSO, oCurrentFolder, oFolders, oFolder, oFiles, oFile
Set oFSO = Server.CreateObject( "Scripting.FileSystemObject" )
if not (oFSO.FolderExists( sServerDir ) ) then
Set oFSO = Nothing
SendError 102, currentFolder
end if
Set oCurrentFolder = oFSO.GetFolder( sServerDir )
Set oFolders = oCurrentFolder.SubFolders
Set oFiles = oCurrentFolder.Files
' Open the "Folders" node.
Response.Write "<Folders>"
For Each oFolder in oFolders
Response.Write "<Folder name=""" & ConvertToXmlAttribute( oFolder.name ) & """ />"
Next
' Close the "Folders" node.
Response.Write "</Folders>"
' Open the "Files" node.
Response.Write "<Files>"
For Each oFile in oFiles
Dim iFileSize
iFileSize = Round( oFile.size / 1024 )
If ( iFileSize < 1 AND oFile.size <> 0 ) Then iFileSize = 1
Response.Write "<File name=""" & ConvertToXmlAttribute( oFile.name ) & """ size=""" & iFileSize & """ />"
Next
' Close the "Files" node.
Response.Write "</Files>"
End Sub
Sub CreateFolder( resourceType, currentFolder )
Dim sErrorNumber
Dim sNewFolderName
sNewFolderName = Request.QueryString( "NewFolderName" )
sNewFolderName = SanitizeFolderName( sNewFolderName )
If ( sNewFolderName = "" OR InStr( 1, sNewFolderName, ".." ) > 0 ) Then
sErrorNumber = "102"
Else
' Map the virtual path to the local server path of the current folder.
Dim sServerDir
sServerDir = ServerMapFolder( resourceType, CombinePaths(currentFolder, sNewFolderName), "CreateFolder" )
On Error Resume Next
CreateServerFolder sServerDir
Dim iErrNumber, sErrDescription
iErrNumber = err.number
sErrDescription = err.Description
On Error Goto 0
Select Case iErrNumber
Case 0
sErrorNumber = "0"
Case 52
sErrorNumber = "102" ' Invalid Folder Name.
Case 70
sErrorNumber = "103" ' Security Error.
Case 76
sErrorNumber = "102" ' Path too long.
Case Else
sErrorNumber = "110"
End Select
End If
' Create the "Error" node.
Response.Write "<Error number=""" & sErrorNumber & """ originalNumber=""" & iErrNumber & """ originalDescription=""" & ConvertToXmlAttribute( sErrDescription ) & """ />"
End Sub
Sub FileUpload( resourceType, currentFolder, sCommand )
Dim oUploader
Set oUploader = New NetRube_Upload
oUploader.MaxSize = 0
oUploader.Allowed = ConfigAllowedExtensions.Item( resourceType )
oUploader.Denied = ConfigDeniedExtensions.Item( resourceType )
oUploader.HtmlExtensions = ConfigHtmlExtensions
oUploader.GetData
Dim sErrorNumber
sErrorNumber = "0"
Dim sFileName, sOriginalFileName, sExtension
sFileName = ""
If oUploader.ErrNum > 0 Then
sErrorNumber = "202"
Else
' Map the virtual path to the local server path.
Dim sServerDir
sServerDir = ServerMapFolder( resourceType, currentFolder, sCommand )
Dim oFSO
Set oFSO = Server.CreateObject( "Scripting.FileSystemObject" )
if not (oFSO.FolderExists( sServerDir ) ) then
sErrorNumber = "102"
else
' Get the uploaded file name.
sFileName = oUploader.File( "NewFile" ).Name
sExtension = oUploader.File( "NewFile" ).Ext
sFileName = SanitizeFileName( sFileName )
sOriginalFileName = sFileName
Dim iCounter
iCounter = 0
Do While ( True )
Dim sFilePath
sFilePath = sServerDir & sFileName
If ( oFSO.FileExists( sFilePath ) ) Then
iCounter = iCounter + 1
sFileName = RemoveExtension( sOriginalFileName ) & "(" & iCounter & ")." & sExtension
sErrorNumber = "201"
Else
oUploader.SaveAs "NewFile", sFilePath
If oUploader.ErrNum > 0 Then sErrorNumber = "202"
Exit Do
End If
Loop
end if
End If
Set oUploader = Nothing
dim sFileUrl
sFileUrl = CombinePaths( GetResourceTypePath( resourceType, sCommand ) , currentFolder )
sFileUrl = CombinePaths( sFileUrl, sFileName )
SendUploadResults sErrorNumber, sFileUrl, sFileName, ""
End Sub
%>

View file

@ -0,0 +1,128 @@
<%
' FCKeditor - The text editor for Internet - http://www.fckeditor.net
' Copyright (C) 2003-2007 Frederico Caldeira Knabben
'
' == BEGIN LICENSE ==
'
' Licensed under the terms of any of the following licenses at your
' choice:
'
' - GNU General Public License Version 2 or later (the "GPL")
' http://www.gnu.org/licenses/gpl.html
'
' - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
' http://www.gnu.org/licenses/lgpl.html
'
' - Mozilla Public License Version 1.1 or later (the "MPL")
' http://www.mozilla.org/MPL/MPL-1.1.html
'
' == END LICENSE ==
'
' Configuration file for the File Manager Connector for ASP.
%>
<%
' SECURITY: You must explicitly enable this "connector" (set it to "True").
' WARNING: don't just set "ConfigIsEnabled = true", you must be sure that only
' authenticated users can access this file or use some kind of session checking.
Dim ConfigIsEnabled
ConfigIsEnabled = False
' Path to user files relative to the document root.
' This setting is preserved only for backward compatibility.
' You should look at the settings for each resource type to get the full potential
Dim ConfigUserFilesPath
ConfigUserFilesPath = "/userfiles/"
' Due to security issues with Apache modules, it is recommended to leave the
' following setting enabled.
Dim ConfigForceSingleExtension
ConfigForceSingleExtension = true
' What the user can do with this connector
Dim ConfigAllowedCommands
ConfigAllowedCommands = "QuickUpload|FileUpload|GetFolders|GetFoldersAndFiles|CreateFolder"
' Allowed Resource Types
Dim ConfigAllowedTypes
ConfigAllowedTypes = "File|Image|Flash|Media"
' For security, HTML is allowed in the first Kb of data for files having the
' following extensions only.
Dim ConfigHtmlExtensions
ConfigHtmlExtensions = "html|htm|xml|xsd|txt|js"
'
' Configuration settings for each Resource Type
'
' - AllowedExtensions: the possible extensions that can be allowed.
' If it is empty then any file type can be uploaded.
'
' - DeniedExtensions: The extensions that won't be allowed.
' If it is empty then no restrictions are done here.
'
' For a file to be uploaded it has to fulfill both the AllowedExtensions
' and DeniedExtensions (that's it: not being denied) conditions.
'
' - FileTypesPath: the virtual folder relative to the document root where
' these resources will be located.
' Attention: It must start and end with a slash: '/'
'
' - FileTypesAbsolutePath: the physical path to the above folder. It must be
' an absolute path.
' If it's an empty string then it will be autocalculated.
' Useful if you are using a virtual directory, symbolic link or alias.
' Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
' Attention: The above 'FileTypesPath' must point to the same directory.
' Attention: It must end with a slash: '/'
'
' - QuickUploadPath: the virtual folder relative to the document root where
' these resources will be uploaded using the Upload tab in the resources
' dialogs.
' Attention: It must start and end with a slash: '/'
'
' - QuickUploadAbsolutePath: the physical path to the above folder. It must be
' an absolute path.
' If it's an empty string then it will be autocalculated.
' Useful if you are using a virtual directory, symbolic link or alias.
' Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
' Attention: The above 'QuickUploadPath' must point to the same directory.
' Attention: It must end with a slash: '/'
'
Dim ConfigAllowedExtensions, ConfigDeniedExtensions, ConfigFileTypesPath, ConfigFileTypesAbsolutePath, ConfigQuickUploadPath, ConfigQuickUploadAbsolutePath
Set ConfigAllowedExtensions = CreateObject( "Scripting.Dictionary" )
Set ConfigDeniedExtensions = CreateObject( "Scripting.Dictionary" )
Set ConfigFileTypesPath = CreateObject( "Scripting.Dictionary" )
Set ConfigFileTypesAbsolutePath = CreateObject( "Scripting.Dictionary" )
Set ConfigQuickUploadPath = CreateObject( "Scripting.Dictionary" )
Set ConfigQuickUploadAbsolutePath = CreateObject( "Scripting.Dictionary" )
ConfigAllowedExtensions.Add "File", "7z|aiff|asf|avi|bmp|csv|doc|fla|flv|gif|gz|gzip|jpeg|jpg|mid|mov|mp3|mp4|mpc|mpeg|mpg|ods|odt|pdf|png|ppt|pxd|qt|ram|rar|rm|rmi|rmvb|rtf|sdc|sitd|swf|sxc|sxw|tar|tgz|tif|tiff|txt|vsd|wav|wma|wmv|xls|xml|zip"
ConfigDeniedExtensions.Add "File", ""
ConfigFileTypesPath.Add "File", ConfigUserFilesPath & "file/"
ConfigFileTypesAbsolutePath.Add "File", ""
ConfigQuickUploadPath.Add "File", ConfigUserFilesPath
ConfigQuickUploadAbsolutePath.Add "File", ""
ConfigAllowedExtensions.Add "Image", "bmp|gif|jpeg|jpg|png"
ConfigDeniedExtensions.Add "Image", ""
ConfigFileTypesPath.Add "Image", ConfigUserFilesPath & "image/"
ConfigFileTypesAbsolutePath.Add "Image", ""
ConfigQuickUploadPath.Add "Image", ConfigUserFilesPath
ConfigQuickUploadAbsolutePath.Add "Image", ""
ConfigAllowedExtensions.Add "Flash", "swf|flv"
ConfigDeniedExtensions.Add "Flash", ""
ConfigFileTypesPath.Add "Flash", ConfigUserFilesPath & "flash/"
ConfigFileTypesAbsolutePath.Add "Flash", ""
ConfigQuickUploadPath.Add "Flash", ConfigUserFilesPath
ConfigQuickUploadAbsolutePath.Add "Flash", ""
ConfigAllowedExtensions.Add "Media", "aiff|asf|avi|bmp|fla|flv|gif|jpeg|jpg|mid|mov|mp3|mp4|mpc|mpeg|mpg|png|qt|ram|rm|rmi|rmvb|swf|tif|tiff|wav|wma|wmv"
ConfigDeniedExtensions.Add "Media", ""
ConfigFileTypesPath.Add "Media", ConfigUserFilesPath & "media/"
ConfigFileTypesAbsolutePath.Add "Media", ""
ConfigQuickUploadPath.Add "Media", ConfigUserFilesPath
ConfigQuickUploadAbsolutePath.Add "Media", ""
%>

View file

@ -0,0 +1,88 @@
<%@ CodePage=65001 Language="VBScript"%>
<%
Option Explicit
Response.Buffer = True
%>
<%
' FCKeditor - The text editor for Internet - http://www.fckeditor.net
' Copyright (C) 2003-2007 Frederico Caldeira Knabben
'
' == BEGIN LICENSE ==
'
' Licensed under the terms of any of the following licenses at your
' choice:
'
' - GNU General Public License Version 2 or later (the "GPL")
' http://www.gnu.org/licenses/gpl.html
'
' - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
' http://www.gnu.org/licenses/lgpl.html
'
' - Mozilla Public License Version 1.1 or later (the "MPL")
' http://www.mozilla.org/MPL/MPL-1.1.html
'
' == END LICENSE ==
'
' This is the File Manager Connector for ASP.
%>
<!--#include file="config.asp"-->
<!--#include file="util.asp"-->
<!--#include file="io.asp"-->
<!--#include file="basexml.asp"-->
<!--#include file="commands.asp"-->
<!--#include file="class_upload.asp"-->
<%
If ( ConfigIsEnabled = False ) Then
SendError 1, "This connector is disabled. Please check the ""editor/filemanager/connectors/asp/config.asp"" file"
End If
DoResponse
Sub DoResponse()
Dim sCommand, sResourceType, sCurrentFolder
' Get the main request information.
sCommand = Request.QueryString("Command")
sResourceType = Request.QueryString("Type")
If ( sResourceType = "" ) Then sResourceType = "File"
sCurrentFolder = GetCurrentFolder()
' Check if it is an allowed command
if ( Not IsAllowedCommand( sCommand ) ) then
SendError 1, "The """ & sCommand & """ command isn't allowed"
end if
' Check if it is an allowed resource type.
if ( Not IsAllowedType( sResourceType ) ) Then
SendError 1, "The """ & sResourceType & """ resource type isn't allowed"
end if
' File Upload doesn't have to Return XML, so it must be intercepted before anything.
If ( sCommand = "FileUpload" ) Then
FileUpload sResourceType, sCurrentFolder, sCommand
Exit Sub
End If
SetXmlHeaders
CreateXmlHeader sCommand, sResourceType, sCurrentFolder, GetUrlFromPath( sResourceType, sCurrentFolder, sCommand)
' Execute the required command.
Select Case sCommand
Case "GetFolders"
GetFolders sResourceType, sCurrentFolder
Case "GetFoldersAndFiles"
GetFoldersAndFiles sResourceType, sCurrentFolder
Case "CreateFolder"
CreateFolder sResourceType, sCurrentFolder
End Select
CreateXmlFooter
Response.End
End Sub
%>

View file

@ -0,0 +1,222 @@
<%
' FCKeditor - The text editor for Internet - http://www.fckeditor.net
' Copyright (C) 2003-2007 Frederico Caldeira Knabben
'
' == BEGIN LICENSE ==
'
' Licensed under the terms of any of the following licenses at your
' choice:
'
' - GNU General Public License Version 2 or later (the "GPL")
' http://www.gnu.org/licenses/gpl.html
'
' - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
' http://www.gnu.org/licenses/lgpl.html
'
' - Mozilla Public License Version 1.1 or later (the "MPL")
' http://www.mozilla.org/MPL/MPL-1.1.html
'
' == END LICENSE ==
'
' This file include IO specific functions used by the ASP Connector.
%>
<%
function CombinePaths( sBasePath, sFolder)
CombinePaths = RemoveFromEnd( sBasePath, "/" ) & "/" & RemoveFromStart( sFolder, "/" )
end function
Function GetResourceTypePath( resourceType, sCommand )
if ( sCommand = "QuickUpload") then
GetResourceTypePath = ConfigQuickUploadPath.Item( resourceType )
else
GetResourceTypePath = ConfigFileTypesPath.Item( resourceType )
end if
end Function
Function GetResourceTypeDirectory( resourceType, sCommand )
if ( sCommand = "QuickUpload") then
if ( ConfigQuickUploadAbsolutePath.Item( resourceType ) <> "" ) then
GetResourceTypeDirectory = ConfigQuickUploadAbsolutePath.Item( resourceType )
else
' Map the "UserFiles" path to a local directory.
GetResourceTypeDirectory = Server.MapPath( ConfigQuickUploadPath.Item( resourceType ) )
end if
else
if ( ConfigFileTypesAbsolutePath.Item( resourceType ) <> "" ) then
GetResourceTypeDirectory = ConfigFileTypesAbsolutePath.Item( resourceType )
else
' Map the "UserFiles" path to a local directory.
GetResourceTypeDirectory = Server.MapPath( ConfigFileTypesPath.Item( resourceType ) )
end if
end if
end Function
Function GetUrlFromPath( resourceType, folderPath, sCommand )
GetUrlFromPath = CombinePaths( GetResourceTypePath( resourceType, sCommand ), folderPath )
End Function
Function RemoveExtension( fileName )
RemoveExtension = Left( fileName, InStrRev( fileName, "." ) - 1 )
End Function
Function ServerMapFolder( resourceType, folderPath, sCommand )
Dim sResourceTypePath
' Get the resource type directory.
sResourceTypePath = GetResourceTypeDirectory( resourceType, sCommand )
' Ensure that the directory exists.
CreateServerFolder sResourceTypePath
' Return the resource type directory combined with the required path.
ServerMapFolder = CombinePaths( sResourceTypePath, folderPath )
End Function
Sub CreateServerFolder( folderPath )
Dim oFSO
Set oFSO = Server.CreateObject( "Scripting.FileSystemObject" )
Dim sParent
sParent = oFSO.GetParentFolderName( folderPath )
' Check if the parent exists, or create it.
If ( NOT oFSO.FolderExists( sParent ) ) Then CreateServerFolder( sParent )
If ( oFSO.FolderExists( folderPath ) = False ) Then
On Error resume next
oFSO.CreateFolder( folderPath )
if err.number<>0 then
dim sErrorNumber
Dim iErrNumber, sErrDescription
iErrNumber = err.number
sErrDescription = err.Description
On Error Goto 0
Select Case iErrNumber
Case 52
sErrorNumber = "102" ' Invalid Folder Name.
Case 70
sErrorNumber = "103" ' Security Error.
Case 76
sErrorNumber = "102" ' Path too long.
Case Else
sErrorNumber = "110"
End Select
SendError sErrorNumber, "CreateServerFolder(" & folderPath & ") : " & sErrDescription
end if
End If
Set oFSO = Nothing
End Sub
Function IsAllowedExt( extension, resourceType )
Dim oRE
Set oRE = New RegExp
oRE.IgnoreCase = True
oRE.Global = True
Dim sAllowed, sDenied
sAllowed = ConfigAllowedExtensions.Item( resourceType )
sDenied = ConfigDeniedExtensions.Item( resourceType )
IsAllowedExt = True
If sDenied <> "" Then
oRE.Pattern = sDenied
IsAllowedExt = Not oRE.Test( extension )
End If
If IsAllowedExt And sAllowed <> "" Then
oRE.Pattern = sAllowed
IsAllowedExt = oRE.Test( extension )
End If
Set oRE = Nothing
End Function
Function IsAllowedType( resourceType )
Dim oRE
Set oRE = New RegExp
oRE.IgnoreCase = True
oRE.Global = True
oRE.Pattern = "^(" & ConfigAllowedTypes & ")$"
IsAllowedType = oRE.Test( resourceType )
Set oRE = Nothing
End Function
Function IsAllowedCommand( sCommand )
Dim oRE
Set oRE = New RegExp
oRE.IgnoreCase = True
oRE.Global = True
oRE.Pattern = "^(" & ConfigAllowedCommands & ")$"
IsAllowedCommand = oRE.Test( sCommand )
Set oRE = Nothing
End Function
function GetCurrentFolder()
dim sCurrentFolder
sCurrentFolder = Request.QueryString("CurrentFolder")
If ( sCurrentFolder = "" ) Then sCurrentFolder = "/"
' Check the current folder syntax (must begin and start with a slash).
If ( Right( sCurrentFolder, 1 ) <> "/" ) Then sCurrentFolder = sCurrentFolder & "/"
If ( Left( sCurrentFolder, 1 ) <> "/" ) Then sCurrentFolder = "/" & sCurrentFolder
' Check for invalid folder paths (..)
If ( InStr( 1, sCurrentFolder, ".." ) <> 0 ) Then
SendError 102, ""
End If
GetCurrentFolder = sCurrentFolder
end function
' Do a cleanup of the folder name to avoid possible problems
function SanitizeFolderName( sNewFolderName )
Dim oRegex
Set oRegex = New RegExp
oRegex.Global = True
' remove . \ / | : ? * " < >
oRegex.Pattern = "(\.|\\|\/|\||:|\?|\*|""|\<|\>)"
SanitizeFolderName = oRegex.Replace( sNewFolderName, "_" )
Set oRegex = Nothing
end function
' Do a cleanup of the file name to avoid possible problems
function SanitizeFileName( sNewFileName )
Dim oRegex
Set oRegex = New RegExp
oRegex.Global = True
if ( ConfigForceSingleExtension = True ) then
oRegex.Pattern = "\.(?![^.]*$)"
sNewFileName = oRegex.Replace( sNewFileName, "_" )
end if
' remove \ / | : ? * " < >
oRegex.Pattern = "(\\|\/|\||:|\?|\*|""|\<|\>)"
SanitizeFileName = oRegex.Replace( sNewFileName, "_" )
Set oRegex = Nothing
end function
' This is the function that sends the results of the uploading process.
Sub SendUploadResults( errorNumber, fileUrl, fileName, customMsg )
Response.Clear
Response.Write "<script type=""text/javascript"">"
Response.Write "window.parent.OnUploadCompleted(" & errorNumber & ",""" & Replace( fileUrl, """", "\""" ) & """,""" & Replace( fileName, """", "\""" ) & """,""" & Replace( customMsg , """", "\""" ) & """) ;"
Response.Write "</script>"
Response.End
End Sub
%>

View file

@ -0,0 +1,61 @@
<%@ CodePage=65001 Language="VBScript"%>
<%
Option Explicit
Response.Buffer = True
%>
<%
' FCKeditor - The text editor for Internet - http://www.fckeditor.net
' Copyright (C) 2003-2007 Frederico Caldeira Knabben
'
' == BEGIN LICENSE ==
'
' Licensed under the terms of any of the following licenses at your
' choice:
'
' - GNU General Public License Version 2 or later (the "GPL")
' http://www.gnu.org/licenses/gpl.html
'
' - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
' http://www.gnu.org/licenses/lgpl.html
'
' - Mozilla Public License Version 1.1 or later (the "MPL")
' http://www.mozilla.org/MPL/MPL-1.1.html
'
' == END LICENSE ==
'
' This is the "File Uploader" for ASP.
%>
<!--#include file="config.asp"-->
<!--#include file="util.asp"-->
<!--#include file="io.asp"-->
<!--#include file="commands.asp"-->
<!--#include file="class_upload.asp"-->
<%
' Check if this uploader has been enabled.
If ( ConfigIsEnabled = False ) Then
SendUploadResults "1", "", "", "This file uploader is disabled. Please check the ""editor/filemanager/connectors/asp/config.asp"" file"
End If
Dim sCommand, sResourceType, sCurrentFolder
sCommand = "QuickUpload"
sResourceType = Request.QueryString("Type")
If ( sResourceType = "" ) Then sResourceType = "File"
sCurrentFolder = GetCurrentFolder()
' Is Upload enabled?
if ( Not IsAllowedCommand( sCommand ) ) then
SendUploadResults "1", "", "", "The """ & sCommand & """ command isn't allowed"
end if
' Check if it is an allowed resource type.
if ( Not IsAllowedType( sResourceType ) ) Then
SendUploadResults "1", "", "", "The " & sResourceType & " resource type isn't allowed"
end if
FileUpload sResourceType, sCurrentFolder, sCommand
%>

View file

@ -0,0 +1,55 @@
<%
' FCKeditor - The text editor for Internet - http://www.fckeditor.net
' Copyright (C) 2003-2007 Frederico Caldeira Knabben
'
' == BEGIN LICENSE ==
'
' Licensed under the terms of any of the following licenses at your
' choice:
'
' - GNU General Public License Version 2 or later (the "GPL")
' http://www.gnu.org/licenses/gpl.html
'
' - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
' http://www.gnu.org/licenses/lgpl.html
'
' - Mozilla Public License Version 1.1 or later (the "MPL")
' http://www.mozilla.org/MPL/MPL-1.1.html
'
' == END LICENSE ==
'
' This file include generic functions used by the ASP Connector.
%>
<%
Function RemoveFromStart( sourceString, charToRemove )
Dim oRegex
Set oRegex = New RegExp
oRegex.Pattern = "^" & charToRemove & "+"
RemoveFromStart = oRegex.Replace( sourceString, "" )
End Function
Function RemoveFromEnd( sourceString, charToRemove )
Dim oRegex
Set oRegex = New RegExp
oRegex.Pattern = charToRemove & "+$"
RemoveFromEnd = oRegex.Replace( sourceString, "" )
End Function
Function ConvertToXmlAttribute( value )
ConvertToXmlAttribute = Replace( value, "&", "&amp;" )
End Function
Function InArray( value, sourceArray )
Dim i
For i = 0 to UBound( sourceArray )
If sourceArray(i) = value Then
InArray = True
Exit Function
End If
Next
InArray = False
End Function
%>

View file

@ -0,0 +1,98 @@
<%@ Control Language="C#" EnableViewState="false" AutoEventWireup="false" Inherits="FredCK.FCKeditorV2.FileBrowser.Config" %>
<%--
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2007 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Configuration file for the File Browser Connector for ASP.NET.
--%>
<script runat="server">
/**
* This function must check the user session to be sure that he/she is
* authorized to upload and access files in the File Browser.
*/
private bool CheckAuthentication()
{
// WARNING : DO NOT simply return "true". By doing so, you are allowing
// "anyone" to upload and list the files in your server. You must implement
// some kind of session validation here. Even something very simple as...
//
// return ( Session[ "IsAuthorized" ] != null && (bool)Session[ "IsAuthorized" ] == true );
//
// ... where Session[ "IsAuthorized" ] is set to "true" as soon as the
// user logs in your system.
return false;
}
public override void SetConfig()
{
// SECURITY: You must explicitly enable this "connector". (Set it to "true").
Enabled = CheckAuthentication();
// URL path to user files.
UserFilesPath = "/userfiles/";
// The connector tries to resolve the above UserFilesPath automatically.
// Use the following setting it you prefer to explicitely specify the
// absolute path. Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
// Attention: The above 'UserFilesPath' URL must point to the same directory.
UserFilesAbsolutePath = "";
// Due to security issues with Apache modules, it is recommended to leave the
// following setting enabled.
ForceSingleExtension = true;
// Allowed Resource Types
AllowedTypes = new string[] { "File", "Image", "Flash", "Media" };
// For security, HTML is allowed in the first Kb of data for files having the
// following extensions only.
HtmlExtensions = new string[] { "html", "htm", "xml", "xsd", "txt", "js" };
TypeConfig[ "File" ].AllowedExtensions = new string[] { "7z", "aiff", "asf", "avi", "bmp", "csv", "doc", "fla", "flv", "gif", "gz", "gzip", "jpeg", "jpg", "mid", "mov", "mp3", "mp4", "mpc", "mpeg", "mpg", "ods", "odt", "pdf", "png", "ppt", "pxd", "qt", "ram", "rar", "rm", "rmi", "rmvb", "rtf", "sdc", "sitd", "swf", "sxc", "sxw", "tar", "tgz", "tif", "tiff", "txt", "vsd", "wav", "wma", "wmv", "xls", "xml", "zip" };
TypeConfig[ "File" ].DeniedExtensions = new string[] { };
TypeConfig[ "File" ].FilesPath = "%UserFilesPath%file/";
TypeConfig[ "File" ].FilesAbsolutePath = ( UserFilesAbsolutePath == "" ? "" : "%UserFilesAbsolutePath%file/" );
TypeConfig[ "File" ].QuickUploadPath = "%UserFilesPath%";
TypeConfig[ "File" ].QuickUploadAbsolutePath = ( UserFilesAbsolutePath == "" ? "" : "%UserFilesAbsolutePath%" );
TypeConfig[ "Image" ].AllowedExtensions = new string[] { "bmp", "gif", "jpeg", "jpg", "png" };
TypeConfig[ "Image" ].DeniedExtensions = new string[] { };
TypeConfig[ "Image" ].FilesPath = "%UserFilesPath%image/";
TypeConfig[ "Image" ].FilesAbsolutePath = ( UserFilesAbsolutePath == "" ? "" : "%UserFilesAbsolutePath%image/" );
TypeConfig[ "Image" ].QuickUploadPath = "%UserFilesPath%";
TypeConfig[ "Image" ].QuickUploadAbsolutePath = ( UserFilesAbsolutePath == "" ? "" : "%UserFilesAbsolutePath%" );
TypeConfig[ "Flash" ].AllowedExtensions = new string[] { "swf", "flv" };
TypeConfig[ "Flash" ].DeniedExtensions = new string[] { };
TypeConfig[ "Flash" ].FilesPath = "%UserFilesPath%flash/";
TypeConfig[ "Flash" ].FilesAbsolutePath = ( UserFilesAbsolutePath == "" ? "" : "%UserFilesAbsolutePath%flash/" );
TypeConfig[ "Flash" ].QuickUploadPath = "%UserFilesPath%";
TypeConfig[ "Flash" ].QuickUploadAbsolutePath = ( UserFilesAbsolutePath == "" ? "" : "%UserFilesAbsolutePath%" );
TypeConfig[ "Media" ].AllowedExtensions = new string[] { "aiff", "asf", "avi", "bmp", "fla", "flv", "gif", "jpeg", "jpg", "mid", "mov", "mp3", "mp4", "mpc", "mpeg", "mpg", "png", "qt", "ram", "rm", "rmi", "rmvb", "swf", "tif", "tiff", "wav", "wma", "wmv" };
TypeConfig[ "Media" ].DeniedExtensions = new string[] { };
TypeConfig[ "Media" ].FilesPath = "%UserFilesPath%media/";
TypeConfig[ "Media" ].FilesAbsolutePath = ( UserFilesAbsolutePath == "" ? "" : "%UserFilesAbsolutePath%media/" );
TypeConfig[ "Media" ].QuickUploadPath = "%UserFilesPath%";
TypeConfig[ "Media" ].QuickUploadAbsolutePath = ( UserFilesAbsolutePath == "" ? "" : "%UserFilesAbsolutePath%" );
}
</script>

View file

@ -0,0 +1,32 @@
<%@ Page Language="c#" Trace="false" Inherits="FredCK.FCKeditorV2.FileBrowser.Connector" AutoEventWireup="false" %>
<%@ Register Src="config.ascx" TagName="Config" TagPrefix="FCKeditor" %>
<%--
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2007 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* This is the File Browser Connector for ASP.NET.
*
* The code of this page if included in the FCKeditor.Net package,
* in the FredCK.FCKeditorV2.dll assembly file. So to use it you must
* include that DLL in your "bin" directory.
*
* To download the FCKeditor.Net package, go to our official web site:
* http://www.fckeditor.net
--%>
<FCKeditor:Config id="Config" runat="server"></FCKeditor:Config>

View file

@ -0,0 +1,32 @@
<%@ Page Language="c#" Trace="false" Inherits="FredCK.FCKeditorV2.FileBrowser.Uploader" AutoEventWireup="false" %>
<%@ Register Src="config.ascx" TagName="Config" TagPrefix="FCKeditor" %>
<%--
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2007 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* This is the Uploader for ASP.NET.
*
* The code of this page if included in the FCKeditor.Net package,
* in the FredCK.FCKeditorV2.dll assemblyfile. So to use it you must
* include that DLL in your "bin" directory.
*
* To download the FCKeditor.Net package, go to our official web site:
* http://www.fckeditor.net
--%>
<FCKeditor:Config id="Config" runat="server"></FCKeditor:Config>

View file

@ -0,0 +1,273 @@
<cfcomponent name="ImageObject">
<!---
ImageObject.cfc written by Rick Root (rick@webworksllc.com)
Related Web Sites:
- http://www.opensourcecf.com/imagecfc (home page)
This is an object oriented interface to the original
ImageCFC.
Example Code:
io = createObject("component","ImageObject");
io.setOption("defaultJpegCompression",95);
io.init("#ExpandPath(".")#/emily.jpg");
io.scaleWidth(500);
io.save("#ExpandPath(".")#/imagex1.jpg");
io.flipHorizontal();
io.save("#ExpandPath(".")#/imagex2.jpg");
io.revert();
io.filterFastBlur(2,5);
io.save("#ExpandPath(".")#/imagex3.jpg");
io.revert();
io.filterPosterize(32);
io.save("#ExpandPath(".")#/imagex4.jpg");
LICENSE
-------
Copyright (c) 2006, Rick Root <rick@webworksllc.com>
All rights reserved.
Redistribution and use in source and binary forms, with or
without modification, are permitted provided that the
following conditions are met:
- Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
- Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
- Neither the name of the Webworks, LLC. nor the names of
its contributors may be used to endorse or promote products
derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--->
<cfset variables.img = "">
<cfset variables.revertimg = "">
<cfset variables.imageCFC = createObject("component","image")>
<cfset variables.imageInfo = structNew()>
<cfset variables.imageInfo.width = 0>
<cfset variables.imageInfo.height = 0>
<cfset variables.imageInfo.colorModel = "">
<cfset variables.imageInfo.colorspace = "">
<cfset variables.imageInfo.objColorModel = "">
<cfset variables.imageInfo.objColorspace = "">
<cfset variables.imageInfo.sampleModel = "">
<cfset variables.imageInfo.imageType = 0>
<cfset variables.imageInfo.misc = "">
<cfset variables.imageInfo.canModify = false>
<cfset variables.imageCFC.setOption("throwonerror",true)>
<!---
init(filename) Initialize object from a file.
init(width, height) Initialize with a blank image
init(bufferedImage) Initiailize with an existing object
--->
<cffunction name="init" access="public" output="false" returnType="void">
<cfargument name="arg1" type="any" required="yes">
<cfargument name="arg2" type="any" required="no">
<cfif isDefined("arg2") and isNumeric(arg1) and isNumeric(arg2)>
<cfset arg1 = javacast("int",int(arg1))>
<cfset arg2 = javacast("int",int(arg2))>
<cfset variables.img = createObject("java","java.awt.image.BufferedImage")>
<cfset variables.img.init(arg1,arg2,variables.img.TYPE_INT_RGB)>
<cfelseif arg1.getClass().getName() eq "java.awt.image.BufferedImage">
<cfset variables.img = arg1>
<cfelseif isSimpleValue(arg1) and len(arg1) gt 0>
<cfset imageResults = variables.imageCFC.readImage(arg1, "no")>
<cfset variables.img = imageResults.img>
<cfelse>
<cfthrow message="Object Instantiation Error" detail="You have attempted to initialize ooimage.cfc with invalid arguments. Please consult the documentation for correct initialization arguments.">
</cfif>
<cfif variables.revertimg eq "">
<cfset variables.revertimg = variables.img>
</cfif>
<cfset variables.imageInfo = imageCFC.getImageInfo(variables.img,"")>
<cfreturn>
</cffunction>
<cffunction name="flipHorizontal" access="public" output="true" returnType="void" hint="Flip an image horizontally.">
<cfset var imageResults = imageCFC.flipHorizontal(variables.img,"","")>
<cfset variables.revertimg = variables.img>
<cfset variables.img = imageResults.img>
<cfset variables.imageInfo = imageCFC.getImageInfo(variables.img,"")>
</cffunction>
<cffunction name="getImageInfo" access="public" output="true" returntype="struct" hint="Returns image information.">
<cfreturn variables.imageInfo>
</cffunction>
<cffunction name="getImageObject" access="public" output="true" returntype="struct" hint="Returns a java Buffered Image Object.">
<cfreturn variables.img>
</cffunction>
<cffunction name="flipVertical" access="public" output="true" returntype="void" hint="Flop an image vertically.">
<cfset var imageResults = imageCFC.flipVertical(variables.img,"","")>
<cfset variables.revertimg = variables.img>
<cfset variables.img = imageResults.img>
<cfset variables.imageInfo = imageCFC.getImageInfo(variables.img,"")>
</cffunction>
<cffunction name="scaleWidth" access="public" output="true" returntype="void" hint="Scale an image to a specific width.">
<cfargument name="newWidth" required="yes" type="numeric">
<cfset var imageResults = imageCFC.scaleWidth(variables.img,"","", newWidth)>
<cfset variables.revertimg = variables.img>
<cfset variables.img = imageResults.img>
<cfset variables.imageInfo = imageCFC.getImageInfo(variables.img,"")>
</cffunction>
<cffunction name="scaleHeight" access="public" output="true" returntype="void" hint="Scale an image to a specific height.">
<cfargument name="newHeight" required="yes" type="numeric">
<cfset var imageResults = imageCFC.scaleHeight(variables.img,"","", newHeight)>
<cfset variables.revertimg = variables.img>
<cfset variables.img = imageResults.img>
<cfset variables.imageInfo = imageCFC.getImageInfo(variables.img,"")>
</cffunction>
<cffunction name="resize" access="public" output="true" returntype="void" hint="Resize an image to a specific width and height.">
<cfargument name="newWidth" required="yes" type="numeric">
<cfargument name="newHeight" required="yes" type="numeric">
<cfargument name="preserveAspect" required="no" type="boolean" default="FALSE">
<cfargument name="cropToExact" required="no" type="boolean" default="FALSE">
<cfset var imageResults = imageCFC.resize(variables.img,"","",newWidth,newHeight,preserveAspect,cropToExact)>
<cfset variables.revertimg = variables.img>
<cfset variables.img = imageResults.img>
<cfset variables.imageInfo = imageCFC.getImageInfo(variables.img,"")>
</cffunction>
<cffunction name="crop" access="public" output="true" returntype="void" hint="Crop an image.">
<cfargument name="fromX" required="yes" type="numeric">
<cfargument name="fromY" required="yes" type="numeric">
<cfargument name="newWidth" required="yes" type="numeric">
<cfargument name="newHeight" required="yes" type="numeric">
<cfset var imageResults = imageCFC.crop(variables.img,"","",fromX,fromY,newWidth,newHeight)>
<cfset variables.revertimg = variables.img>
<cfset variables.img = imageResults.img>
<cfset variables.imageInfo = imageCFC.getImageInfo(variables.img,"")>
</cffunction>
<cffunction name="rotate" access="public" output="true" returntype="void" hint="Rotate an image (+/-)90, (+/-)180, or (+/-)270 degrees.">
<cfargument name="degrees" required="yes" type="numeric">
<cfset var imageResults = imageCFC.rotate(variables.img,"","",degrees)>
<cfset variables.revertimg = variables.img>
<cfset variables.img = imageResults.img>
<cfset variables.imageInfo = imageCFC.getImageInfo(variables.img,"")>
</cffunction>
<cffunction name="setOption" access="public" output="true" returnType="void" hint="Sets values for allowed CFC options.">
<cfargument name="key" type="string" required="yes">
<cfargument name="val" type="string" required="yes">
<cfif lcase(trim(key)) eq "throwonerror">
<cfthrow message="Option Configuration Error" detail="You cannot set the throwOnError option when using ImageObject.cfc">
</cfif>
<cfset imageCFC.setOption(key, val)>
</cffunction>
<cffunction name="getOption" access="public" output="true" returnType="any" hint="Returns the current value for the specified CFC option.">
<cfargument name="key" type="string" required="yes">
<cfreturn imageCFC.getOption(key)>
</cffunction>
<cffunction name="filterFastBlur" access="public" output="true" returntype="void" hint="Internal method used for flipping and flopping images.">
<cfargument name="blurAmount" required="yes" type="numeric">
<cfargument name="iterations" required="yes" type="numeric">
<cfset var imageResults = imageCFC.filterFastBlur(variables.img,"","",blurAmount,iterations)>
<cfset variables.revertimg = variables.img>
<cfset variables.img = imageResults.img>
<cfset variables.imageInfo = imageCFC.getImageInfo(variables.img,"")>
</cffunction>
<cffunction name="filterSharpen" access="public" output="true" returntype="void" hint="Internal method used for flipping and flopping images.">
<cfset var imageResults = imageCFC.filterSharpen(variables.img,"","")>
<cfset variables.revertimg = variables.img>
<cfset variables.img = imageResults.img>
<cfset variables.imageInfo = imageCFC.getImageInfo(variables.img,"")>
</cffunction>
<cffunction name="filterPosterize" access="public" output="true" returntype="void" hint="Internal method used for flipping and flopping images.">
<cfargument name="amount" required="yes" type="string">
<cfset var imageResults = imageCFC.filterPosterize(variables.img,"","",amount)>
<cfset variables.revertimg = variables.img>
<cfset variables.img = imageResults.img>
<cfset variables.imageInfo = imageCFC.getImageInfo(variables.img,"")>
</cffunction>
<cffunction name="addText" access="public" output="true" returntype="void" hint="Add text to an image.">
<cfargument name="x" required="yes" type="numeric">
<cfargument name="y" required="yes" type="numeric">
<cfargument name="fontDetails" required="yes" type="struct">
<cfargument name="content" required="yes" type="String">
<cfset var imageResults = imageCFC.addText(variables.img,"","",x,y,fontDetails,content)>
<cfset variables.revertimg = variables.img>
<cfset variables.img = imageResults.img>
<cfset variables.imageInfo = imageCFC.getImageInfo(variables.img,"")>
</cffunction>
<cffunction name="watermark" access="public" output="false" returnType="void">
<cfargument name="wmImage" required="yes" type="Any">
<cfargument name="alpha" required="yes" type="numeric">
<cfargument name="placeAtX" required="yes" type="numeric">
<cfargument name="placeAtY" required="yes" type="numeric">
<cfset var imageResults = "">
<cfif isSimpleValue(wmImage)>
<!--- filename or URL --->
<cfset imageResults = imageCFC.watermark(variables.img,"","",wmImage,alpha,placeAtX,placeAtY)>
<cfelse>
<!--- must be a java object --->
<cfset imageResults = imageCFC.watermark(variables.img,wmImage,"","",alpha,placeAtX,placeAtY)>
</cfif>
<cfset variables.revertimg = variables.img>
<cfset variables.img = imageResults.img>
<cfset variables.imageInfo = imageCFC.getImageInfo(variables.img,"")>
</cffunction>
<cffunction name="save" access="public" output="false" returnType="void">
<cfargument name="filename" type="string" required="no">
<cfargument name="jpegCompression" type="numeric" required="no">
<cfif isDefined("arguments.jpegCompression") and isNumeric(arguments.jpegCompression)>
<cfset imageCFC.writeImage(filename,variables.img,jpegCompression)>
<cfelse>
<cfset imageCFC.writeImage(filename,variables.img)>
</cfif>
</cffunction>
<cffunction name="revert" access="public" output="true" returntype="void" hint="Undo the previous manipulation.">
<cfset variables.img = variables.revertimg>
<cfset variables.imageInfo = imageCFC.getImageInfo(variables.img,"")>
</cffunction>
</cfcomponent>

View file

@ -0,0 +1,315 @@
<cfsetting enablecfoutputonly="yes" showdebugoutput="no">
<!---
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2007 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* File Browser connector for ColdFusion 5.
* (based on the original CF connector by Hendrik Kramer - hk@lwd.de)
*
* Note:
* FCKeditor requires that the connector responds with UTF-8 encoded XML.
* As ColdFusion 5 does not fully support UTF-8 encoding, we force ASCII
* file and folder names in this connector to allow CF5 send a UTF-8
* encoded response - code points under 127 in UTF-8 are stored using a
* single byte, using the same encoding as ASCII, which is damn handy.
* This is all grand for the English speakers, like meself, but I dunno
* how others are gonna take to it. Well, the previous version of this
* connector already did this with file names and nobody seemed to mind,
* so fingers-crossed nobody will mind their folder names being munged too.
*
--->
<cfparam name="url.command">
<cfparam name="url.type">
<cfparam name="url.currentFolder">
<!--- note: no serverPath url parameter - see config.cfm if you need to set the serverPath manually --->
<cfinclude template="config.cfm">
<cfscript>
userFilesPath = config.userFilesPath;
if ( userFilesPath eq "" )
{
userFilesPath = "/userfiles/";
}
// make sure the user files path is correctly formatted
userFilesPath = replace(userFilesPath, "\", "/", "ALL");
userFilesPath = replace(userFilesPath, '//', '/', 'ALL');
if ( right(userFilesPath,1) NEQ "/" )
{
userFilesPath = userFilesPath & "/";
}
if ( left(userFilesPath,1) NEQ "/" )
{
userFilesPath = "/" & userFilesPath;
}
// make sure the current folder is correctly formatted
url.currentFolder = replace(url.currentFolder, "\", "/", "ALL");
url.currentFolder = replace(url.currentFolder, '//', '/', 'ALL');
if ( right(url.currentFolder,1) neq "/" )
{
url.currentFolder = url.currentFolder & "/";
}
if ( left(url.currentFolder,1) neq "/" )
{
url.currentFolder = "/" & url.currentFolder;
}
if ( find("/",getBaseTemplatePath()) neq 0 )
{
fs = "/";
}
else
{
fs = "\";
}
// Get the base physical path to the web root for this application. The code to determine the path automatically assumes that
// the "FCKeditor" directory in the http request path is directly off the web root for the application and that it's not a
// virtual directory or a symbolic link / junction. Use the serverPath config setting to force a physical path if necessary.
if ( len(config.serverPath) )
{
serverPath = config.serverPath;
if ( right(serverPath,1) neq fs )
{
serverPath = serverPath & fs;
}
}
else
{
serverPath = replaceNoCase(getBaseTemplatePath(),replace(cgi.script_name,"/",fs,"all"),"") & replace(userFilesPath,"/",fs,"all");
}
rootPath = left( serverPath, Len(serverPath) - Len(userFilesPath) ) ;
xmlContent = ""; // append to this string to build content
</cfscript>
<cfset resourceTypeUrl = rereplace( replace( Config.FileTypesPath[url.type], fs, "/", "all"), "/$", "") >
<cfif isDefined( "Config.FileTypesAbsolutePath" )
and structkeyexists( Config.FileTypesAbsolutePath, url.type )
and Len( Config.FileTypesAbsolutePath[url.type] )>
<cfset userFilesServerPath = Config.FileTypesAbsolutePath[url.type] & url.currentFolder>
<cfelse>
<cftry>
<cfset userFilesServerPath = expandpath( resourceTypeUrl ) & url.currentFolder>
<!--- Catch: Parameter 1 of function ExpandPath must be a relative path --->
<cfcatch type="any">
<cfset userFilesServerPath = rootPath & Config.FileTypesPath[url.type] & url.currentFolder>
</cfcatch>
</cftry>
</cfif>
<cfset userFilesServerPath = replace( userFilesServerPath, "/", fs, "all" ) >
<!--- get rid of double directory separators --->
<cfset userFilesServerPath = replace( userFilesServerPath, fs & fs, fs, "all") >
<cfif not config.enabled>
<cfset xmlContent = "<Error number=""1"" text=""This connector is disabled. Please check the 'editor/filemanager/connectors/cfm/config.cfm' file"" />">
<cfelseif find("..",url.currentFolder)>
<cfset xmlContent = "<Error number=""102"" />">
<cfelseif isDefined("Config.ConfigAllowedCommands") and not ListFind(Config.ConfigAllowedCommands, url.command)>
<cfset xmlContent = '<Error number="1" text="The &quot;' & url.command & '&quot; command isn''t allowed" />'>
<cfelseif isDefined("Config.ConfigAllowedTypes") and not ListFind(Config.ConfigAllowedTypes, url.type)>
<cfset xmlContent = '<Error number="1" text="The &quot;' & url.type & '&quot; type isn''t allowed" />'>
</cfif>
<cfset resourceTypeDirectory = left( userFilesServerPath, Len(userFilesServerPath) - Len(url.currentFolder) )>
<cfif not len(xmlContent) and not directoryexists(resourceTypeDirectory)>
<!--- create directories in physical path if they don't already exist --->
<cfset currentPath = "">
<cftry>
<cfloop list="#resourceTypeDirectory#" index="name" delimiters="#fs#">
<cfif currentPath eq "" and fs eq "\">
<!--- Without checking this, we would have in Windows \C:\ --->
<cfif not directoryExists(name)>
<cfdirectory action="create" directory="#name#" mode="755">
</cfif>
<cfelse>
<cfif not directoryExists(currentPath & fs & name)>
<cfdirectory action="create" directory="#currentPath##fs##name#" mode="755">
</cfif>
</cfif>
<cfif fs eq "\" and currentPath eq "">
<cfset currentPath = name>
<cfelse>
<cfset currentPath = currentPath & fs & name>
</cfif>
</cfloop>
<cfcatch type="any">
<!--- this should only occur as a result of a permissions problem --->
<cfset xmlContent = "<Error number=""103"" />">
</cfcatch>
</cftry>
</cfif>
<cfif not len(xmlContent)>
<!--- no errors thus far - run command --->
<!--- we need to know the physical path to the current folder for all commands --->
<cfset currentFolderPath = userFilesServerPath>
<cfswitch expression="#url.command#">
<cfcase value="FileUpload">
<cfset config_included = true >
<cfinclude template="cf5_upload.cfm">
<cfabort>
</cfcase>
<cfcase value="GetFolders">
<!--- Sort directories first, name ascending --->
<cfdirectory
action="list"
directory="#currentFolderPath#"
name="qDir"
sort="type,name">
<cfscript>
i=1;
folders = "";
while( i lte qDir.recordCount ) {
if( not compareNoCase( qDir.type[i], "FILE" ))
break;
if( not listFind(".,..", qDir.name[i]) )
folders = folders & '<Folder name="#HTMLEditFormat( qDir.name[i] )#" />';
i=i+1;
}
xmlContent = xmlContent & '<Folders>' & folders & '</Folders>';
</cfscript>
</cfcase>
<cfcase value="GetFoldersAndFiles">
<!--- Sort directories first, name ascending --->
<cfdirectory
action="list"
directory="#currentFolderPath#"
name="qDir"
sort="type,name">
<cfscript>
i=1;
folders = "";
files = "";
while( i lte qDir.recordCount ) {
if( not compareNoCase( qDir.type[i], "DIR" ) and not listFind(".,..", qDir.name[i]) ) {
folders = folders & '<Folder name="#HTMLEditFormat(qDir.name[i])#" />';
} else if( not compareNoCase( qDir.type[i], "FILE" ) ) {
fileSizeKB = round(qDir.size[i] / 1024);
files = files & '<File name="#HTMLEditFormat(qDir.name[i])#" size="#IIf( fileSizeKB GT 0, DE( fileSizeKB ), 1)#" />';
}
i=i+1;
}
xmlContent = xmlContent & '<Folders>' & folders & '</Folders>';
xmlContent = xmlContent & '<Files>' & files & '</Files>';
</cfscript>
</cfcase>
<cfcase value="CreateFolder">
<cfparam name="url.newFolderName" default="">
<cfscript>
newFolderName = url.newFolderName;
if( reFind("[^A-Za-z0-9_\-\.]", newFolderName) ) {
// Munge folder name same way as we do the filename
// This means folder names are always US-ASCII so we don't have to worry about CF5 and UTF-8
newFolderName = reReplace(newFolderName, "[^A-Za-z0-9\-\.]", "_", "all");
newFolderName = reReplace(newFolderName, "_{2,}", "_", "all");
newFolderName = reReplace(newFolderName, "([^_]+)_+$", "\1", "all");
newFolderName = reReplace(newFolderName, "$_([^_]+)$", "\1", "all");
}
</cfscript>
<cfif not len(newFolderName) or len(newFolderName) gt 255>
<cfset errorNumber = 102>
<cfelseif directoryExists(currentFolderPath & newFolderName)>
<cfset errorNumber = 101>
<cfelseif reFind("^\.\.",newFolderName)>
<cfset errorNumber = 103>
<cfelse>
<cfset errorNumber = 0>
<cftry>
<cfdirectory
action="create"
directory="#currentFolderPath##newFolderName#"
mode="755">
<cfcatch>
<!---
un-resolvable error numbers in ColdFusion:
* 102 : Invalid folder name.
* 103 : You have no permissions to create the folder.
--->
<cfset errorNumber = 110>
</cfcatch>
</cftry>
</cfif>
<cfset xmlContent = xmlContent & '<Error number="#errorNumber#" />'>
</cfcase>
<cfdefaultcase>
<cfthrow type="fckeditor.connector" message="Illegal command: #url.command#">
</cfdefaultcase>
</cfswitch>
</cfif>
<cfscript>
xmlHeader = '<?xml version="1.0" encoding="utf-8" ?><Connector command="#url.command#" resourceType="#url.type#">';
xmlHeader = xmlHeader & '<CurrentFolder path="#url.currentFolder#" url="#resourceTypeUrl##url.currentFolder#" />';
xmlFooter = '</Connector>';
</cfscript>
<cfheader name="Expires" value="#GetHttpTimeString(Now())#">
<cfheader name="Pragma" value="no-cache">
<cfheader name="Cache-Control" value="no-cache, no-store, must-revalidate">
<cfcontent reset="true" type="text/xml; charset=UTF-8">
<cfoutput>#xmlHeader##xmlContent##xmlFooter#</cfoutput>

View file

@ -0,0 +1,296 @@
<cfsetting enablecfoutputonly="Yes">
<!---
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2007 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* This is the "File Uploader" for ColdFusion 5.
* Based on connector.cfm by Mark Woods (mark@thickpaddy.com)
*
* Note:
* FCKeditor requires that the connector responds with UTF-8 encoded XML.
* As ColdFusion 5 does not fully support UTF-8 encoding, we force ASCII
* file and folder names in this connector to allow CF5 send a UTF-8
* encoded response - code points under 127 in UTF-8 are stored using a
* single byte, using the same encoding as ASCII, which is damn handy.
* This is all grand for the English speakers, like meself, but I dunno
* how others are gonna take to it. Well, the previous version of this
* connector already did this with file names and nobody seemed to mind,
* so fingers-crossed nobody will mind their folder names being munged too.
*
--->
<cfparam name="url.command" default="QuickUpload">
<cfparam name="url.type" default="File">
<cfparam name="url.currentFolder" default="/">
<cfif not isDefined("config_included")>
<cfinclude template="config.cfm">
</cfif>
<cfscript>
function SendUploadResults(errorNumber, fileUrl, fileName, customMsg)
{
WriteOutput('<script type="text/javascript">');
WriteOutput('window.parent.OnUploadCompleted(' & errorNumber & ', "' & JSStringFormat(fileUrl) & '", "' & JSStringFormat(fileName) & '", "' & JSStringFormat(customMsg) & '");' );
WriteOutput('</script>');
}
</cfscript>
<cfif NOT config.enabled>
<cfset SendUploadResults(1, "", "", "This file uploader is disabled. Please check the ""editor/filemanager/connectors/cfm/config.cfm"" file")>
<cfabort>
</cfif>
<cfif isDefined("Config.ConfigAllowedCommands") and not ListFind(Config.ConfigAllowedCommands, url.command)>
<cfset SendUploadResults(1, "", "", "The """ & url.command & """ command isn't allowed")>
<cfabort>
</cfif>
<cfif isDefined("Config.ConfigAllowedTypes") and not ListFind(Config.ConfigAllowedTypes, url.type)>
<cfset SendUploadResults(1, "", "", "The """ & url.type & """ type isn't allowed")>
<cfabort>
</cfif>
<cfif find( "..", url.currentFolder)>
<cfset SendUploadResults(102)>
<cfabort>
</cfif>
<cfscript>
userFilesPath = config.userFilesPath;
if ( userFilesPath eq "" ) {
userFilesPath = "/userfiles/";
}
// make sure the user files path is correctly formatted
userFilesPath = replace(userFilesPath, "\", "/", "ALL");
userFilesPath = replace(userFilesPath, '//', '/', 'ALL');
if ( right(userFilesPath,1) NEQ "/" ) {
userFilesPath = userFilesPath & "/";
}
if ( left(userFilesPath,1) NEQ "/" ) {
userFilesPath = "/" & userFilesPath;
}
// make sure the current folder is correctly formatted
url.currentFolder = replace(url.currentFolder, "\", "/", "ALL");
url.currentFolder = replace(url.currentFolder, '//', '/', 'ALL');
if ( right(url.currentFolder,1) neq "/" ) {
url.currentFolder = url.currentFolder & "/";
}
if ( left(url.currentFolder,1) neq "/" ) {
url.currentFolder = "/" & url.currentFolder;
}
if (find("/",getBaseTemplatePath())) {
fs = "/";
} else {
fs = "\";
}
// Get the base physical path to the web root for this application. The code to determine the path automatically assumes that
// the "FCKeditor" directory in the http request path is directly off the web root for the application and that it's not a
// virtual directory or a symbolic link / junction. Use the serverPath config setting to force a physical path if necessary.
if ( len(config.serverPath) ) {
serverPath = config.serverPath;
if ( right(serverPath,1) neq fs ) {
serverPath = serverPath & fs;
}
} else {
serverPath = replaceNoCase(getBaseTemplatePath(),replace(cgi.script_name,"/",fs,"all"),"") & replace(userFilesPath,"/",fs,"all");
}
rootPath = left( serverPath, Len(serverPath) - Len(userFilesPath) ) ;
</cfscript>
<cfif url.command eq "QuickUpload">
<cfset resourceTypeUrl = rereplace( replace( Config.QuickUploadPath[url.type], fs, "/", "all"), "/$", "") >
<cfif isDefined( "Config.QuickUploadAbsolutePath" )
and structkeyexists( Config.QuickUploadAbsolutePath, url.type )
and Len( Config.QuickUploadAbsolutePath[url.type] )>
<cfset userFilesServerPath = Config.QuickUploadAbsolutePath[url.type] & url.currentFolder>
<cfelse>
<cftry>
<cfset userFilesServerPath = expandpath( resourceTypeUrl ) & url.currentFolder>
<!--- Catch: Parameter 1 of function ExpandPath must be a relative path --->
<cfcatch type="any">
<cfset userFilesServerPath = rootPath & Config.QuickUploadPath[url.type] & url.currentFolder>
</cfcatch>
</cftry>
</cfif>
<cfelse>
<cfset resourceTypeUrl = rereplace( replace( Config.FileTypesPath[url.type], fs, "/", "all"), "/$", "") >
<cfif isDefined( "Config.FileTypesAbsolutePath" )
and structkeyexists( Config.FileTypesAbsolutePath, url.type )
and Len( Config.FileTypesAbsolutePath[url.type] )>
<cfset userFilesServerPath = Config.FileTypesAbsolutePath[url.type] & url.currentFolder>
<cfelse>
<cftry>
<cfset userFilesServerPath = expandpath( resourceTypeUrl ) & url.currentFolder>
<!--- Catch: Parameter 1 of function ExpandPath must be a relative path --->
<cfcatch type="any">
<cfset userFilesServerPath = rootPath & Config.FileTypesPath[url.type] & url.currentFolder>
</cfcatch>
</cftry>
</cfif>
</cfif>
<cfset userFilesServerPath = replace( userFilesServerPath, "/", fs, "all" ) >
<!--- get rid of double directory separators --->
<cfset userFilesServerPath = replace( userFilesServerPath, fs & fs, fs, "all") >
<!--- create resource type directory if not exists --->
<cfset resourceTypeDirectory = left( userFilesServerPath, Len(userFilesServerPath) - Len(url.currentFolder) )>
<cfif not directoryexists( resourceTypeDirectory )>
<cfset currentPath = "">
<cftry>
<cfloop list="#resourceTypeDirectory#" index="name" delimiters="#fs#">
<cfif currentPath eq "" and fs eq "\">
<!--- Without checking this, we would have in Windows \C:\ --->
<cfif not directoryExists(name)>
<cfdirectory action="create" directory="#name#" mode="755">
</cfif>
<cfelse>
<cfif not directoryExists(currentPath & fs & name)>
<cfdirectory action="create" directory="#currentPath##fs##name#" mode="755">
</cfif>
</cfif>
<cfif fs eq "\" and currentPath eq "">
<cfset currentPath = name>
<cfelse>
<cfset currentPath = currentPath & fs & name>
</cfif>
</cfloop>
<cfcatch type="any">
<!--- this should only occur as a result of a permissions problem --->
<cfset SendUploadResults(103)>
<cfabort>
</cfcatch>
</cftry>
</cfif>
<cfset currentFolderPath = userFilesServerPath>
<cfset resourceType = url.type>
<cfset fileName = "">
<cfset fileExt = "">
<!--- Can be overwritten. The last value will be sent with the result --->
<cfset customMsg = "">
<cftry>
<!--- first upload the file with an unique filename --->
<cffile action="upload"
fileField="NewFile"
destination="#currentFolderPath#"
nameConflict="makeunique"
mode="644"
attributes="normal">
<cfif cffile.fileSize EQ 0>
<cfthrow>
</cfif>
<cfset lAllowedExtensions = config.allowedExtensions[#resourceType#]>
<cfset lDeniedExtensions = config.deniedExtensions[#resourceType#]>
<cfif ( len(lAllowedExtensions) and not listFindNoCase(lAllowedExtensions,cffile.ServerFileExt) )
or ( len(lDeniedExtensions) and listFindNoCase(lDeniedExtensions,cffile.ServerFileExt) )>
<cfset errorNumber = "202">
<cffile action="delete" file="#cffile.ServerDirectory##fs##cffile.ServerFile#">
<cfelse>
<cfscript>
errorNumber = 0;
fileName = cffile.ClientFileName ;
fileExt = cffile.ServerFileExt ;
fileExisted = false ;
// munge filename for html download. Only a-z, 0-9, _, - and . are allowed
if( reFind("[^A-Za-z0-9_\-\.]", fileName) ) {
fileName = reReplace(fileName, "[^A-Za-z0-9\-\.]", "_", "ALL");
fileName = reReplace(fileName, "_{2,}", "_", "ALL");
fileName = reReplace(fileName, "([^_]+)_+$", "\1", "ALL");
fileName = reReplace(fileName, "$_([^_]+)$", "\1", "ALL");
}
// remove additional dots from file name
if( isDefined("Config.ForceSingleExtension") and Config.ForceSingleExtension )
fileName = replace( fileName, '.', "_", "all" ) ;
// When the original filename already exists, add numbers (0), (1), (2), ... at the end of the filename.
if( compare( cffile.ServerFileName, fileName ) ) {
counter = 0;
tmpFileName = fileName;
while( fileExists("#currentFolderPath##fileName#.#fileExt#") ) {
fileExisted = true ;
counter = counter + 1 ;
fileName = tmpFileName & '(#counter#)' ;
}
}
</cfscript>
<!--- Rename the uploaded file, if neccessary --->
<cfif compare(cffile.ServerFileName,fileName)>
<cfif fileExisted>
<cfset errorNumber = "201">
</cfif>
<cffile
action="rename"
source="#currentFolderPath##cffile.ServerFileName#.#cffile.ServerFileExt#"
destination="#currentFolderPath##fileName#.#fileExt#"
mode="644"
attributes="normal">
</cfif>
</cfif>
<cfcatch type="any">
<cfset errorNumber = "1">
<cfset customMsg = cfcatch.message >
</cfcatch>
</cftry>
<cfif errorNumber EQ 0>
<!--- file was uploaded succesfully --->
<cfset SendUploadResults(errorNumber, '#resourceTypeUrl##url.currentFolder##fileName#.#fileExt#', "", "")>
<cfabort>
<cfelseif errorNumber EQ 201>
<!--- file was changed (201), submit the new filename --->
<cfset SendUploadResults(errorNumber, '#resourceTypeUrl##url.currentFolder##fileName#.#fileExt#', replace( fileName & "." & fileExt, "'", "\'", "ALL"), customMsg)>
<cfabort>
<cfelse>
<!--- An error occured(202). Submit only the error code and a message (if available). --->
<cfset SendUploadResults(errorNumber, '', '', customMsg)>
<cfabort>
</cfif>

View file

@ -0,0 +1,68 @@
<cfsetting enablecfoutputonly="Yes">
<!---
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2007 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* This file include the functions that create the base XML output by the ColdFusion Connector (MX 6.0 and above).
--->
<cffunction name="SetXmlHeaders" returntype="void">
<cfheader name="Expires" value="#GetHttpTimeString(Now())#">
<cfheader name="Pragma" value="no-cache">
<cfheader name="Cache-Control" value="no-cache, no-store, must-revalidate">
<cfcontent reset="true" type="text/xml; charset=UTF-8">
</cffunction>
<cffunction name="CreateXmlHeader" returntype="void" output="true">
<cfargument name="command" required="true">
<cfargument name="resourceType" required="true">
<cfargument name="currentFolder" required="true">
<cfset SetXmlHeaders()>
<cfoutput><?xml version="1.0" encoding="utf-8" ?></cfoutput>
<cfoutput><Connector command="#ARGUMENTS.command#" resourceType="#ARGUMENTS.resourceType#"></cfoutput>
<cfoutput><CurrentFolder path="#HTMLEditFormat(ARGUMENTS.currentFolder)#" url="#HTMLEditFormat( GetUrlFromPath( resourceType, currentFolder, command ) )#" /></cfoutput>
<cfset REQUEST.HeaderSent = true>
</cffunction>
<cffunction name="CreateXmlFooter" returntype="void" output="true">
<cfoutput></Connector></cfoutput>
</cffunction>
<cffunction name="SendError" returntype="void" output="true">
<cfargument name="number" required="true" type="Numeric">
<cfargument name="text" required="true">
<cfif isDefined("REQUEST.HeaderSent") and REQUEST.HeaderSent>
<cfset SendErrorNode( ARGUMENTS.number, ARGUMENTS.text )>
<cfset CreateXmlFooter() >
<cfelse>
<cfset SetXmlHeaders()>
<cfoutput><?xml version="1.0" encoding="utf-8" ?></cfoutput>
<cfoutput><Connector></cfoutput>
<cfset SendErrorNode( ARGUMENTS.number, ARGUMENTS.text )>
<cfset CreateXmlFooter() >
</cfif>
<cfabort>
</cffunction>
<cffunction name="SendErrorNode" returntype="void" output="true">
<cfargument name="number" required="true" type="Numeric">
<cfargument name="text" required="true">
<cfoutput><Error number="#ARGUMENTS.number#" text="#htmleditformat(ARGUMENTS.text)#" /></cfoutput>
</cffunction>

View file

@ -0,0 +1,225 @@
<cfsetting enablecfoutputonly="Yes">
<!---
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2007 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* This file include the functions that handle the Command requests
* in the ColdFusion Connector (MX 6.0 and above).
--->
<cffunction name="FileUpload" returntype="void" output="true">
<cfargument name="resourceType" type="string" required="yes" default="">
<cfargument name="currentFolder" type="string" required="yes" default="">
<cfargument name="sCommand" type="string" required="yes" default="">
<cfset var sFileName = "">
<cfset var sFilePart = "">
<cfset var sFileExt = "">
<cfset var sFileUrl = "">
<cfset var sTempFilePath = "">
<cfset var errorNumber = 0>
<cfset var customMsg = 0>
<cfset var counter = 0>
<cfset var destination = "">
<cftry>
<cffile action="UPLOAD" filefield="NewFile" destination="#GetTempDirectory()#" nameconflict="makeunique" mode="0755" />
<cfset sTempFilePath = CFFILE.ServerDirectory & REQUEST.fs & CFFILE.ServerFile>
<!--- Map the virtual path to the local server path. --->
<cfset sServerDir = ServerMapFolder( ARGUMENTS.resourceType, ARGUMENTS.currentFolder, ARGUMENTS.sCommand) >
<!--- Get the uploaded file name. --->
<cfset sFileName = SanitizeFileName( CFFILE.ClientFile ) >
<cfset sOriginalFileName = sFileName >
<cfif isDefined( "REQUEST.Config.SecureImageUploads" ) and REQUEST.Config.SecureImageUploads>
<cfif not IsImageValid( sTempFilePath, CFFILE.ClientFileExt )>
<cftry>
<cffile action="delete" file="#sTempFilePath#">
<cfcatch type="any">
</cfcatch>
</cftry>
<cfthrow errorcode="202" type="fckeditor">
</cfif>
</cfif>
<cfif isDefined( "REQUEST.Config.HtmlExtensions" ) and not listFindNoCase( REQUEST.Config.HtmlExtensions, CFFILE.ClientFileExt )>
<cfif DetectHtml( sTempFilePath )>
<cftry>
<cffile action="delete" file="#sTempFilePath#">
<cfcatch type="any">
</cfcatch>
</cftry>
<cfthrow errorcode="202" type="fckeditor">
</cfif>
</cfif>
<cfif not IsAllowedExt( CFFILE.ClientFileExt, ARGUMENTS.resourceType )>
<cftry>
<cffile action="delete" file="#sTempFilePath#">
<cfcatch type="any">
</cfcatch>
</cftry>
<cfthrow errorcode="202" type="fckeditor">
</cfif>
<!--- When the original filename already exists, add numbers (0), (1), (2), ... at the end of the filename. --->
<cfscript>
sFileExt = GetExtension( sFileName ) ;
sFilePart = RemoveExtension( sFileName );
while( fileExists( sServerDir & sFileName ) )
{
counter = counter + 1;
sFileName = sFilePart & '(#counter#).' & CFFILE.ClientFileExt;
errorNumber = 201;
}
</cfscript>
<cfset destination = sServerDir & sFileName>
<!---
<cfdump var="#sTempFilePath#">
<cfoutput ><br /></cfoutput>
<cfdump var="#destination#">
<cfabort>
--->
<cflock name="#destination#" timeout="30" type="Exclusive">
<cftry>
<cffile action="move" source="#sTempFilePath#" destination="#destination#" mode="755">
<!--- omit CF 6.1 error during moving uploaded file, just copy that file instead of moving --->
<cfcatch type="any">
<cffile action="copy" source="#sTempFilePath#" destination="#destination#" mode="755">
</cfcatch>
</cftry>
</cflock>
<cfset sFileUrl = CombinePaths( GetResourceTypePath( ARGUMENTS.resourceType, sCommand ) , ARGUMENTS.currentFolder ) >
<cfset sFileUrl = CombinePaths( sFileUrl , sFileName ) >
<cfcatch type="fckeditor">
<cfset errorNumber = CFCATCH.ErrorCode>
</cfcatch>
<cfcatch type="any">
<cfset errorNumber = "1">
<cfset customMsg = CFCATCH.Message >
</cfcatch>
</cftry>
<cfset SendUploadResults( errorNumber, sFileUrl, sFileName, customMsg ) >
</cffunction>
<cffunction name="GetFolders" returntype="void" output="true">
<cfargument name="resourceType" type="String" required="true">
<cfargument name="currentFolder" type="String" required="true">
<cfset var i = 1>
<cfset var folders = "">
<!--- Map the virtual path to the local server path --->
<cfset var sServerDir = ServerMapFolder( ARGUMENTS.resourceType, ARGUMENTS.currentFolder, "GetFolders" ) >
<!--- Sort directories first, name ascending --->
<cfdirectory action="list" directory="#sServerDir#" name="qDir" sort="type,name">
<cfscript>
while( i lte qDir.recordCount )
{
if( compareNoCase( qDir.type[i], "FILE" ) and not listFind( ".,..", qDir.name[i] ) )
{
folders = folders & '<Folder name="#HTMLEditFormat( qDir.name[i] )#" />' ;
}
i = i + 1;
}
</cfscript>
<cfoutput><Folders>#folders#</Folders></cfoutput>
</cffunction>
<cffunction name="GetFoldersAndfiles" returntype="void" output="true">
<cfargument name="resourceType" type="String" required="true">
<cfargument name="currentFolder" type="String" required="true">
<cfset var i = 1>
<cfset var folders = "">
<cfset var files = "">
<!--- Map the virtual path to the local server path --->
<cfset var sServerDir = ServerMapFolder( ARGUMENTS.resourceType, ARGUMENTS.currentFolder, "GetFolders" ) >
<!--- Sort directories first, name ascending --->
<cfdirectory action="list" directory="#sServerDir#" name="qDir" sort="type,name">
<cfscript>
while( i lte qDir.recordCount )
{
if( not compareNoCase( qDir.type[i], "DIR" ) and not listFind( ".,..", qDir.name[i] ) )
{
folders = folders & '<Folder name="#HTMLEditFormat(qDir.name[i])#" />' ;
}
else if( not compareNoCase( qDir.type[i], "FILE" ) )
{
fileSizeKB = round(qDir.size[i] / 1024) ;
files = files & '<File name="#HTMLEditFormat(qDir.name[i])#" size="#IIf( fileSizeKB GT 0, DE( fileSizeKB ), 1)#" />' ;
}
i = i + 1 ;
}
</cfscript>
<cfoutput><Folders>#folders#</Folders></cfoutput>
<cfoutput><Files>#files#</Files></cfoutput>
</cffunction>
<cffunction name="CreateFolder" returntype="void" output="true">
<cfargument name="resourceType" required="true" type="string">
<cfargument name="currentFolder" required="true" type="string">
<cfset var sNewFolderName = url.newFolderName >
<cfset var sServerDir = "" >
<cfset var errorNumber = 0>
<cfset var sErrorMsg = "">
<cfset var currentFolderPath = ServerMapFolder( ARGUMENTS.resourceType, ARGUMENTS.currentFolder, 'CreateFolder' )>
<cfparam name="url.newFolderName" default="">
<cfscript>
sNewFolderName = SanitizeFolderName( sNewFolderName ) ;
</cfscript>
<cfif not len( sNewFolderName ) or len( sNewFolderName ) gt 255>
<cfset errorNumber = 102>
<cfelseif directoryExists( currentFolderPath & sNewFolderName )>
<cfset errorNumber = 101>
<cfelseif find( "..", sNewFolderName )>
<cfset errorNumber = 103>
<cfelse>
<cfset errorNumber = 0>
<!--- Map the virtual path to the local server path of the current folder. --->
<cfset sServerDir = currentFolderPath & sNewFolderName >
<cftry>
<cfdirectory action="create" directory="#currentFolderPath##sNewFolderName#" mode="755">
<cfcatch type="any">
<!---
un-resolvable error numbers in ColdFusion:
* 102 : Invalid folder name.
* 103 : You have no permissions to create the folder.
--->
<cfset errorNumber = 110>
</cfcatch>
</cftry>
</cfif>
<cfoutput><Error number="#errorNumber#" originalDescription="#HTMLEditFormat(sErrorMsg)#" /></cfoutput>
</cffunction>

View file

@ -0,0 +1,89 @@
<cfsetting enablecfoutputonly="yes" showdebugoutput="no">
<!---
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2007 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* File Browser connector for ColdFusion (MX 6.0 and above).
* (based on the original CF connector by Hendrik Kramer - hk@lwd.de)
*
--->
<cfparam name="url.command">
<cfparam name="url.type">
<cfparam name="url.currentFolder">
<!--- note: no serverPath url parameter - see config.cfm if you need to set the serverPath manually --->
<cfinclude template="config.cfm">
<cfinclude template="cf_util.cfm">
<cfinclude template="cf_io.cfm">
<cfinclude template="cf_basexml.cfm">
<cfinclude template="cf_commands.cfm">
<cfif not Config.Enabled>
<cfset SendError( 1, 'This connector is disabled. Please check the "editor/filemanager/connectors/cfm/config.cfm" file' )>
</cfif>
<cfset REQUEST.Config = Config>
<cfif find( "/", getBaseTemplatePath() ) >
<cfset REQUEST.Fs = "/">
<cfelse>
<cfset REQUEST.Fs = "\">
</cfif>
<cfset DoResponse() >
<cffunction name="DoResponse" output="true" returntype="void">
<!--- Get the main request informaiton. --->
<cfset var sCommand = "#URL.Command#" >
<cfset var sResourceType = URL.Type >
<cfset var sCurrentFolder = GetCurrentFolder() >
<!--- Check if it is an allowed command --->
<cfif not IsAllowedCommand( sCommand ) >
<cfset SendError( 1, "The """ & sCommand & """ command isn't allowed" ) >
</cfif>
<!--- Check if it is an allowed type. --->
<cfif not IsAllowedType( sResourceType ) >
<cfset SendError( 1, 'Invalid type specified' ) >
</cfif>
<!--- File Upload doesn't have to Return XML, so it must be intercepted before anything. --->
<cfif sCommand eq "FileUpload">
<cfset FileUpload( sResourceType, sCurrentFolder, sCommand )>
<cfabort>
</cfif>
<cfset CreateXmlHeader( sCommand, sResourceType, sCurrentFolder )>
<!--- Execute the required command. --->
<cfif sCommand eq "GetFolders">
<cfset GetFolders( sResourceType, sCurrentFolder ) >
<cfelseif sCommand eq "GetFoldersAndFiles">
<cfset GetFoldersAndFiles( sResourceType, sCurrentFolder ) >
<cfelseif sCommand eq "CreateFolder">
<cfset CreateFolder( sResourceType, sCurrentFolder ) >
</cfif>
<cfset CreateXmlFooter()>
<cfexit>
</cffunction>

View file

@ -0,0 +1,288 @@
<cfsetting enablecfoutputonly="Yes">
<!---
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2007 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* This file include IO specific functions used by the ColdFusion Connector (MX 6.0 and above).
*
--->
<cffunction name="CombinePaths" returntype="String" output="true">
<cfargument name="sBasePath" required="true">
<cfargument name="sFolder" required="true">
<cfset sBasePath = RemoveFromEnd( sBasePath, "/" )>
<cfset sBasePath = RemoveFromEnd( sBasePath, "\" )>
<cfreturn sBasePath & "/" & RemoveFromStart( ARGUMENTS.sFolder, '/' )>
</cffunction>
<cffunction name="GetResourceTypePath" returntype="String" output="false">
<cfargument name="resourceType" required="true">
<cfargument name="sCommand" required="true">
<cfif ARGUMENTS.sCommand eq "QuickUpload">
<cfreturn REQUEST.Config['QuickUploadPath'][ARGUMENTS.resourceType]>
<cfelse>
<cfreturn REQUEST.Config['FileTypesPath'][ARGUMENTS.resourceType]>
</cfif>
</cffunction>
<cffunction name="GetResourceTypeDirectory" returntype="String" output="false">
<cfargument name="resourceType" required="true">
<cfargument name="sCommand" required="true">
<cfif ARGUMENTS.sCommand eq "QuickUpload">
<cfif isDefined( "REQUEST.Config.QuickUploadAbsolutePath" )
and structkeyexists( REQUEST.Config.QuickUploadAbsolutePath, ARGUMENTS.resourceType )
and Len( REQUEST.Config.QuickUploadAbsolutePath[ARGUMENTS.resourceType] )>
<cfreturn REQUEST.Config.QuickUploadAbsolutePath[ARGUMENTS.resourceType]>
</cfif>
<cfreturn expandpath( REQUEST.Config.QuickUploadPath[ARGUMENTS.resourceType] )>
<cfelse>
<cfif isDefined( "REQUEST.Config.FileTypesAbsolutePath" )
and structkeyexists( REQUEST.Config.FileTypesAbsolutePath, ARGUMENTS.resourceType )
and Len( REQUEST.Config.FileTypesAbsolutePath[ARGUMENTS.resourceType] )>
<cfreturn REQUEST.Config.FileTypesAbsolutePath[ARGUMENTS.resourceType]>
</cfif>
<cfreturn expandpath( REQUEST.Config.FileTypesPath[ARGUMENTS.resourceType] )>
</cfif>
</cffunction>
<cffunction name="GetUrlFromPath" returntype="String" output="false">
<cfargument name="resourceType" required="true">
<cfargument name="folderPath" required="true">
<cfargument name="sCommand" required="true">
<cfreturn CombinePaths( GetResourceTypePath( ARGUMENTS.resourceType, ARGUMENTS.sCommand ), ARGUMENTS.folderPath )>
</cffunction>
<cffunction name="RemoveExtension" output="false" returntype="String">
<cfargument name="fileName" required="true">
<cfset var pos = find( ".", reverse ( ARGUMENTS.fileName ) )>
<cfreturn mid( ARGUMENTS.fileName, 1, Len( ARGUMENTS.fileName ) - pos ) >
</cffunction>
<cffunction name="GetExtension" output="false" returntype="String">
<cfargument name="fileName" required="true">
<cfset var pos = find( ".", reverse ( ARGUMENTS.fileName ) )>
<cfif not pos>
<cfreturn "">
</cfif>
<cfreturn mid( ARGUMENTS.fileName, pos, Len( ARGUMENTS.fileName ) - pos ) >
</cffunction>
<cffunction name="ServerMapFolder" returntype="String" output="false">
<cfargument name="resourceType" required="true">
<cfargument name="folderPath" required="true">
<cfargument name="sCommand" required="true">
<!--- Get the resource type directory. --->
<cfset var sResourceTypePath = GetResourceTypeDirectory( ARGUMENTS.resourceType, ARGUMENTS.sCommand ) >
<!--- Ensure that the directory exists. --->
<cfset var sErrorMsg = CreateServerFolder( sResourceTypePath ) >
<cfif sErrorMsg neq ''>
<cfset SendError( 1, 'Error creating folder "' & sResourceTypePath & '" (' & sErrorMsg & ')' )>
</cfif>
<!--- Return the resource type directory combined with the required path. --->
<cfreturn CombinePaths( sResourceTypePath , ARGUMENTS.folderPath )>
</cffunction>
<cffunction name="GetParentFolder" returntype="string" output="false">
<cfargument name="folderPath" required="true">
<cfreturn rereplace(ARGUMENTS.folderPath, "[/\\\\][^/\\\\]+[/\\\\]?$", "")>
</cffunction>
<cffunction name="CreateServerFolder" returntype="String" output="false">
<cfargument name="folderPath">
<!--- Ensure the folder path has no double-slashes, or mkdir may fail on certain platforms --->
<cfset folderPath = rereplace(ARGUMENTS.folderPath, "//+", "/", "all")>
<cfif directoryexists(ARGUMENTS.folderPath) or fileexists(ARGUMENTS.folderPath)>
<cfreturn "">
<cfelse>
<cftry>
<cfdirectory action="create" mode="0755" directory="#ARGUMENTS.folderPath#">
<cfcatch type="any">
<cfreturn CFCATCH.Message>
</cfcatch>
</cftry>
</cfif>
<cfreturn "">
</cffunction>
<cffunction name="IsAllowedExt" returntype="boolean" output="false">
<cfargument name="sExtension" required="true">
<cfargument name="resourceType" required="true">
<cfif isDefined( "REQUEST.Config.AllowedExtensions." & ARGUMENTS.resourceType )
and listLen( REQUEST.Config.AllowedExtensions[ARGUMENTS.resourceType] )
and not listFindNoCase( REQUEST.Config.AllowedExtensions[ARGUMENTS.resourceType], ARGUMENTS.sExtension )>
<cfreturn false>
</cfif>
<cfif isDefined( "REQUEST.Config.DeniedExtensions." & ARGUMENTS.resourceType )
and listLen( REQUEST.Config.DeniedExtensions[ARGUMENTS.resourceType] )
and listFindNoCase( REQUEST.Config.DeniedExtensions[ARGUMENTS.resourceType], ARGUMENTS.sExtension )>
<cfreturn false>
</cfif>
<cfreturn true>
</cffunction>
<cffunction name="IsAllowedType" returntype="boolean" output="false">
<cfargument name="resourceType">
<cfif not listFindNoCase( REQUEST.Config.ConfigAllowedTypes, ARGUMENTS.resourceType )>
<cfreturn false>
</cfif>
<cfreturn true>
</cffunction>
<cffunction name="IsAllowedCommand" returntype="boolean" output="true">
<cfargument name="sCommand" required="true" type="String">
<cfif not listFindNoCase( REQUEST.Config.ConfigAllowedCommands, ARGUMENTS.sCommand )>
<cfreturn false>
</cfif>
<cfreturn true>
</cffunction>
<cffunction name="GetCurrentFolder" returntype="String" output="false">
<cfset var sCurrentFolder = "/">
<cfif isDefined( "URL.CurrentFolder" )>
<cfset sCurrentFolder = URL.CurrentFolder>
</cfif>
<!--- Check the current folder syntax (must begin and start with a slash). --->
<cfif not refind( "/$", sCurrentFolder)>
<cfset sCurrentFolder = sCurrentFolder & "/">
</cfif>
<cfif not refind( "^/", sCurrentFolder )>
<cfset sCurrentFolder = "/" & sCurrentFolder>
</cfif>
<!--- Ensure the folder path has no double-slashes, or mkdir may fail on certain platforms --->
<cfset sCurrentFolder = rereplace( sCurrentFolder, "//+", "/", "all" )>
<cfif find( "..", sCurrentFolder)>
<cfset SendError( 102, "" )>
</cfif>
<cfreturn sCurrentFolder>
</cffunction>
<cffunction name="SanitizeFolderName" returntype="String" output="false">
<cfargument name="sNewFolderName" required="true">
<!--- Do a cleanup of the folder name to avoid possible problems --->
<!--- Remove . \ / | : ? * " < > --->
<cfset sNewFolderName = rereplace( sNewFolderName, '\.+|\\+|\/+|\|+|\:+|\?+|\*+|"+|<+|>+', "_", "all" )>
<cfreturn sNewFolderName>
</cffunction>
<cffunction name="BinaryFileRead" returntype="String" output="true">
<cfargument name="fileName" required="true" type="string">
<cfargument name="bytes" required="true" type="Numeric">
<cfscript>
var chunk = "";
var fileReaderClass = "";
var fileReader = "";
var file = "";
var done = false;
var counter = 0;
var byteArray = "";
if( not fileExists( ARGUMENTS.fileName ) )
{
return "" ;
}
if (REQUEST.CFVersion gte 8)
{
file = FileOpen( ARGUMENTS.fileName, "readbinary" ) ;
byteArray = FileRead( file, 1024 ) ;
chunk = toString( toBinary( toBase64( byteArray ) ) ) ;
FileClose( file ) ;
}
else
{
fileReaderClass = createObject("java", "java.io.FileInputStream");
fileReader = fileReaderClass.init(fileName);
while(not done)
{
char = fileReader.read();
counter = counter + 1;
if ( char eq -1 or counter eq ARGUMENTS.bytes)
{
done = true;
}
else
{
chunk = chunk & chr(char) ;
}
}
}
</cfscript>
<cfreturn chunk>
</cffunction>
<cffunction name="SendUploadResults" returntype="String" output="true">
<cfargument name="errorNumber" required="true" type="Numeric">
<cfargument name="fileUrl" required="false" type="String" default="">
<cfargument name="fileName" required="false" type="String" default="">
<cfargument name="customMsg" required="false" type="String" default="">
<cfoutput>
<script type="text/javascript">
window.parent.OnUploadCompleted( #errorNumber#, "#JSStringFormat(fileUrl)#", "#JSStringFormat(fileName)#", "#JSStringFormat(customMsg)#" );
</script>
</cfoutput>
<cfabort>
</cffunction>
<cffunction name="SanitizeFileName" returntype="String" output="false">
<cfargument name="sNewFileName" required="true">
<cfif isDefined("REQUEST.Config.ForceSingleExtension") and REQUEST.Config.ForceSingleExtension>
<cfset sNewFileName = rereplace( sNewFileName, '\.(?![^.]*$)', "_", "all" )>
</cfif>
<!--- Do a cleanup of the file name to avoid possible problems --->
<!--- Remove \ / | : ? * " < > --->
<cfset sNewFileName = rereplace( sNewFileName, '\\[.]+|\\+|\/+|\|+|\:+|\?+|\*+|"+|<+|>+', "_", "all" )>
<cfreturn sNewFileName>
</cffunction>

View file

@ -0,0 +1,68 @@
<cfsetting enablecfoutputonly="yes" showdebugoutput="no">
<!---
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2007 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* File Browser connector for ColdFusion (MX 6.0 and above).
* (based on the original CF connector by Hendrik Kramer - hk@lwd.de)
--->
<cfparam name="url.type" default="File">
<cfparam name="url.currentFolder" default="/">
<!--- note: no serverPath url parameter - see config.cfm if you need to set the serverPath manually --->
<cfinclude template="config.cfm">
<cfinclude template="cf_util.cfm">
<cfinclude template="cf_io.cfm">
<cfinclude template="cf_commands.cfm">
<cfset REQUEST.Config = Config>
<cfif find( "/", getBaseTemplatePath() ) >
<cfset REQUEST.Fs = "/">
<cfelse>
<cfset REQUEST.Fs = "\">
</cfif>
<cfif not Config.Enabled>
<cfset SendUploadResults( '1', '', '', 'This file uploader is disabled. Please check the "editor/filemanager/connectors/cfm/config.cfm" file' )>
</cfif>
<cfset sCommand = 'QuickUpload'>
<cfset sType = "File">
<cfif isDefined( "URL.Type" )>
<cfset sType = URL.Type>
</cfif>
<cfset sCurrentFolder = GetCurrentFolder()>
<!--- Is enabled the upload? --->
<cfif not IsAllowedCommand( sCommand )>
<cfset SendUploadResults( "1", "", "", "The """ & sCommand & """ command isn't allowed" )>
</cfif>
<!--- Check if it is an allowed type. --->
<cfif not IsAllowedType( sType )>
<cfset SendUploadResults( "1", "", "", "Invalid type specified" ) >
</cfif>
<cfset FileUpload( sType, sCurrentFolder, sCommand )>

View file

@ -0,0 +1,132 @@
<cfsetting enablecfoutputonly="Yes">
<!---
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2007 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* This file include generic functions used by the ColdFusion Connector (MX 6.0 and above).
--->
<cffunction name="RemoveFromStart" output="false" returntype="String">
<cfargument name="sourceString" type="String">
<cfargument name="charToRemove" type="String">
<cfif left(ARGUMENTS.sourceString, 1) eq ARGUMENTS.charToRemove>
<cfreturn mid( ARGUMENTS.sourceString, 2, len(ARGUMENTS.sourceString) -1 )>
</cfif>
<cfreturn ARGUMENTS.sourceString>
</cffunction>
<cffunction name="RemoveFromEnd" output="false" returntype="String">
<cfargument name="sourceString" type="String">
<cfargument name="charToRemove" type="String">
<cfif right(ARGUMENTS.sourceString, 1) eq ARGUMENTS.charToRemove>
<cfreturn mid( ARGUMENTS.sourceString, 1, len(ARGUMENTS.sourceString) -1 )>
</cfif>
<cfreturn ARGUMENTS.sourceString>
</cffunction>
<!---
Check file content.
Currently this function validates only image files.
Returns false if file is invalid.
detectionLevel:
0 = none
1 = check image size for images,
2 = use DetectHtml for images
---->
<cffunction name="IsImageValid" returntype="boolean" output="true">
<cfargument name="filePath" required="true" type="String">
<cfargument name="extension" required="true" type="String">
<cfset var imageCFC = "">
<cfset var imageInfo = "">
<cfif not ListFindNoCase("gif,jpeg,jpg,png,swf,psd,bmp,iff,tiff,tif,swc,jpc,jp2,jpx,jb2,xmb,wbmp", ARGUMENTS.extension)>
<cfreturn true>
</cfif>
<cftry>
<cfif REQUEST.CFVersion gte 8>
<cfset objImage = ImageRead(ARGUMENTS.filePath) >
<cfset imageInfo = ImageInfo(objImage)>
<!--- <cfimage action="info" source="#ARGUMENTS.filePath#" structName="imageInfo" /> --->
<cfelse>
<cfset imageCFC = createObject("component", "image")>
<cfset imageInfo = imageCFC.getImageInfo("", ARGUMENTS.filePath)>
</cfif>
<cfif imageInfo.height lte 0 or imageInfo.width lte 0>
<cfreturn false>
</cfif>
<cfcatch type="any">
<cfreturn false>
</cfcatch>
</cftry>
<cfreturn true>
</cffunction>
<!---
Detect HTML in the first KB to prevent against potential security issue with
IE/Safari/Opera file type auto detection bug.
Returns true if file contain insecure HTML code at the beginning.
--->
<cffunction name="DetectHtml" output="false" returntype="boolean">
<cfargument name="filePath" required="true" type="String">
<cfset var tags = "<body,<head,<html,<img,<pre,<script,<table,<title">
<cfset var chunk = lcase( Trim( BinaryFileRead( ARGUMENTS.filePath, 1024 ) ) )>
<cfif not Len(chunk)>
<cfreturn false>
</cfif>
<cfif refind('<!doctype\W*x?html', chunk)>
<cfreturn true>
</cfif>
<cfloop index = "tag" list = "#tags#">
<cfif find( tag, chunk )>
<cfreturn true>
</cfif>
</cfloop>
<!--- type = javascript --->
<cfif refind('type\s*=\s*[''"]?\s*(?:\w*/)?(?:ecma|java)', chunk)>
<cfreturn true>
</cfif> >
<!--- href = javascript --->
<!--- src = javascript --->
<!--- data = javascript --->
<cfif refind('(?:href|src|data)\s*=\s*[\''"]?\s*(?:ecma|java)script:', chunk)>
<cfreturn true>
</cfif>
<!--- url(javascript --->
<cfif refind('url\s*\(\s*[\''"]?\s*(?:ecma|java)script:', chunk)>
<cfreturn true>
</cfif>
<cfreturn false>
</cffunction>

View file

@ -0,0 +1,183 @@
<cfsetting enablecfoutputonly="Yes">
<!---
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2007 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Configuration file for the ColdFusion Connector (all versions).
--->
<cfscript>
Config = StructNew() ;
// SECURITY: You must explicitly enable this "connector". (Set enabled to "true")
Config.Enabled = true ;
// Path to uploaded files relative to the document root.
Config.UserFilesPath = "/userfiles/" ;
// Use this to force the server path if FCKeditor is not running directly off
// the root of the application or the FCKeditor directory in the URL is a virtual directory
// or a symbolic link / junction
// Example: C:\inetpub\wwwroot\myDocs\
Config.ServerPath = "" ;
// Due to security issues with Apache modules, it is recommended to leave the
// following setting enabled.
Config.ForceSingleExtension = true ;
// Perform additional checks for image files - if set to true, validate image size
// (This feature works in MX 6.0 and above)
Config.SecureImageUploads = true;
// What the user can do with this connector
Config.ConfigAllowedCommands = "QuickUpload,FileUpload,GetFolders,GetFoldersAndFiles,CreateFolder" ;
//Allowed Resource Types
Config.ConfigAllowedTypes = "File,Image,Flash,Media" ;
// For security, HTML is allowed in the first Kb of data for files having the
// following extensions only.
// (This feature works in MX 6.0 and above))
Config.HtmlExtensions = "html,htm,xml,xsd,txt,js" ;
// Configuration settings for each Resource Type
//
// - AllowedExtensions: the possible extensions that can be allowed.
// If it is empty then any file type can be uploaded.
// - DeniedExtensions: The extensions that won't be allowed.
// If it is empty then no restrictions are done here.
//
// For a file to be uploaded it has to fulfill both the AllowedExtensions
// and DeniedExtensions (that's it: not being denied) conditions.
//
// - FileTypesPath: the virtual folder relative to the document root where
// these resources will be located.
// Attention: It must start and end with a slash: '/'
//
// - FileTypesAbsolutePath: the physical path to the above folder. It must be
// an absolute path.
// If it's an empty string then it will be autocalculated.
// Usefull if you are using a virtual directory, symbolic link or alias.
// Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
// Attention: The above 'FileTypesPath' must point to the same directory.
// Attention: It must end with a slash: '/'
//
//
// - QuickUploadPath: the virtual folder relative to the document root where
// these resources will be uploaded using the Upload tab in the resources
// dialogs.
// Attention: It must start and end with a slash: '/'
//
// - QuickUploadAbsolutePath: the physical path to the above folder. It must be
// an absolute path.
// If it's an empty string then it will be autocalculated.
// Usefull if you are using a virtual directory, symbolic link or alias.
// Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
// Attention: The above 'QuickUploadPath' must point to the same directory.
// Attention: It must end with a slash: '/'
Config.AllowedExtensions = StructNew() ;
Config.DeniedExtensions = StructNew() ;
Config.FileTypesPath = StructNew() ;
Config.FileTypesAbsolutePath = StructNew() ;
Config.QuickUploadPath = StructNew() ;
Config.QuickUploadAbsolutePath = StructNew() ;
Config.AllowedExtensions["File"] = "7z,aiff,asf,avi,bmp,csv,doc,fla,flv,gif,gz,gzip,jpeg,jpg,mid,mov,mp3,mp4,mpc,mpeg,mpg,ods,odt,pdf,png,ppt,pxd,qt,ram,rar,rm,rmi,rmvb,rtf,sdc,sitd,swf,sxc,sxw,tar,tgz,tif,tiff,txt,vsd,wav,wma,wmv,xls,xml,zip" ;
Config.DeniedExtensions["File"] = "" ;
Config.FileTypesPath["File"] = Config.UserFilesPath & 'file/' ;
Config.FileTypesAbsolutePath["File"] = iif( Config.ServerPath eq "", de(""), de(Config.ServerPath & 'file/') ) ;
Config.QuickUploadPath["File"] = Config.FileTypesPath["File"] ;
Config.QuickUploadAbsolutePath["File"] = Config.FileTypesAbsolutePath["File"] ;
Config.AllowedExtensions["Image"] = "bmp,gif,jpeg,jpg,png" ;
Config.DeniedExtensions["Image"] = "" ;
Config.FileTypesPath["Image"] = Config.UserFilesPath & 'image/' ;
Config.FileTypesAbsolutePath["Image"] = iif( Config.ServerPath eq "", de(""), de(Config.ServerPath & 'image/') ) ;
Config.QuickUploadPath["Image"] = Config.FileTypesPath["Image"] ;
Config.QuickUploadAbsolutePath["Image"] = Config.FileTypesAbsolutePath["Image"] ;
Config.AllowedExtensions["Flash"] = "swf,flv" ;
Config.DeniedExtensions["Flash"] = "" ;
Config.FileTypesPath["Flash"] = Config.UserFilesPath & 'flash/' ;
Config.FileTypesAbsolutePath["Flash"] = iif( Config.ServerPath eq "", de(""), de(Config.ServerPath & 'flash/') ) ;
Config.QuickUploadPath["Flash"] = Config.FileTypesPath["Flash"] ;
Config.QuickUploadAbsolutePath["Flash"] = Config.FileTypesAbsolutePath["Flash"] ;
Config.AllowedExtensions["Media"] = "aiff,asf,avi,bmp,fla,flv,gif,jpeg,jpg,mid,mov,mp3,mp4,mpc,mpeg,mpg,png,qt,ram,rm,rmi,rmvb,swf,tif,tiff,wav,wma,wmv" ;
Config.DeniedExtensions["Media"] = "" ;
Config.FileTypesPath["Media"] = Config.UserFilesPath & 'media/' ;
Config.FileTypesAbsolutePath["Media"] = iif( Config.ServerPath eq "", de(""), de(Config.ServerPath & 'media/') ) ;
Config.QuickUploadPath["Media"] = Config.FileTypesPath["Media"] ;
Config.QuickUploadAbsolutePath["Media"] = Config.FileTypesAbsolutePath["Media"] ;
</cfscript>
<cftry>
<!--- code to maintain backwards compatibility with previous version of cfm connector --->
<cfif isDefined("application.userFilesPath")>
<cflock scope="application" type="readonly" timeout="5">
<cfset config.userFilesPath = application.userFilesPath>
</cflock>
<cfelseif isDefined("server.userFilesPath")>
<cflock scope="server" type="readonly" timeout="5">
<cfset config.userFilesPath = server.userFilesPath>
</cflock>
</cfif>
<!--- look for config struct in application and server scopes --->
<cfif isDefined("application.FCKeditor") and isStruct(application.FCKeditor)>
<cflock scope="application" type="readonly" timeout="5">
<cfset variables.FCKeditor = duplicate(application.FCKeditor)>
</cflock>
<cfelseif isDefined("server.FCKeditor") and isStruct(server.FCKeditor)>
<cflock scope="server" type="readonly" timeout="5">
<cfset variables.FCKeditor = duplicate(server.FCKeditor)>
</cflock>
</cfif>
<!--- catch potential "The requested scope application has not been enabled" exception --->
<cfcatch type="any">
</cfcatch>
</cftry>
<cfif isDefined("FCKeditor")>
<!--- copy key values from external to local config (i.e. override default config as required) --->
<cfscript>
function structCopyKeys(stFrom, stTo) {
for ( key in stFrom ) {
if ( isStruct(stFrom[key]) ) {
structCopyKeys(stFrom[key],stTo[key]);
} else {
stTo[key] = stFrom[key];
}
}
}
structCopyKeys(FCKeditor, config);
</cfscript>
</cfif>

View file

@ -0,0 +1,31 @@
<cfsetting enablecfoutputonly="Yes">
<!---
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2007 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* File Browser connector for ColdFusion (all versions).
*
--->
<cfset REQUEST.CFVersion = Left( SERVER.COLDFUSION.PRODUCTVERSION, Find( ",", SERVER.COLDFUSION.PRODUCTVERSION ) - 1 )>
<cfif REQUEST.CFVersion lte 5>
<cfinclude template="cf5_connector.cfm">
<cfelse>
<cfinclude template="cf_connector.cfm">
</cfif>

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,31 @@
<cfsetting enablecfoutputonly="Yes">
<!---
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2007 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* This is the "File Uploader" for ColdFusion (all versions).
*
--->
<cfset REQUEST.CFVersion = Left( SERVER.COLDFUSION.PRODUCTVERSION, Find( ",", SERVER.COLDFUSION.PRODUCTVERSION ) - 1 )>
<cfif REQUEST.CFVersion lte 5>
<cfinclude template="cf5_upload.cfm">
<cfelse>
<cfinclude template="cf_upload.cfm">
</cfif>

View file

@ -0,0 +1,65 @@
[//lasso
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2007 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Configuration file for the File Manager Connector for Lasso.
*/
/*.....................................................................
The connector uses the file tags, which require authentication. Enter a
valid username and password from Lasso admin for a group with file tags
permissions for uploads and the path you define in UserFilesPath below.
*/
var('connection') = array(
-username='xxxxxxxx',
-password='xxxxxxxx'
);
/*.....................................................................
Set the base path for files that users can upload and browse (relative
to server root).
Set which file extensions are allowed and/or denied for each file type.
*/
var('config') = map(
'Enabled' = false,
'UserFilesPath' = '/userfiles/',
'Subdirectories' = map(
'File' = 'File/',
'Image' = 'Image/',
'Flash' = 'Flash/',
'Media' = 'Media/'
),
'AllowedExtensions' = map(
'File' = array('7z','aiff','asf','avi','bmp','csv','doc','fla','flv','gif','gz','gzip','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','ods','odt','pdf','png','ppt','pxd','qt','ram','rar','rm','rmi','rmvb','rtf','sdc','sitd','swf','sxc','sxw','tar','tgz','tif','tiff','txt','vsd','wav','wma','wmv','xls','xml','zip'),
'Image' = array('bmp','gif','jpeg','jpg','png'),
'Flash' = array('swf','flv'),
'Media' = array('aiff','asf','avi','bmp','fla','flv','gif','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','png','qt','ram','rm','rmi','rmvb','swf','tif','tiff','wav','wma','wmv')
),
'DeniedExtensions' = map(
'File' = array(),
'Image' = array(),
'Flash' = array(),
'Media' = array()
)
);
]

View file

@ -0,0 +1,257 @@
[//lasso
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2007 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* This is the File Manager Connector for Lasso.
*/
/*.....................................................................
Include global configuration. See config.lasso for details.
*/
include('config.lasso');
/*.....................................................................
Translate current date/time to GMT for custom header.
*/
var('headerDate') = date_localtogmt(date)->format('%a, %d %b %Y %T GMT');
/*.....................................................................
Convert query string parameters to variables and initialize output.
*/
var(
'Command' = action_param('Command'),
'Type' = action_param('Type'),
'CurrentFolder' = action_param('CurrentFolder'),
'ServerPath' = action_param('ServerPath'),
'NewFolderName' = action_param('NewFolderName'),
'NewFile' = null,
'NewFileName' = string,
'OrigFilePath' = string,
'NewFilePath' = string,
'commandData' = string,
'folders' = '\t<Folders>\n',
'files' = '\t<Files>\n',
'errorNumber' = integer,
'responseType' = 'xml',
'uploadResult' = '0'
);
/*.....................................................................
Calculate the path to the current folder.
*/
$ServerPath == '' ? $ServerPath = $config->find('UserFilesPath');
var('currentFolderURL' = $ServerPath
+ $config->find('Subdirectories')->find(action_param('Type'))
+ action_param('CurrentFolder')
);
/*.....................................................................
Build the appropriate response per the 'Command' parameter. Wrap the
entire process in an inline for file tag permissions.
*/
inline($connection);
select($Command);
/*.............................................................
List all subdirectories in the 'Current Folder' directory.
*/
case('GetFolders');
$commandData += '\t<Folders>\n';
iterate(file_listdirectory($currentFolderURL), local('this'));
#this->endswith('/') ? $commandData += '\t\t<Folder name="' + #this->removetrailing('/')& + '" />\n';
/iterate;
$commandData += '\t</Folders>\n';
/*.............................................................
List both files and folders in the 'Current Folder' directory.
Include the file sizes in kilobytes.
*/
case('GetFoldersAndFiles');
iterate(file_listdirectory($currentFolderURL), local('this'));
if(#this->endswith('/'));
$folders += '\t\t<Folder name="' + #this->removetrailing('/')& + '" />\n';
else;
local('size') = file_getsize($currentFolderURL + #this) / 1024;
$files += '\t\t<File name="' + #this + '" size="' + #size + '" />\n';
/if;
/iterate;
$folders += '\t</Folders>\n';
$files += '\t</Files>\n';
$commandData += $folders + $files;
/*.............................................................
Create a directory 'NewFolderName' within the 'Current Folder.'
*/
case('CreateFolder');
var('newFolder' = $currentFolderURL + $NewFolderName + '/');
file_create($newFolder);
/*.........................................................
Map Lasso's file error codes to FCKEditor's error codes.
*/
select(file_currenterror( -errorcode));
case(0);
$errorNumber = 0;
case( -9983);
$errorNumber = 101;
case( -9976);
$errorNumber = 102;
case( -9977);
$errorNumber = 102;
case( -9961);
$errorNumber = 103;
case;
$errorNumber = 110;
/select;
$commandData += '<Error number="' + $errorNumber + '" />\n';
/*.............................................................
Process an uploaded file.
*/
case('FileUpload');
/*.........................................................
This is the only command that returns an HTML response.
*/
$responseType = 'html';
/*.........................................................
Was a file actually uploaded?
*/
file_uploads->size ? $NewFile = file_uploads->get(1) | $uploadResult = '202';
if($uploadResult == '0');
/*.....................................................
Split the file's extension from the filename in order
to follow the API's naming convention for duplicate
files. (Test.txt, Test(1).txt, Test(2).txt, etc.)
*/
$NewFileName = $NewFile->find('OrigName');
$OrigFilePath = $currentFolderURL + $NewFileName;
$NewFilePath = $OrigFilePath;
local('fileExtension') = '.' + $NewFile->find('OrigExtension');
local('shortFileName') = $NewFileName->removetrailing(#fileExtension)&;
/*.....................................................
Make sure the file extension is allowed.
*/
if($config->find('DeniedExtensions')->find($Type) >> $NewFile->find('OrigExtension'));
$uploadResult = '202';
else;
/*.................................................
Rename the target path until it is unique.
*/
while(file_exists($NewFilePath));
$NewFilePath = $currentFolderURL + #shortFileName + '(' + loop_count + ')' + #fileExtension;
/while;
/*.................................................
Copy the uploaded file to its final location.
*/
file_copy($NewFile->find('path'), $NewFilePath);
/*.................................................
Set the error code for the response. Note whether
the file had to be renamed.
*/
select(file_currenterror( -errorcode));
case(0);
$OrigFilePath != $NewFilePath ? $uploadResult = 201;
case;
$uploadResult = '202';
/select;
/if;
/if;
/*.........................................................
Set the HTML response.
*/
if($uploadResult == '0' || $uploadResult == '201');
$__html_reply__ = '\
<script type="text/javascript">
window.parent.frames[\'frmUpload\'].OnUploadCompleted(' + $uploadResult + ',\'' + $NewFilePath + '\',\'' + $NewFilePath->split('/')->last + '\');
</script>
';
else;
$__html_reply__ = '\
<script type="text/javascript">
window.parent.frames[\'frmUpload\'].OnUploadCompleted(' + $uploadResult + ');
</script>
';
/if;
/select;
/inline;
/*.....................................................................
Send a custom header for xml responses.
*/
if($responseType == 'xml');
header;
]
HTTP/1.0 200 OK
Date: [$headerDate]
Server: Lasso Professional [lasso_version( -lassoversion)]
Expires: Mon, 26 Jul 1997 05:00:00 GMT
Last-Modified: [$headerDate]
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Keep-Alive: timeout=15, max=98
Connection: Keep-Alive
Content-Type: text/xml; charset=utf-8
[//lasso
/header;
/*.................................................................
Set the content type encoding for Lasso.
*/
content_type('text/xml; charset=utf-8');
/*.................................................................
Wrap the response as XML and output.
*/
$__html_reply__ = '\
<?xml version="1.0" encoding="utf-8" ?>
<Connector command="' + $Command + '" resourceType="' + $Type + '">
<CurrentFolder path="' + $CurrentFolder + '" url="' + $currentFolderURL + '" />
' + $commandData + '
</Connector>
';
/if;
]

View file

@ -0,0 +1,157 @@
[//lasso
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2007 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* This is the "File Uploader" for Lasso.
*/
/*.....................................................................
Include global configuration. See config.lasso for details.
*/
include('config.lasso');
/*.....................................................................
Convert query string parameters to variables and initialize output.
*/
var(
'Type' = action_param('Type'),
'CurrentFolder' = action_param('CurrentFolder'),
'ServerPath' = action_param('ServerPath'),
'NewFile' = null,
'NewFileName' = string,
'OrigFilePath' = string,
'NewFilePath' = string,
'errorNumber' = 0,
'customMsg' = ''
);
$Type == '' ? $Type = 'File';
/*.....................................................................
Calculate the path to the current folder.
*/
$ServerPath == '' ? $ServerPath = $config->find('UserFilesPath');
var('currentFolderURL' = $ServerPath
+ $config->find('Subdirectories')->find(action_param('Type'))
+ action_param('CurrentFolder')
);
/*.....................................................................
Custom tag sets the HTML response.
*/
define_tag(
'sendresults',
-namespace='fck_',
-priority='replace',
-required='errorNumber',
-type='integer',
-optional='fileUrl',
-type='string',
-optional='fileName',
-type='string',
-optional='customMsg',
-type='string',
-description='Sets the HTML response for the FCKEditor Quick Upload feature.'
);
$__html_reply__ = '\
<script type="text/javascript">
window.parent.OnUploadCompleted(' + #errorNumber + ',"'
+ string_replace(#fileUrl, -find='"', -replace='\\"') + '","'
+ string_replace(#fileName, -find='"', -replace='\\"') + '","'
+ string_replace(#customMsg, -find='"', -replace='\\"') + '");
</script>
';
/define_tag;
if($config->find('Enabled'));
/*.................................................................
Process an uploaded file.
*/
inline($connection);
/*.............................................................
Was a file actually uploaded?
*/
file_uploads->size ? $NewFile = file_uploads->get(1) | $errorNumber = 202;
if($errorNumber == 0);
/*.........................................................
Split the file's extension from the filename in order
to follow the API's naming convention for duplicate
files. (Test.txt, Test(1).txt, Test(2).txt, etc.)
*/
$NewFileName = $NewFile->find('OrigName');
$OrigFilePath = $currentFolderURL + $NewFileName;
$NewFilePath = $OrigFilePath;
local('fileExtension') = '.' + $NewFile->find('OrigExtension');
local('shortFileName') = $NewFileName->removetrailing(#fileExtension)&;
/*.........................................................
Make sure the file extension is allowed.
*/
if($config->find('DeniedExtensions')->find($Type) >> $NewFile->find('OrigExtension'));
$errorNumber = 202;
else;
/*.....................................................
Rename the target path until it is unique.
*/
while(file_exists($NewFilePath));
$NewFileName = #shortFileName + '(' + loop_count + ')' + #fileExtension;
$NewFilePath = $currentFolderURL + $NewFileName;
/while;
/*.....................................................
Copy the uploaded file to its final location.
*/
file_copy($NewFile->find('path'), $NewFilePath);
/*.....................................................
Set the error code for the response.
*/
select(file_currenterror( -errorcode));
case(0);
$OrigFilePath != $NewFilePath ? $errorNumber = 201;
case;
$errorNumber = 202;
/select;
/if;
/if;
/inline;
else;
$errorNumber = 1;
$customMsg = 'This file uploader is disabled. Please check the "editor/filemanager/upload/lasso/config.lasso" file.';
/if;
fck_sendresults(
-errorNumber=$errorNumber,
-fileUrl=$NewFilePath,
-fileName=$NewFileName,
-customMsg=$customMsg
);
]

View file

@ -0,0 +1,63 @@
#####
# FCKeditor - The text editor for Internet - http://www.fckeditor.net
# Copyright (C) 2003-2007 Frederico Caldeira Knabben
#
# == BEGIN LICENSE ==
#
# Licensed under the terms of any of the following licenses at your
# choice:
#
# - GNU General Public License Version 2 or later (the "GPL")
# http://www.gnu.org/licenses/gpl.html
#
# - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
# http://www.gnu.org/licenses/lgpl.html
#
# - Mozilla Public License Version 1.1 or later (the "MPL")
# http://www.mozilla.org/MPL/MPL-1.1.html
#
# == END LICENSE ==
#
# This is the File Manager Connector for Perl.
#####
sub CreateXmlHeader
{
local($command,$resourceType,$currentFolder) = @_;
# Create the XML document header.
print '<?xml version="1.0" encoding="utf-8" ?>';
# Create the main "Connector" node.
print '<Connector command="' . $command . '" resourceType="' . $resourceType . '">';
# Add the current folder node.
print '<CurrentFolder path="' . ConvertToXmlAttribute($currentFolder) . '" url="' . ConvertToXmlAttribute(GetUrlFromPath($resourceType,$currentFolder)) . '" />';
}
sub CreateXmlFooter
{
print '</Connector>';
}
sub SendError
{
local( $number, $text ) = @_;
print << "_HTML_HEAD_";
Content-Type:text/xml; charset=utf-8
Pragma: no-cache
Cache-Control: no-cache
Expires: Thu, 01 Dec 1994 16:00:00 GMT
_HTML_HEAD_
# Create the XML document header
print '<?xml version="1.0" encoding="utf-8" ?>' ;
print '<Connector><Error number="' . $number . '" text="' . &specialchar_cnv( $text ) . '" /></Connector>' ;
exit ;
}
1;

View file

@ -0,0 +1,168 @@
#####
# FCKeditor - The text editor for Internet - http://www.fckeditor.net
# Copyright (C) 2003-2007 Frederico Caldeira Knabben
#
# == BEGIN LICENSE ==
#
# Licensed under the terms of any of the following licenses at your
# choice:
#
# - GNU General Public License Version 2 or later (the "GPL")
# http://www.gnu.org/licenses/gpl.html
#
# - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
# http://www.gnu.org/licenses/lgpl.html
#
# - Mozilla Public License Version 1.1 or later (the "MPL")
# http://www.mozilla.org/MPL/MPL-1.1.html
#
# == END LICENSE ==
#
# This is the File Manager Connector for Perl.
#####
sub GetFolders
{
local($resourceType, $currentFolder) = @_;
# Map the virtual path to the local server path.
$sServerDir = &ServerMapFolder($resourceType, $currentFolder);
print "<Folders>"; # Open the "Folders" node.
opendir(DIR,"$sServerDir");
@files = grep(!/^\.\.?$/,readdir(DIR));
closedir(DIR);
foreach $sFile (@files) {
if($sFile != '.' && $sFile != '..' && (-d "$sServerDir$sFile")) {
$cnv_filename = &ConvertToXmlAttribute($sFile);
print '<Folder name="' . $cnv_filename . '" />';
}
}
print "</Folders>"; # Close the "Folders" node.
}
sub GetFoldersAndFiles
{
local($resourceType, $currentFolder) = @_;
# Map the virtual path to the local server path.
$sServerDir = &ServerMapFolder($resourceType,$currentFolder);
# Initialize the output buffers for "Folders" and "Files".
$sFolders = '<Folders>';
$sFiles = '<Files>';
opendir(DIR,"$sServerDir");
@files = grep(!/^\.\.?$/,readdir(DIR));
closedir(DIR);
foreach $sFile (@files) {
if($sFile ne '.' && $sFile ne '..') {
if(-d "$sServerDir$sFile") {
$cnv_filename = &ConvertToXmlAttribute($sFile);
$sFolders .= '<Folder name="' . $cnv_filename . '" />' ;
} else {
($iFileSize,$refdate,$filedate,$fileperm) = (stat("$sServerDir$sFile"))[7,8,9,2];
if($iFileSize > 0) {
$iFileSize = int($iFileSize / 1024);
if($iFileSize < 1) {
$iFileSize = 1;
}
}
$cnv_filename = &ConvertToXmlAttribute($sFile);
$sFiles .= '<File name="' . $cnv_filename . '" size="' . $iFileSize . '" />' ;
}
}
}
print $sFolders ;
print '</Folders>'; # Close the "Folders" node.
print $sFiles ;
print '</Files>'; # Close the "Files" node.
}
sub CreateFolder
{
local($resourceType, $currentFolder) = @_;
$sErrorNumber = '0' ;
$sErrorMsg = '' ;
if($FORM{'NewFolderName'} ne "") {
$sNewFolderName = $FORM{'NewFolderName'};
# Map the virtual path to the local server path of the current folder.
$sServerDir = &ServerMapFolder($resourceType, $currentFolder);
if(-w $sServerDir) {
$sServerDir .= $sNewFolderName;
$sErrorMsg = &CreateServerFolder($sServerDir);
if($sErrorMsg == 0) {
$sErrorNumber = '0';
} elsif($sErrorMsg eq 'Invalid argument' || $sErrorMsg eq 'No such file or directory') {
$sErrorNumber = '102'; #// Path too long.
} else {
$sErrorNumber = '110';
}
} else {
$sErrorNumber = '103';
}
} else {
$sErrorNumber = '102' ;
}
# Create the "Error" node.
$cnv_errmsg = &ConvertToXmlAttribute($sErrorMsg);
print '<Error number="' . $sErrorNumber . '" originalDescription="' . $cnv_errmsg . '" />';
}
sub FileUpload
{
eval("use File::Copy;");
local($resourceType, $currentFolder) = @_;
$sErrorNumber = '0' ;
$sFileName = '' ;
if($new_fname) {
# Map the virtual path to the local server path.
$sServerDir = &ServerMapFolder($resourceType,$currentFolder);
# Get the uploaded file name.
$sFileName = $new_fname;
$sOriginalFileName = $sFileName;
$iCounter = 0;
while(1) {
$sFilePath = $sServerDir . $sFileName;
if(-e $sFilePath) {
$iCounter++ ;
($path,$BaseName,$ext) = &RemoveExtension($sOriginalFileName);
$sFileName = $BaseName . '(' . $iCounter . ').' . $ext;
$sErrorNumber = '201';
} else {
copy("$img_dir/$new_fname","$sFilePath");
chmod(0777,$sFilePath);
unlink("$img_dir/$new_fname");
last;
}
}
} else {
$sErrorNumber = '202' ;
}
$sFileName =~ s/"/\\"/g;
SendUploadResults($sErrorNumber, $resourceType.$currentFolder.$sFileName, $sFileName, '');
}
sub SendUploadResults
{
local($sErrorNumber, $sFileUrl, $sFileName, $customMsg) = @_;
print "Content-type: text/html\n\n";
print '<script type="text/javascript">';
print 'window.parent.OnUploadCompleted(' . $sErrorNumber . ',"' . JS_cnv($sFileUrl) . '","' . JS_cnv($sFileName) . '","' . JS_cnv($customMsg) . '") ;';
print '</script>';
exit ;
}
1;

View file

@ -0,0 +1,137 @@
#!/usr/bin/env perl
#####
# FCKeditor - The text editor for Internet - http://www.fckeditor.net
# Copyright (C) 2003-2007 Frederico Caldeira Knabben
#
# == BEGIN LICENSE ==
#
# Licensed under the terms of any of the following licenses at your
# choice:
#
# - GNU General Public License Version 2 or later (the "GPL")
# http://www.gnu.org/licenses/gpl.html
#
# - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
# http://www.gnu.org/licenses/lgpl.html
#
# - Mozilla Public License Version 1.1 or later (the "MPL")
# http://www.mozilla.org/MPL/MPL-1.1.html
#
# == END LICENSE ==
#
# This is the File Manager Connector for Perl.
#####
##
# ATTENTION: To enable this connector, look for the "SECURITY" comment in this file.
##
## START: Hack for Windows (Not important to understand the editor code... Perl specific).
if(Windows_check()) {
chdir(GetScriptPath($0));
}
sub Windows_check
{
# IIS,PWS(NT/95)
$www_server_os = $^O;
# Win98 & NT(SP4)
if($www_server_os eq "") { $www_server_os= $ENV{'OS'}; }
# AnHTTPd/Omni/IIS
if($ENV{'SERVER_SOFTWARE'} =~ /AnWeb|Omni|IIS\//i) { $www_server_os= 'win'; }
# Win Apache
if($ENV{'WINDIR'} ne "") { $www_server_os= 'win'; }
if($www_server_os=~ /win/i) { return(1); }
return(0);
}
sub GetScriptPath {
local($path) = @_;
if($path =~ /[\:\/\\]/) { $path =~ s/(.*?)[\/\\][^\/\\]+$/$1/; } else { $path = '.'; }
$path;
}
## END: Hack for IIS
require 'util.pl';
require 'io.pl';
require 'basexml.pl';
require 'commands.pl';
require 'upload_fck.pl';
##
# SECURITY: REMOVE/COMMENT THE FOLLOWING LINE TO ENABLE THIS CONNECTOR.
##
&SendError( 1, 'This connector is disabled. Please check the "editor/filemanager/connectors/perl/connector.cgi" file' ) ;
&read_input();
if($FORM{'ServerPath'} ne "") {
$GLOBALS{'UserFilesPath'} = $FORM{'ServerPath'};
if(!($GLOBALS{'UserFilesPath'} =~ /\/$/)) {
$GLOBALS{'UserFilesPath'} .= '/' ;
}
} else {
$GLOBALS{'UserFilesPath'} = '/userfiles/';
}
# Map the "UserFiles" path to a local directory.
$rootpath = &GetRootPath();
$GLOBALS{'UserFilesDirectory'} = $rootpath . $GLOBALS{'UserFilesPath'};
&DoResponse();
sub DoResponse
{
if($FORM{'Command'} eq "" || $FORM{'Type'} eq "" || $FORM{'CurrentFolder'} eq "") {
return ;
}
# Get the main request informaiton.
$sCommand = $FORM{'Command'};
$sResourceType = $FORM{'Type'};
$sCurrentFolder = $FORM{'CurrentFolder'};
# Check the current folder syntax (must begin and start with a slash).
if(!($sCurrentFolder =~ /\/$/)) {
$sCurrentFolder .= '/';
}
if(!($sCurrentFolder =~ /^\//)) {
$sCurrentFolder = '/' . $sCurrentFolder;
}
# Check for invalid folder paths (..)
if ( $sCurrentFolder =~ /\.\./ ) {
SendError( 102, "" ) ;
}
# File Upload doesn't have to Return XML, so it must be intercepted before anything.
if($sCommand eq 'FileUpload') {
FileUpload($sResourceType,$sCurrentFolder);
return ;
}
print << "_HTML_HEAD_";
Content-Type:text/xml; charset=utf-8
Pragma: no-cache
Cache-Control: no-cache
Expires: Thu, 01 Dec 1994 16:00:00 GMT
_HTML_HEAD_
&CreateXmlHeader($sCommand,$sResourceType,$sCurrentFolder);
# Execute the required command.
if($sCommand eq 'GetFolders') {
&GetFolders($sResourceType,$sCurrentFolder);
} elsif($sCommand eq 'GetFoldersAndFiles') {
&GetFoldersAndFiles($sResourceType,$sCurrentFolder);
} elsif($sCommand eq 'CreateFolder') {
&CreateFolder($sResourceType,$sCurrentFolder);
}
&CreateXmlFooter();
exit ;
}

View file

@ -0,0 +1,131 @@
#####
# FCKeditor - The text editor for Internet - http://www.fckeditor.net
# Copyright (C) 2003-2007 Frederico Caldeira Knabben
#
# == BEGIN LICENSE ==
#
# Licensed under the terms of any of the following licenses at your
# choice:
#
# - GNU General Public License Version 2 or later (the "GPL")
# http://www.gnu.org/licenses/gpl.html
#
# - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
# http://www.gnu.org/licenses/lgpl.html
#
# - Mozilla Public License Version 1.1 or later (the "MPL")
# http://www.mozilla.org/MPL/MPL-1.1.html
#
# == END LICENSE ==
#
# This is the File Manager Connector for Perl.
#####
sub GetUrlFromPath
{
local($resourceType, $folderPath) = @_;
if($resourceType eq '') {
$rmpath = &RemoveFromEnd($GLOBALS{'UserFilesPath'},'/');
return("$rmpath$folderPath");
} else {
return("$GLOBALS{'UserFilesPath'}$resourceType$folderPath");
}
}
sub RemoveExtension
{
local($fileName) = @_;
local($path, $base, $ext);
if($fileName !~ /\./) {
$fileName .= '.';
}
if($fileName =~ /([^\\\/]*)\.(.*)$/) {
$base = $1;
$ext = $2;
if($fileName =~ /(.*)$base\.$ext$/) {
$path = $1;
}
}
return($path,$base,$ext);
}
sub ServerMapFolder
{
local($resourceType,$folderPath) = @_;
# Get the resource type directory.
$sResourceTypePath = $GLOBALS{'UserFilesDirectory'} . $resourceType . '/';
# Ensure that the directory exists.
&CreateServerFolder($sResourceTypePath);
# Return the resource type directory combined with the required path.
$rmpath = &RemoveFromStart($folderPath,'/');
return("$sResourceTypePath$rmpath");
}
sub GetParentFolder
{
local($folderPath) = @_;
$folderPath =~ s/[\/][^\/]+[\/]?$//g;
return $folderPath;
}
sub CreateServerFolder
{
local($folderPath) = @_;
$sParent = &GetParentFolder($folderPath);
# Check if the parent exists, or create it.
if(!(-e $sParent)) {
$sErrorMsg = &CreateServerFolder($sParent);
if($sErrorMsg == 1) {
return(1);
}
}
if(!(-e $folderPath)) {
umask(000);
mkdir("$folderPath",0777);
chmod(0777,"$folderPath");
return(0);
} else {
return(1);
}
}
sub GetRootPath
{
#use Cwd;
# my $dir = getcwd;
# print $dir;
# $dir =~ s/$ENV{'DOCUMENT_ROOT'}//g;
# print $dir;
# return($dir);
# $wk = $0;
# $wk =~ s/\/connector\.cgi//g;
# if($wk) {
# $current_dir = $wk;
# } else {
# $current_dir = `pwd`;
# }
# return($current_dir);
use Cwd;
if($ENV{'DOCUMENT_ROOT'}) {
$dir = $ENV{'DOCUMENT_ROOT'};
} else {
my $dir = getcwd;
$workdir =~ s/\/connector\.cgi//g;
$dir =~ s/$workdir//g;
}
return($dir);
}
1;

View file

@ -0,0 +1,118 @@
#!/usr/bin/env perl
#####
# FCKeditor - The text editor for Internet - http://www.fckeditor.net
# Copyright (C) 2003-2007 Frederico Caldeira Knabben
#
# == BEGIN LICENSE ==
#
# Licensed under the terms of any of the following licenses at your
# choice:
#
# - GNU General Public License Version 2 or later (the "GPL")
# http://www.gnu.org/licenses/gpl.html
#
# - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
# http://www.gnu.org/licenses/lgpl.html
#
# - Mozilla Public License Version 1.1 or later (the "MPL")
# http://www.mozilla.org/MPL/MPL-1.1.html
#
# == END LICENSE ==
#
# This is the File Manager Connector for Perl.
#####
##
# ATTENTION: To enable this connector, look for the "SECURITY" comment in this file.
##
## START: Hack for Windows (Not important to understand the editor code... Perl specific).
if(Windows_check()) {
chdir(GetScriptPath($0));
}
sub Windows_check
{
# IIS,PWS(NT/95)
$www_server_os = $^O;
# Win98 & NT(SP4)
if($www_server_os eq "") { $www_server_os= $ENV{'OS'}; }
# AnHTTPd/Omni/IIS
if($ENV{'SERVER_SOFTWARE'} =~ /AnWeb|Omni|IIS\//i) { $www_server_os= 'win'; }
# Win Apache
if($ENV{'WINDIR'} ne "") { $www_server_os= 'win'; }
if($www_server_os=~ /win/i) { return(1); }
return(0);
}
sub GetScriptPath {
local($path) = @_;
if($path =~ /[\:\/\\]/) { $path =~ s/(.*?)[\/\\][^\/\\]+$/$1/; } else { $path = '.'; }
$path;
}
## END: Hack for IIS
require 'util.pl';
require 'io.pl';
require 'basexml.pl';
require 'commands.pl';
require 'upload_fck.pl';
##
# SECURITY: REMOVE/COMMENT THE FOLLOWING LINE TO ENABLE THIS CONNECTOR.
##
&SendUploadResults(1, '', '', 'This connector is disabled. Please check the "editor/filemanager/connectors/perl/upload.cgi" file' ) ;
&read_input();
if($FORM{'ServerPath'} ne "") {
$GLOBALS{'UserFilesPath'} = $FORM{'ServerPath'};
if(!($GLOBALS{'UserFilesPath'} =~ /\/$/)) {
$GLOBALS{'UserFilesPath'} .= '/' ;
}
} else {
$GLOBALS{'UserFilesPath'} = '/userfiles/';
}
# Map the "UserFiles" path to a local directory.
$rootpath = &GetRootPath();
$GLOBALS{'UserFilesDirectory'} = $rootpath . $GLOBALS{'UserFilesPath'};
&DoResponse();
sub DoResponse
{
# Get the main request information.
$sCommand = 'FileUpload'; #$FORM{'Command'};
$sResourceType = $FORM{'Type'};
$sCurrentFolder = $FORM{'CurrentFolder'};
if ($sResourceType eq '') {
$sResourceType = 'File' ;
}
if ($sCurrentFolder eq '') {
$sCurrentFolder = '/' ;
}
# Check the current folder syntax (must begin and start with a slash).
if(!($sCurrentFolder =~ /\/$/)) {
$sCurrentFolder .= '/';
}
if(!($sCurrentFolder =~ /^\//)) {
$sCurrentFolder = '/' . $sCurrentFolder;
}
# Check for invalid folder paths (..)
if ( $sCurrentFolder =~ /\.\./ ) {
SendError( 102, "" ) ;
}
# File Upload doesn't have to Return XML, so it must be intercepted before anything.
if($sCommand eq 'FileUpload') {
FileUpload($sResourceType,$sCurrentFolder);
return ;
}
}

View file

@ -0,0 +1,667 @@
#####
# FCKeditor - The text editor for Internet - http://www.fckeditor.net
# Copyright (C) 2003-2007 Frederico Caldeira Knabben
#
# == BEGIN LICENSE ==
#
# Licensed under the terms of any of the following licenses at your
# choice:
#
# - GNU General Public License Version 2 or later (the "GPL")
# http://www.gnu.org/licenses/gpl.html
#
# - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
# http://www.gnu.org/licenses/lgpl.html
#
# - Mozilla Public License Version 1.1 or later (the "MPL")
# http://www.mozilla.org/MPL/MPL-1.1.html
#
# == END LICENSE ==
#
# This is the File Manager Connector for Perl.
#####
# image data save dir
$img_dir = './temp/';
# File size max(unit KB)
$MAX_CONTENT_SIZE = 30000;
# Filelock (1=use,0=not use)
$PM{'flock'} = '1';
# upload Content-Type list
my %UPLOAD_CONTENT_TYPE_LIST = (
'image/(x-)?png' => 'png', # PNG image
'image/p?jpe?g' => 'jpg', # JPEG image
'image/gif' => 'gif', # GIF image
'image/x-xbitmap' => 'xbm', # XBM image
'image/(x-(MS-)?)?bmp' => 'bmp', # Windows BMP image
'image/pict' => 'pict', # Macintosh PICT image
'image/tiff' => 'tif', # TIFF image
'application/pdf' => 'pdf', # PDF image
'application/x-shockwave-flash' => 'swf', # Shockwave Flash
'video/(x-)?msvideo' => 'avi', # Microsoft Video
'video/quicktime' => 'mov', # QuickTime Video
'video/mpeg' => 'mpeg', # MPEG Video
'video/x-mpeg2' => 'mpv2', # MPEG2 Video
'audio/(x-)?midi?' => 'mid', # MIDI Audio
'audio/(x-)?wav' => 'wav', # WAV Audio
'audio/basic' => 'au', # ULAW Audio
'audio/mpeg' => 'mpga', # MPEG Audio
'application/(x-)?zip(-compressed)?' => 'zip', # ZIP Compress
'text/html' => 'html', # HTML
'text/plain' => 'txt', # TEXT
'(?:application|text)/(?:rtf|richtext)' => 'rtf', # RichText
'application/msword' => 'doc', # Microsoft Word
'application/vnd.ms-excel' => 'xls', # Microsoft Excel
''
);
# Upload is permitted.
# A regular expression is possible.
my %UPLOAD_EXT_LIST = (
'png' => 'PNG image',
'p?jpe?g|jpe|jfif|pjp' => 'JPEG image',
'gif' => 'GIF image',
'xbm' => 'XBM image',
'bmp|dib|rle' => 'Windows BMP image',
'pi?ct' => 'Macintosh PICT image',
'tiff?' => 'TIFF image',
'pdf' => 'PDF image',
'swf' => 'Shockwave Flash',
'avi' => 'Microsoft Video',
'moo?v|qt' => 'QuickTime Video',
'm(p(e?gv?|e|v)|1v)' => 'MPEG Video',
'mp(v2|2v)' => 'MPEG2 Video',
'midi?|kar|smf|rmi|mff' => 'MIDI Audio',
'wav' => 'WAVE Audio',
'au|snd' => 'ULAW Audio',
'mp(e?ga|2|a|3)|abs' => 'MPEG Audio',
'zip' => 'ZIP Compress',
'lzh' => 'LZH Compress',
'cab' => 'CAB Compress',
'd?html?' => 'HTML',
'rtf|rtx' => 'RichText',
'txt|text' => 'Text',
''
);
# sjis or euc
my $CHARCODE = 'sjis';
$TRANS_2BYTE_CODE = 0;
##############################################################################
# Summary
#
# Form Read input
#
# Parameters
# Returns
# Memo
##############################################################################
sub read_input
{
eval("use File::Copy;");
eval("use File::Path;");
my ($FORM) = @_;
mkdir($img_dir,0777);
chmod(0777,$img_dir);
undef $img_data_exists;
undef @NEWFNAMES;
undef @NEWFNAME_DATA;
if($ENV{'CONTENT_LENGTH'} > 10000000 || $ENV{'CONTENT_LENGTH'} > $MAX_CONTENT_SIZE * 1024) {
&upload_error(
'Size Error',
sprintf(
"Transmitting size is too large.MAX <strong>%d KB</strong> Now Size <strong>%d KB</strong>(<strong>%d bytes</strong> Over)",
$MAX_CONTENT_SIZE,
int($ENV{'CONTENT_LENGTH'} / 1024),
$ENV{'CONTENT_LENGTH'} - $MAX_CONTENT_SIZE * 1024
)
);
}
my $Buffer;
if($ENV{'CONTENT_TYPE'} =~ /multipart\/form-data/) {
# METHOD POST only
return unless($ENV{'CONTENT_LENGTH'});
binmode(STDIN);
# STDIN A pause character is detected.'(MacIE3.0 boundary of $ENV{'CONTENT_TYPE'} cannot be trusted.)
my $Boundary = <STDIN>;
$Boundary =~ s/\x0D\x0A//;
$Boundary = quotemeta($Boundary);
while(<STDIN>) {
if(/^\s*Content-Disposition:/i) {
my($name,$ContentType,$FileName);
# form data get
if(/\bname="([^"]+)"/i || /\bname=([^\s:;]+)/i) {
$name = $1;
$name =~ tr/+/ /;
$name =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
&Encode(\$name);
}
if(/\bfilename="([^"]*)"/i || /\bfilename=([^\s:;]*)/i) {
$FileName = $1 || 'unknown';
}
# head read
while(<STDIN>) {
last if(! /\w/);
if(/^\s*Content-Type:\s*"([^"]+)"/i || /^\s*Content-Type:\s*([^\s:;]+)/i) {
$ContentType = $1;
}
}
# body read
$value = "";
while(<STDIN>) {
last if(/^$Boundary/o);
$value .= $_;
};
$lastline = $_;
$value =~s /\x0D\x0A$//;
if($value ne '') {
if($FileName || $ContentType) {
$img_data_exists = 1;
(
$FileName, #
$Ext, #
$Length, #
$ImageWidth, #
$ImageHeight, #
$ContentName #
) = &CheckContentType(\$value,$FileName,$ContentType);
$FORM{$name} = $FileName;
$new_fname = $FileName;
push(@NEWFNAME_DATA,"$FileName\t$Ext\t$Length\t$ImageWidth\t$ImageHeight\t$ContentName");
# Multi-upload correspondence
push(@NEWFNAMES,$new_fname);
open(OUT,">$img_dir/$new_fname");
binmode(OUT);
eval "flock(OUT,2);" if($PM{'flock'} == 1);
print OUT $value;
eval "flock(OUT,8);" if($PM{'flock'} == 1);
close(OUT);
} elsif($name) {
$value =~ tr/+/ /;
$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
&Encode(\$value,'trans');
$FORM{$name} .= "\0" if(defined($FORM{$name}));
$FORM{$name} .= $value;
}
}
};
last if($lastline =~ /^$Boundary\-\-/o);
}
} elsif($ENV{'CONTENT_LENGTH'}) {
read(STDIN,$Buffer,$ENV{'CONTENT_LENGTH'});
}
foreach(split(/&/,$Buffer),split(/&/,$ENV{'QUERY_STRING'})) {
my($name, $value) = split(/=/);
$name =~ tr/+/ /;
$name =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
$value =~ tr/+/ /;
$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
&Encode(\$name);
&Encode(\$value,'trans');
$FORM{$name} .= "\0" if(defined($FORM{$name}));
$FORM{$name} .= $value;
}
}
##############################################################################
# Summary
#
# CheckContentType
#
# Parameters
# Returns
# Memo
##############################################################################
sub CheckContentType
{
my($DATA,$FileName,$ContentType) = @_;
my($Ext,$ImageWidth,$ImageHeight,$ContentName,$Infomation);
my $DataLength = length($$DATA);
# An unknown file type
$_ = $ContentType;
my $UnknownType = (
!$_
|| /^application\/(x-)?macbinary$/i
|| /^application\/applefile$/i
|| /^application\/octet-stream$/i
|| /^text\/plane$/i
|| /^x-unknown-content-type/i
);
# MacBinary(Mac Unnecessary data are deleted.)
if($UnknownType || $ENV{'HTTP_USER_AGENT'} =~ /Macintosh|Mac_/) {
if($DataLength > 128 && !unpack("C",substr($$DATA,0,1)) && !unpack("C",substr($$DATA,74,1)) && !unpack("C",substr($$DATA,82,1)) ) {
my $MacBinary_ForkLength = unpack("N", substr($$DATA, 83, 4)); # ForkLength Get
my $MacBinary_FileName = quotemeta(substr($$DATA, 2, unpack("C",substr($$DATA, 1, 1))));
if($MacBinary_FileName && $MacBinary_ForkLength && $DataLength >= $MacBinary_ForkLength + 128
&& ($FileName =~ /$MacBinary_FileName/i || substr($$DATA,102,4) eq 'mBIN')) { # DATA TOP 128byte MacBinary!!
$$DATA = substr($$DATA,128,$MacBinary_ForkLength);
my $ResourceLength = $DataLength - $MacBinary_ForkLength - 128;
$DataLength = $MacBinary_ForkLength;
}
}
}
# A file name is changed into EUC.
# &jcode::convert(\$FileName,'euc',$FormCodeDefault);
# &jcode::h2z_euc(\$FileName);
$FileName =~ s/^.*\\//; # Windows, Mac
$FileName =~ s/^.*\///; # UNIX
$FileName =~ s/&/&amp;/g;
$FileName =~ s/"/&quot;/g;
$FileName =~ s/</&lt;/g;
$FileName =~ s/>/&gt;/g;
#
# if($CHARCODE ne 'euc') {
# &jcode::convert(\$FileName,$CHARCODE,'euc');
# }
# An extension is extracted and it changes into a small letter.
my $FileExt;
if($FileName =~ /\.(\w+)$/) {
$FileExt = $1;
$FileExt =~ tr/A-Z/a-z/;
}
# Executable file detection (ban on upload)
if($$DATA =~ /^MZ/) {
$Ext = 'exe';
}
# text
if(!$Ext && ($UnknownType || $ContentType =~ /^text\//i || $ContentType =~ /^application\/(?:rtf|richtext)$/i || $ContentType =~ /^image\/x-xbitmap$/i)
&& ! $$DATA =~ /[\000-\006\177\377]/) {
# $$DATA =~ s/\x0D\x0A/\n/g;
# $$DATA =~ tr/\x0D\x0A/\n\n/;
#
# if(
# $$DATA =~ /<\s*SCRIPT(?:.|\n)*?>/i
# || $$DATA =~ /<\s*(?:.|\n)*?\bONLOAD\s*=(?:.|\n)*?>/i
# || $$DATA =~ /<\s*(?:.|\n)*?\bONCLICK\s*=(?:.|\n)*?>/i
# ) {
# $Infomation = '(JavaScript contains)';
# }
# if($$DATA =~ /<\s*TABLE(?:.|\n)*?>/i
# || $$DATA =~ /<\s*BLINK(?:.|\n)*?>/i
# || $$DATA =~ /<\s*MARQUEE(?:.|\n)*?>/i
# || $$DATA =~ /<\s*OBJECT(?:.|\n)*?>/i
# || $$DATA =~ /<\s*EMBED(?:.|\n)*?>/i
# || $$DATA =~ /<\s*FRAME(?:.|\n)*?>/i
# || $$DATA =~ /<\s*APPLET(?:.|\n)*?>/i
# || $$DATA =~ /<\s*FORM(?:.|\n)*?>/i
# || $$DATA =~ /<\s*(?:.|\n)*?\bSRC\s*=(?:.|\n)*?>/i
# || $$DATA =~ /<\s*(?:.|\n)*?\bDYNSRC\s*=(?:.|\n)*?>/i
# ) {
# $Infomation = '(the HTML tag which is not safe is included)';
# }
if($FileExt =~ /^txt$/i || $FileExt =~ /^cgi$/i || $FileExt =~ /^pl$/i) { # Text File
$Ext = 'txt';
} elsif($ContentType =~ /^text\/html$/i || $FileExt =~ /html?/i || $$DATA =~ /<\s*HTML(?:.|\n)*?>/i) { # HTML File
$Ext = 'html';
} elsif($ContentType =~ /^image\/x-xbitmap$/i || $FileExt =~ /^xbm$/i) { # XBM(x-BitMap) Image
my $XbmName = $1;
my ($XbmWidth, $XbmHeight);
if($$DATA =~ /\#define\s*$XbmName\_width\s*(\d+)/i) {
$XbmWidth = $1;
}
if($$DATA =~ /\#define\s*$XbmName\_height\s*(\d+)/i) {
$XbmHeight = $1;
}
if($XbmWidth && $XbmHeight) {
$Ext = 'xbm';
$ImageWidth = $XbmWidth;
$ImageHeight = $XbmHeight;
}
} else { #
$Ext = 'txt';
}
}
# image
if(!$Ext && ($UnknownType || $ContentType =~ /^image\//i)) {
# PNG
if($$DATA =~ /^\x89PNG\x0D\x0A\x1A\x0A/) {
if(substr($$DATA, 12, 4) eq 'IHDR') {
$Ext = 'png';
($ImageWidth, $ImageHeight) = unpack("N2", substr($$DATA, 16, 8));
}
} elsif($$DATA =~ /^GIF8(?:9|7)a/) { # GIF89a(modified), GIF89a, GIF87a
$Ext = 'gif';
($ImageWidth, $ImageHeight) = unpack("v2", substr($$DATA, 6, 4));
} elsif($$DATA =~ /^II\x2a\x00\x08\x00\x00\x00/ || $$DATA =~ /^MM\x00\x2a\x00\x00\x00\x08/) { # TIFF
$Ext = 'tif';
} elsif($$DATA =~ /^BM/) { # BMP
$Ext = 'bmp';
} elsif($$DATA =~ /^\xFF\xD8\xFF/ || $$DATA =~ /JFIF/) { # JPEG
my $HeaderPoint = index($$DATA, "\xFF\xD8\xFF", 0);
my $Point = $HeaderPoint + 2;
while($Point < $DataLength) {
my($Maker, $MakerType, $MakerLength) = unpack("C2n",substr($$DATA,$Point,4));
if($Maker != 0xFF || $MakerType == 0xd9 || $MakerType == 0xda) {
last;
} elsif($MakerType >= 0xC0 && $MakerType <= 0xC3) {
$Ext = 'jpg';
($ImageHeight, $ImageWidth) = unpack("n2", substr($$DATA, $Point + 5, 4));
if($HeaderPoint > 0) {
$$DATA = substr($$DATA, $HeaderPoint);
$DataLength = length($$DATA);
}
last;
} else {
$Point += $MakerLength + 2;
}
}
}
}
# audio
if(!$Ext && ($UnknownType || $ContentType =~ /^audio\//i)) {
# MIDI Audio
if($$DATA =~ /^MThd/) {
$Ext = 'mid';
} elsif($$DATA =~ /^\x2esnd/) { # ULAW Audio
$Ext = 'au';
} elsif($$DATA =~ /^RIFF/ || $$DATA =~ /^ID3/ && $$DATA =~ /RIFF/) {
my $HeaderPoint = index($$DATA, "RIFF", 0);
$_ = substr($$DATA, $HeaderPoint + 8, 8);
if(/^WAVEfmt $/) {
# WAVE
if(unpack("V",substr($$DATA, $HeaderPoint + 16, 4)) == 16) {
$Ext = 'wav';
} else { # RIFF WAVE MP3
$Ext = 'mp3';
}
} elsif(/^RMIDdata$/) { # RIFF MIDI
$Ext = 'rmi';
} elsif(/^RMP3data$/) { # RIFF MP3
$Ext = 'rmp';
}
if($ContentType =~ /^audio\//i) {
$Infomation .= '(RIFF '. substr($$DATA, $HeaderPoint + 8, 4). ')';
}
}
}
# a binary file
unless ($Ext) {
# PDF image
if($$DATA =~ /^\%PDF/) {
# Picture size is not measured.
$Ext = 'pdf';
} elsif($$DATA =~ /^FWS/) { # Shockwave Flash
$Ext = 'swf';
} elsif($$DATA =~ /^RIFF/ || $$DATA =~ /^ID3/ && $$DATA =~ /RIFF/) {
my $HeaderPoint = index($$DATA, "RIFF", 0);
$_ = substr($$DATA,$HeaderPoint + 8, 8);
# AVI
if(/^AVI LIST$/) {
$Ext = 'avi';
}
if($ContentType =~ /^video\//i) {
$Infomation .= '(RIFF '. substr($$DATA, $HeaderPoint + 8, 4). ')';
}
} elsif($$DATA =~ /^PK/) { # ZIP Compress File
$Ext = 'zip';
} elsif($$DATA =~ /^MSCF/) { # CAB Compress File
$Ext = 'cab';
} elsif($$DATA =~ /^Rar\!/) { # RAR Compress File
$Ext = 'rar';
} elsif(substr($$DATA, 2, 5) =~ /^\-lh(\d+|d)\-$/) { # LHA Compress File
$Infomation .= "(lh$1)";
$Ext = 'lzh';
} elsif(substr($$DATA, 325, 25) eq "Apple Video Media Handler" || substr($$DATA, 325, 30) eq "Apple \x83\x72\x83\x66\x83\x49\x81\x45\x83\x81\x83\x66\x83\x42\x83\x41\x83\x6E\x83\x93\x83\x68\x83\x89") {
# QuickTime
$Ext = 'mov';
}
}
# Header analysis failure
unless ($Ext) {
# It will be followed if it applies for the MIME type from the browser.
foreach (keys %UPLOAD_CONTENT_TYPE_LIST) {
next unless ($_);
if($ContentType =~ /^$_$/i) {
$Ext = $UPLOAD_CONTENT_TYPE_LIST{$_};
$ContentName = &CheckContentExt($Ext);
if(
grep {$_ eq $Ext;} (
'png',
'gif',
'jpg',
'xbm',
'tif',
'bmp',
'pdf',
'swf',
'mov',
'zip',
'cab',
'lzh',
'rar',
'mid',
'rmi',
'au',
'wav',
'avi',
'exe'
)
) {
$Infomation .= ' / Header analysis failure';
}
if($Ext ne $FileExt && &CheckContentExt($FileExt) eq $ContentName) {
$Ext = $FileExt;
}
last;
}
}
# a MIME type is unknown--It judges from an extension.
unless ($Ext) {
$ContentName = &CheckContentExt($FileExt);
if($ContentName) {
$Ext = $FileExt;
$Infomation .= ' / MIME type is unknown('. $ContentType. ')';
last;
}
}
}
# $ContentName = &CheckContentExt($Ext) unless($ContentName);
# if($Ext && $ContentName) {
# $ContentName .= $Infomation;
# } else {
# &upload_error(
# 'Extension Error',
# "$FileName A not corresponding extension ($Ext)<BR>The extension which can be responded ". join(',', sort values(%UPLOAD_EXT_LIST))
# );
# }
# # SSI Tag Deletion
# if($Ext =~ /.?html?/ && $$DATA =~ /<\!/) {
# foreach (
# 'config',
# 'echo',
# 'exec',
# 'flastmod',
# 'fsize',
# 'include'
# ) {
# $$DATA =~ s/\#\s*$_/\&\#35\;$_/ig
# }
# }
return (
$FileName,
$Ext,
int($DataLength / 1024 + 1),
$ImageWidth,
$ImageHeight,
$ContentName
);
}
##############################################################################
# Summary
#
# Extension discernment
#
# Parameters
# Returns
# Memo
##############################################################################
sub CheckContentExt
{
my($Ext) = @_;
my $ContentName;
foreach (keys %UPLOAD_EXT_LIST) {
next unless ($_);
if($_ && $Ext =~ /^$_$/) {
$ContentName = $UPLOAD_EXT_LIST{$_};
last;
}
}
return $ContentName;
}
##############################################################################
# Summary
#
# Form decode
#
# Parameters
# Returns
# Memo
##############################################################################
sub Encode
{
my($value,$Trans) = @_;
# my $FormCode = &jcode::getcode($value) || $FormCodeDefault;
# $FormCodeDefault ||= $FormCode;
#
# if($Trans && $TRANS_2BYTE_CODE) {
# if($FormCode ne 'euc') {
# &jcode::convert($value, 'euc', $FormCode);
# }
# &jcode::tr(
# $value,
# "\xA3\xB0-\xA3\xB9\xA3\xC1-\xA3\xDA\xA3\xE1-\xA3\xFA",
# '0-9A-Za-z'
# );
# if($CHARCODE ne 'euc') {
# &jcode::convert($value,$CHARCODE,'euc');
# }
# } else {
# if($CHARCODE ne $FormCode) {
# &jcode::convert($value,$CHARCODE,$FormCode);
# }
# }
# if($CHARCODE eq 'euc') {
# &jcode::h2z_euc($value);
# } elsif($CHARCODE eq 'sjis') {
# &jcode::h2z_sjis($value);
# }
}
##############################################################################
# Summary
#
# Error Msg
#
# Parameters
# Returns
# Memo
##############################################################################
sub upload_error
{
local($error_message) = $_[0];
local($error_message2) = $_[1];
print "Content-type: text/html\n\n";
print<<EOF;
<HTML>
<HEAD>
<TITLE>Error Message</TITLE></HEAD>
<BODY>
<table border="1" cellspacing="10" cellpadding="10">
<TR bgcolor="#0000B0">
<TD bgcolor="#0000B0" NOWRAP><font size="-1" color="white"><B>Error Message</B></font></TD>
</TR>
</table>
<UL>
<H4> $error_message </H4>
$error_message2 <BR>
</UL>
</BODY>
</HTML>
EOF
&rm_tmp_uploaded_files; # Image Temporary deletion
exit;
}
##############################################################################
# Summary
#
# Image Temporary deletion
#
# Parameters
# Returns
# Memo
##############################################################################
sub rm_tmp_uploaded_files
{
if($img_data_exists == 1){
sleep 1;
foreach $fname_list(@NEWFNAMES) {
if(-e "$img_dir/$fname_list") {
unlink("$img_dir/$fname_list");
}
}
}
}
1;

View file

@ -0,0 +1,68 @@
#####
# FCKeditor - The text editor for Internet - http://www.fckeditor.net
# Copyright (C) 2003-2007 Frederico Caldeira Knabben
#
# == BEGIN LICENSE ==
#
# Licensed under the terms of any of the following licenses at your
# choice:
#
# - GNU General Public License Version 2 or later (the "GPL")
# http://www.gnu.org/licenses/gpl.html
#
# - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
# http://www.gnu.org/licenses/lgpl.html
#
# - Mozilla Public License Version 1.1 or later (the "MPL")
# http://www.mozilla.org/MPL/MPL-1.1.html
#
# == END LICENSE ==
#
# This is the File Manager Connector for Perl.
#####
sub RemoveFromStart
{
local($sourceString, $charToRemove) = @_;
$sPattern = '^' . $charToRemove . '+' ;
$sourceString =~ s/^$charToRemove+//g;
return $sourceString;
}
sub RemoveFromEnd
{
local($sourceString, $charToRemove) = @_;
$sPattern = $charToRemove . '+$' ;
$sourceString =~ s/$charToRemove+$//g;
return $sourceString;
}
sub ConvertToXmlAttribute
{
local($value) = @_;
return $value;
# return utf8_encode(htmlspecialchars($value));
}
sub specialchar_cnv
{
local($ch) = @_;
$ch =~ s/&/&amp;/g; # &
$ch =~ s/\"/&quot;/g; #"
$ch =~ s/\'/&#39;/g; # '
$ch =~ s/</&lt;/g; # <
$ch =~ s/>/&gt;/g; # >
return($ch);
}
sub JS_cnv
{
local($ch) = @_;
$ch =~ s/\"/\\\"/g; #"
return($ch);
}
1;

View file

@ -0,0 +1,93 @@
<?php
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2007 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* These functions define the base of the XML response sent by the PHP
* connector.
*/
function SetXmlHeaders()
{
ob_end_clean() ;
// Prevent the browser from caching the result.
// Date in the past
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT') ;
// always modified
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT') ;
// HTTP/1.1
header('Cache-Control: no-store, no-cache, must-revalidate') ;
header('Cache-Control: post-check=0, pre-check=0', false) ;
// HTTP/1.0
header('Pragma: no-cache') ;
// Set the response format.
header( 'Content-Type: text/xml; charset=utf-8' ) ;
}
function CreateXmlHeader( $command, $resourceType, $currentFolder )
{
SetXmlHeaders() ;
// Create the XML document header.
echo '<?xml version="1.0" encoding="utf-8" ?>' ;
// Create the main "Connector" node.
echo '<Connector command="' . $command . '" resourceType="' . $resourceType . '">' ;
// Add the current folder node.
echo '<CurrentFolder path="' . ConvertToXmlAttribute( $currentFolder ) . '" url="' . ConvertToXmlAttribute( GetUrlFromPath( $resourceType, $currentFolder, $command ) ) . '" />' ;
$GLOBALS['HeaderSent'] = true ;
}
function CreateXmlFooter()
{
echo '</Connector>' ;
}
function SendError( $number, $text )
{
if ( isset( $GLOBALS['HeaderSent'] ) && $GLOBALS['HeaderSent'] )
{
SendErrorNode( $number, $text ) ;
CreateXmlFooter() ;
}
else
{
SetXmlHeaders() ;
// Create the XML document header
echo '<?xml version="1.0" encoding="utf-8" ?>' ;
echo '<Connector>' ;
SendErrorNode( $number, $text ) ;
echo '</Connector>' ;
}
exit ;
}
function SendErrorNode( $number, $text )
{
echo '<Error number="' . $number . '" text="' . htmlspecialchars( $text ) . '" />' ;
}
?>

View file

@ -0,0 +1,245 @@
<?php
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2007 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* This is the File Manager Connector for PHP.
*/
function GetFolders( $resourceType, $currentFolder )
{
// Map the virtual path to the local server path.
$sServerDir = ServerMapFolder( $resourceType, $currentFolder, 'GetFolders' ) ;
// Array that will hold the folders names.
$aFolders = array() ;
$oCurrentFolder = opendir( $sServerDir ) ;
while ( $sFile = readdir( $oCurrentFolder ) )
{
if ( $sFile != '.' && $sFile != '..' && is_dir( $sServerDir . $sFile ) )
$aFolders[] = '<Folder name="' . ConvertToXmlAttribute( $sFile ) . '" />' ;
}
closedir( $oCurrentFolder ) ;
// Open the "Folders" node.
echo "<Folders>" ;
natcasesort( $aFolders ) ;
foreach ( $aFolders as $sFolder )
echo $sFolder ;
// Close the "Folders" node.
echo "</Folders>" ;
}
function GetFoldersAndFiles( $resourceType, $currentFolder )
{
// Map the virtual path to the local server path.
$sServerDir = ServerMapFolder( $resourceType, $currentFolder, 'GetFoldersAndFiles' ) ;
// Arrays that will hold the folders and files names.
$aFolders = array() ;
$aFiles = array() ;
$oCurrentFolder = opendir( $sServerDir ) ;
while ( $sFile = readdir( $oCurrentFolder ) )
{
if ( $sFile != '.' && $sFile != '..' )
{
if ( is_dir( $sServerDir . $sFile ) )
$aFolders[] = '<Folder name="' . ConvertToXmlAttribute( $sFile ) . '" />' ;
else
{
$iFileSize = @filesize( $sServerDir . $sFile ) ;
if ( !$iFileSize ) {
$iFileSize = 0 ;
}
if ( $iFileSize > 0 )
{
$iFileSize = round( $iFileSize / 1024 ) ;
if ( $iFileSize < 1 ) $iFileSize = 1 ;
}
$aFiles[] = '<File name="' . ConvertToXmlAttribute( $sFile ) . '" size="' . $iFileSize . '" />' ;
}
}
}
// Send the folders
natcasesort( $aFolders ) ;
echo '<Folders>' ;
foreach ( $aFolders as $sFolder )
echo $sFolder ;
echo '</Folders>' ;
// Send the files
natcasesort( $aFiles ) ;
echo '<Files>' ;
foreach ( $aFiles as $sFiles )
echo $sFiles ;
echo '</Files>' ;
}
function CreateFolder( $resourceType, $currentFolder )
{
if (!isset($_GET)) {
global $_GET;
}
$sErrorNumber = '0' ;
$sErrorMsg = '' ;
if ( isset( $_GET['NewFolderName'] ) )
{
$sNewFolderName = $_GET['NewFolderName'] ;
$sNewFolderName = SanitizeFolderName( $sNewFolderName ) ;
if ( strpos( $sNewFolderName, '..' ) !== FALSE )
$sErrorNumber = '102' ; // Invalid folder name.
else
{
// Map the virtual path to the local server path of the current folder.
$sServerDir = ServerMapFolder( $resourceType, $currentFolder, 'CreateFolder' ) ;
if ( is_writable( $sServerDir ) )
{
$sServerDir .= $sNewFolderName ;
$sErrorMsg = CreateServerFolder( $sServerDir ) ;
switch ( $sErrorMsg )
{
case '' :
$sErrorNumber = '0' ;
break ;
case 'Invalid argument' :
case 'No such file or directory' :
$sErrorNumber = '102' ; // Path too long.
break ;
default :
$sErrorNumber = '110' ;
break ;
}
}
else
$sErrorNumber = '103' ;
}
}
else
$sErrorNumber = '102' ;
// Create the "Error" node.
echo '<Error number="' . $sErrorNumber . '" originalDescription="' . ConvertToXmlAttribute( $sErrorMsg ) . '" />' ;
}
function FileUpload( $resourceType, $currentFolder, $sCommand )
{
if (!isset($_FILES)) {
global $_FILES;
}
$sErrorNumber = '0' ;
$sFileName = '' ;
if ( isset( $_FILES['NewFile'] ) && !is_null( $_FILES['NewFile']['tmp_name'] ) )
{
global $Config ;
$oFile = $_FILES['NewFile'] ;
// Map the virtual path to the local server path.
$sServerDir = ServerMapFolder( $resourceType, $currentFolder, $sCommand ) ;
// Get the uploaded file name.
$sFileName = $oFile['name'] ;
$sFileName = SanitizeFileName( $sFileName ) ;
$sOriginalFileName = $sFileName ;
// Get the extension.
$sExtension = substr( $sFileName, ( strrpos($sFileName, '.') + 1 ) ) ;
$sExtension = strtolower( $sExtension ) ;
if ( isset( $Config['SecureImageUploads'] ) )
{
if ( !IsImageValid( $oFile['tmp_name'], $sExtension ) )
{
$sErrorNumber = '202' ;
}
}
if ( isset( $Config['HtmlExtensions'] ) )
{
if ( !IsHtmlExtension( $sExtension, $Config['HtmlExtensions'] ) && DetectHtml( $oFile['tmp_name'] ) )
{
$sErrorNumber = '202' ;
}
}
// Check if it is an allowed extension.
if ( !$sErrorNumber && IsAllowedExt( $sExtension, $resourceType ) )
{
$iCounter = 0 ;
while ( true )
{
$sFilePath = $sServerDir . $sFileName ;
if ( is_file( $sFilePath ) )
{
$iCounter++ ;
$sFileName = RemoveExtension( $sOriginalFileName ) . '(' . $iCounter . ').' . $sExtension ;
$sErrorNumber = '201' ;
}
else
{
move_uploaded_file( $oFile['tmp_name'], $sFilePath ) ;
if ( is_file( $sFilePath ) )
{
$oldumask = umask(0) ;
chmod( $sFilePath, 0777 ) ;
umask( $oldumask ) ;
}
break ;
}
}
}
else
$sErrorNumber = '202' ;
}
else
$sErrorNumber = '202' ;
$sFileUrl = CombinePaths( GetResourceTypePath( $resourceType, $sCommand ) , $currentFolder ) ;
$sFileUrl = CombinePaths( $sFileUrl, $sFileName ) ;
SendUploadResults( $sErrorNumber, $sFileUrl, $sFileName ) ;
exit ;
}
?>

View file

@ -0,0 +1,140 @@
<?php
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2007 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Configuration file for the File Manager Connector for PHP.
*/
global $Config ;
// SECURITY: You must explicitly enable this "connector". (Set it to "true").
// WARNING: don't just set "$Config['Enabled'] = true ;", you must be sure that only
// authenticated users can access this file or use some kind of session checking.
$Config['Enabled'] = false ;
// Path to user files relative to the document root.
$Config['UserFilesPath'] = '/userfiles/' ;
// Fill the following value it you prefer to specify the absolute path for the
// user files directory. Useful if you are using a virtual directory, symbolic
// link or alias. Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
// Attention: The above 'UserFilesPath' must point to the same directory.
$Config['UserFilesAbsolutePath'] = '' ;
// Due to security issues with Apache modules, it is recommended to leave the
// following setting enabled.
$Config['ForceSingleExtension'] = true ;
// Perform additional checks for image files
// if set to true, validate image size (using getimagesize)
$Config['SecureImageUploads'] = true;
// What the user can do with this connector
$Config['ConfigAllowedCommands'] = array('QuickUpload', 'FileUpload', 'GetFolders', 'GetFoldersAndFiles', 'CreateFolder') ;
// Allowed Resource Types
$Config['ConfigAllowedTypes'] = array('File', 'Image', 'Flash', 'Media') ;
// For security, HTML is allowed in the first Kb of data for files having the
// following extensions only.
$Config['HtmlExtensions'] = array("html", "htm", "xml", "xsd", "txt", "js") ;
/*
Configuration settings for each Resource Type
- AllowedExtensions: the possible extensions that can be allowed.
If it is empty then any file type can be uploaded.
- DeniedExtensions: The extensions that won't be allowed.
If it is empty then no restrictions are done here.
For a file to be uploaded it has to fulfill both the AllowedExtensions
and DeniedExtensions (that's it: not being denied) conditions.
- FileTypesPath: the virtual folder relative to the document root where
these resources will be located.
Attention: It must start and end with a slash: '/'
- FileTypesAbsolutePath: the physical path to the above folder. It must be
an absolute path.
If it's an empty string then it will be autocalculated.
Useful if you are using a virtual directory, symbolic link or alias.
Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
Attention: The above 'FileTypesPath' must point to the same directory.
Attention: It must end with a slash: '/'
- QuickUploadPath: the virtual folder relative to the document root where
these resources will be uploaded using the Upload tab in the resources
dialogs.
Attention: It must start and end with a slash: '/'
- QuickUploadAbsolutePath: the physical path to the above folder. It must be
an absolute path.
If it's an empty string then it will be autocalculated.
Useful if you are using a virtual directory, symbolic link or alias.
Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
Attention: The above 'QuickUploadPath' must point to the same directory.
Attention: It must end with a slash: '/'
NOTE: by default, QuickUploadPath and QuickUploadAbsolutePath point to
"userfiles" directory to maintain backwards compatibility with older versions of FCKeditor.
This is fine, but you in some cases you will be not able to browse uploaded files using file browser.
Example: if you click on "image button", select "Upload" tab and send image
to the server, image will appear in FCKeditor correctly, but because it is placed
directly in /userfiles/ directory, you'll be not able to see it in built-in file browser.
The more expected behaviour would be to send images directly to "image" subfolder.
To achieve that, simply change
$Config['QuickUploadPath']['Image'] = $Config['UserFilesPath'] ;
$Config['QuickUploadAbsolutePath']['Image'] = $Config['UserFilesAbsolutePath'] ;
into:
$Config['QuickUploadPath']['Image'] = $Config['FileTypesPath']['Image'] ;
$Config['QuickUploadAbsolutePath']['Image'] = $Config['FileTypesAbsolutePath']['Image'] ;
*/
$Config['AllowedExtensions']['File'] = array('7z', 'aiff', 'asf', 'avi', 'bmp', 'csv', 'doc', 'fla', 'flv', 'gif', 'gz', 'gzip', 'jpeg', 'jpg', 'mid', 'mov', 'mp3', 'mp4', 'mpc', 'mpeg', 'mpg', 'ods', 'odt', 'pdf', 'png', 'ppt', 'pxd', 'qt', 'ram', 'rar', 'rm', 'rmi', 'rmvb', 'rtf', 'sdc', 'sitd', 'swf', 'sxc', 'sxw', 'tar', 'tgz', 'tif', 'tiff', 'txt', 'vsd', 'wav', 'wma', 'wmv', 'xls', 'xml', 'zip') ;
$Config['DeniedExtensions']['File'] = array() ;
$Config['FileTypesPath']['File'] = $Config['UserFilesPath'] . 'file/' ;
$Config['FileTypesAbsolutePath']['File']= ($Config['UserFilesAbsolutePath'] == '') ? '' : $Config['UserFilesAbsolutePath'].'file/' ;
$Config['QuickUploadPath']['File'] = $Config['UserFilesPath'] ;
$Config['QuickUploadAbsolutePath']['File']= $Config['UserFilesAbsolutePath'] ;
$Config['AllowedExtensions']['Image'] = array('bmp','gif','jpeg','jpg','png') ;
$Config['DeniedExtensions']['Image'] = array() ;
$Config['FileTypesPath']['Image'] = $Config['UserFilesPath'] . 'image/' ;
$Config['FileTypesAbsolutePath']['Image']= ($Config['UserFilesAbsolutePath'] == '') ? '' : $Config['UserFilesAbsolutePath'].'image/' ;
$Config['QuickUploadPath']['Image'] = $Config['UserFilesPath'] ;
$Config['QuickUploadAbsolutePath']['Image']= $Config['UserFilesAbsolutePath'] ;
$Config['AllowedExtensions']['Flash'] = array('swf','flv') ;
$Config['DeniedExtensions']['Flash'] = array() ;
$Config['FileTypesPath']['Flash'] = $Config['UserFilesPath'] . 'flash/' ;
$Config['FileTypesAbsolutePath']['Flash']= ($Config['UserFilesAbsolutePath'] == '') ? '' : $Config['UserFilesAbsolutePath'].'flash/' ;
$Config['QuickUploadPath']['Flash'] = $Config['UserFilesPath'] ;
$Config['QuickUploadAbsolutePath']['Flash']= $Config['UserFilesAbsolutePath'] ;
$Config['AllowedExtensions']['Media'] = array('aiff', 'asf', 'avi', 'bmp', 'fla', 'flv', 'gif', 'jpeg', 'jpg', 'mid', 'mov', 'mp3', 'mp4', 'mpc', 'mpeg', 'mpg', 'png', 'qt', 'ram', 'rm', 'rmi', 'rmvb', 'swf', 'tif', 'tiff', 'wav', 'wma', 'wmv') ;
$Config['DeniedExtensions']['Media'] = array() ;
$Config['FileTypesPath']['Media'] = $Config['UserFilesPath'] . 'media/' ;
$Config['FileTypesAbsolutePath']['Media']= ($Config['UserFilesAbsolutePath'] == '') ? '' : $Config['UserFilesAbsolutePath'].'media/' ;
$Config['QuickUploadPath']['Media'] = $Config['UserFilesPath'] ;
$Config['QuickUploadAbsolutePath']['Media']= $Config['UserFilesAbsolutePath'] ;
?>

View file

@ -0,0 +1,87 @@
<?php
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2007 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* This is the File Manager Connector for PHP.
*/
ob_start() ;
require('./config.php') ;
require('./util.php') ;
require('./io.php') ;
require('./basexml.php') ;
require('./commands.php') ;
require('./phpcompat.php') ;
if ( !$Config['Enabled'] )
SendError( 1, 'This connector is disabled. Please check the "editor/filemanager/connectors/php/config.php" file' ) ;
DoResponse() ;
function DoResponse()
{
if (!isset($_GET)) {
global $_GET;
}
if ( !isset( $_GET['Command'] ) || !isset( $_GET['Type'] ) || !isset( $_GET['CurrentFolder'] ) )
return ;
// Get the main request informaiton.
$sCommand = $_GET['Command'] ;
$sResourceType = $_GET['Type'] ;
$sCurrentFolder = GetCurrentFolder() ;
// Check if it is an allowed command
if ( ! IsAllowedCommand( $sCommand ) )
SendError( 1, 'The "' . $sCommand . '" command isn\'t allowed' ) ;
// Check if it is an allowed type.
if ( !IsAllowedType( $sResourceType ) )
SendError( 1, 'Invalid type specified' ) ;
// File Upload doesn't have to Return XML, so it must be intercepted before anything.
if ( $sCommand == 'FileUpload' )
{
FileUpload( $sResourceType, $sCurrentFolder, $sCommand ) ;
return ;
}
CreateXmlHeader( $sCommand, $sResourceType, $sCurrentFolder ) ;
// Execute the required command.
switch ( $sCommand )
{
case 'GetFolders' :
GetFolders( $sResourceType, $sCurrentFolder ) ;
break ;
case 'GetFoldersAndFiles' :
GetFoldersAndFiles( $sResourceType, $sCurrentFolder ) ;
break ;
case 'CreateFolder' :
CreateFolder( $sResourceType, $sCurrentFolder ) ;
break ;
}
CreateXmlFooter() ;
exit ;
}
?>

View file

@ -0,0 +1,272 @@
<?php
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2007 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* This is the File Manager Connector for PHP.
*/
function CombinePaths( $sBasePath, $sFolder )
{
return RemoveFromEnd( $sBasePath, '/' ) . '/' . RemoveFromStart( $sFolder, '/' ) ;
}
function GetResourceTypePath( $resourceType, $sCommand )
{
global $Config ;
if ( $sCommand == "QuickUpload")
return $Config['QuickUploadPath'][$resourceType] ;
else
return $Config['FileTypesPath'][$resourceType] ;
}
function GetResourceTypeDirectory( $resourceType, $sCommand )
{
global $Config ;
if ( $sCommand == "QuickUpload")
{
if ( strlen( $Config['QuickUploadAbsolutePath'][$resourceType] ) > 0 )
return $Config['QuickUploadAbsolutePath'][$resourceType] ;
// Map the "UserFiles" path to a local directory.
return Server_MapPath( $Config['QuickUploadPath'][$resourceType] ) ;
}
else
{
if ( strlen( $Config['FileTypesAbsolutePath'][$resourceType] ) > 0 )
return $Config['FileTypesAbsolutePath'][$resourceType] ;
// Map the "UserFiles" path to a local directory.
return Server_MapPath( $Config['FileTypesPath'][$resourceType] ) ;
}
}
function GetUrlFromPath( $resourceType, $folderPath, $sCommand )
{
return CombinePaths( GetResourceTypePath( $resourceType, $sCommand ), $folderPath ) ;
}
function RemoveExtension( $fileName )
{
return substr( $fileName, 0, strrpos( $fileName, '.' ) ) ;
}
function ServerMapFolder( $resourceType, $folderPath, $sCommand )
{
// Get the resource type directory.
$sResourceTypePath = GetResourceTypeDirectory( $resourceType, $sCommand ) ;
// Ensure that the directory exists.
$sErrorMsg = CreateServerFolder( $sResourceTypePath ) ;
if ( $sErrorMsg != '' )
SendError( 1, "Error creating folder \"{$sResourceTypePath}\" ({$sErrorMsg})" ) ;
// Return the resource type directory combined with the required path.
return CombinePaths( $sResourceTypePath , $folderPath ) ;
}
function GetParentFolder( $folderPath )
{
$sPattern = "-[/\\\\][^/\\\\]+[/\\\\]?$-" ;
return preg_replace( $sPattern, '', $folderPath ) ;
}
function CreateServerFolder( $folderPath, $lastFolder = null )
{
$sParent = GetParentFolder( $folderPath ) ;
// Ensure the folder path has no double-slashes, or mkdir may fail on certain platforms
while ( strpos($folderPath, '//') !== false )
{
$folderPath = str_replace( '//', '/', $folderPath ) ;
}
// Check if the parent exists, or create it.
if ( !file_exists( $sParent ) )
{
//prevents agains infinite loop when we can't create root folder
if ( !is_null( $lastFolder ) && $lastFolder === $sParent) {
return "Can't create $folderPath directory" ;
}
$sErrorMsg = CreateServerFolder( $sParent, $folderPath ) ;
if ( $sErrorMsg != '' )
return $sErrorMsg ;
}
if ( !file_exists( $folderPath ) )
{
// Turn off all error reporting.
error_reporting( 0 ) ;
$php_errormsg = '' ;
// Enable error tracking to catch the error.
ini_set( 'track_errors', '1' ) ;
// To create the folder with 0777 permissions, we need to set umask to zero.
$oldumask = umask(0) ;
mkdir( $folderPath, 0777 ) ;
umask( $oldumask ) ;
$sErrorMsg = $php_errormsg ;
// Restore the configurations.
ini_restore( 'track_errors' ) ;
ini_restore( 'error_reporting' ) ;
return $sErrorMsg ;
}
else
return '' ;
}
function GetRootPath()
{
if (!isset($_SERVER)) {
global $_SERVER;
}
$sRealPath = realpath( './' ) ;
$sSelfPath = $_SERVER['PHP_SELF'] ;
$sSelfPath = substr( $sSelfPath, 0, strrpos( $sSelfPath, '/' ) ) ;
$sSelfPath = str_replace( '/', DIRECTORY_SEPARATOR, $sSelfPath ) ;
$position = strpos( $sRealPath, $sSelfPath ) ;
// This can check only that this script isn't run from a virtual dir
// But it avoids the problems that arise if it isn't checked
if ( $position === false || $position <> strlen( $sRealPath ) - strlen( $sSelfPath ) )
SendError( 1, 'Sorry, can\'t map "UserFilesPath" to a physical path. You must set the "UserFilesAbsolutePath" value in "editor/filemanager/connectors/php/config.php".' ) ;
return substr( $sRealPath, 0, $position ) ;
}
// Emulate the asp Server.mapPath function.
// given an url path return the physical directory that it corresponds to
function Server_MapPath( $path )
{
// This function is available only for Apache
if ( function_exists( 'apache_lookup_uri' ) )
{
$info = apache_lookup_uri( $path ) ;
return $info->filename . $info->path_info ;
}
// This isn't correct but for the moment there's no other solution
// If this script is under a virtual directory or symlink it will detect the problem and stop
return GetRootPath() . $path ;
}
function IsAllowedExt( $sExtension, $resourceType )
{
global $Config ;
// Get the allowed and denied extensions arrays.
$arAllowed = $Config['AllowedExtensions'][$resourceType] ;
$arDenied = $Config['DeniedExtensions'][$resourceType] ;
if ( count($arAllowed) > 0 && !in_array( $sExtension, $arAllowed ) )
return false ;
if ( count($arDenied) > 0 && in_array( $sExtension, $arDenied ) )
return false ;
return true ;
}
function IsAllowedType( $resourceType )
{
global $Config ;
if ( !in_array( $resourceType, $Config['ConfigAllowedTypes'] ) )
return false ;
return true ;
}
function IsAllowedCommand( $sCommand )
{
global $Config ;
if ( !in_array( $sCommand, $Config['ConfigAllowedCommands'] ) )
return false ;
return true ;
}
function GetCurrentFolder()
{
if (!isset($_GET)) {
global $_GET;
}
$sCurrentFolder = isset( $_GET['CurrentFolder'] ) ? $_GET['CurrentFolder'] : '/' ;
// Check the current folder syntax (must begin and start with a slash).
if ( ! ereg( '/$', $sCurrentFolder ) ) $sCurrentFolder .= '/' ;
if ( strpos( $sCurrentFolder, '/' ) !== 0 ) $sCurrentFolder = '/' . $sCurrentFolder ;
// Ensure the folder path has no double-slashes
while ( strpos ($sCurrentFolder, '//') !== false ) {
$sCurrentFolder = str_replace ('//', '/', $sCurrentFolder) ;
}
// Check for invalid folder paths (..)
if ( strpos( $sCurrentFolder, '..' ) )
SendError( 102, '' ) ;
return $sCurrentFolder ;
}
// Do a cleanup of the folder name to avoid possible problems
function SanitizeFolderName( $sNewFolderName )
{
$sNewFolderName = stripslashes( $sNewFolderName ) ;
// Remove . \ / | : ? * " < >
$sNewFolderName = preg_replace( '/\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>/', '_', $sNewFolderName ) ;
return $sNewFolderName ;
}
// Do a cleanup of the file name to avoid possible problems
function SanitizeFileName( $sNewFileName )
{
global $Config ;
$sNewFileName = stripslashes( $sNewFileName ) ;
// Replace dots in the name with underscores (only one dot can be there... security issue).
if ( $Config['ForceSingleExtension'] )
$sNewFileName = preg_replace( '/\\.(?![^.]*$)/', '_', $sNewFileName ) ;
// Remove \ / | : ? * " < >
$sNewFileName = preg_replace( '/\\\\|\\/|\\||\\:|\\?|\\*|"|<|>/', '_', $sNewFileName ) ;
return $sNewFileName ;
}
// This is the function that sends the results of the uploading process.
function SendUploadResults( $errorNumber, $fileUrl = '', $fileName = '', $customMsg = '' )
{
echo '<script type="text/javascript">' ;
$rpl = array( '\\' => '\\\\', '"' => '\\"' ) ;
echo 'window.parent.OnUploadCompleted(' . $errorNumber . ',"' . strtr( $fileUrl, $rpl ) . '","' . strtr( $fileName, $rpl ) . '", "' . strtr( $customMsg, $rpl ) . '") ;' ;
echo '</script>' ;
exit ;
}
?>

View file

@ -0,0 +1,17 @@
<?php
if ( !isset( $_SERVER ) ) {
$_SERVER = $HTTP_SERVER_VARS ;
}
if ( !isset( $_GET ) ) {
$_GET = $HTTP_GET_VARS ;
}
if ( !isset( $_FILES ) ) {
$_FILES = $HTTP_POST_FILES ;
}
if ( !defined( 'DIRECTORY_SEPARATOR' ) ) {
define( 'DIRECTORY_SEPARATOR',
strtoupper(substr(PHP_OS, 0, 3) == 'WIN') ? '\\' : '/'
) ;
}

View file

@ -0,0 +1,59 @@
<?php
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2007 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* This is the "File Uploader" for PHP.
*/
require('./config.php') ;
require('./util.php') ;
require('./io.php') ;
require('./commands.php') ;
require('./phpcompat.php') ;
function SendError( $number, $text )
{
SendUploadResults( $number, '', '', $text ) ;
}
// Check if this uploader has been enabled.
if ( !$Config['Enabled'] )
SendUploadResults( '1', '', '', 'This file uploader is disabled. Please check the "editor/filemanager/connectors/php/config.php" file' ) ;
$sCommand = 'QuickUpload' ;
// The file type (from the QueryString, by default 'File').
$sType = isset( $_GET['Type'] ) ? $_GET['Type'] : 'File' ;
$sCurrentFolder = GetCurrentFolder() ;
// Is enabled the upload?
if ( ! IsAllowedCommand( $sCommand ) )
SendUploadResults( '1', '', '', 'The ""' . $sCommand . '"" command isn\'t allowed' ) ;
// Check if it is an allowed type.
if ( !IsAllowedType( $sType ) )
SendUploadResults( 1, '', '', 'Invalid type specified' ) ;
FileUpload( $sType, $sCurrentFolder, $sCommand )
?>

View file

@ -0,0 +1,185 @@
<?php
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2007 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Utility functions for the File Manager Connector for PHP.
*/
function RemoveFromStart( $sourceString, $charToRemove )
{
$sPattern = '|^' . $charToRemove . '+|' ;
return preg_replace( $sPattern, '', $sourceString ) ;
}
function RemoveFromEnd( $sourceString, $charToRemove )
{
$sPattern = '|' . $charToRemove . '+$|' ;
return preg_replace( $sPattern, '', $sourceString ) ;
}
function ConvertToXmlAttribute( $value )
{
if ( defined( 'PHP_OS' ) )
{
$os = PHP_OS ;
}
else
{
$os = php_uname() ;
}
if ( strtoupper( substr( $os, 0, 3 ) ) === 'WIN' )
{
return ( utf8_encode( htmlspecialchars( $value ) ) ) ;
}
else
{
return ( htmlspecialchars( $value ) ) ;
}
}
/**
* Check whether given extension is in html etensions list
*
* @param string $ext
* @param array $htmlExtensions
* @return boolean
*/
function IsHtmlExtension( $ext, $htmlExtensions )
{
if ( !$htmlExtensions || !is_array( $htmlExtensions ) )
{
return false ;
}
$lcaseHtmlExtensions = array() ;
foreach ( $htmlExtensions as $key => $val )
{
$lcaseHtmlExtensions[$key] = strtolower( $val ) ;
}
return in_array( $ext, $lcaseHtmlExtensions ) ;
}
/**
* Detect HTML in the first KB to prevent against potential security issue with
* IE/Safari/Opera file type auto detection bug.
* Returns true if file contain insecure HTML code at the beginning.
*
* @param string $filePath absolute path to file
* @return boolean
*/
function DetectHtml( $filePath )
{
$fp = fopen( $filePath, 'rb' ) ;
$chunk = fread( $fp, 1024 ) ;
fclose( $fp ) ;
$chunk = strtolower( $chunk ) ;
if (!$chunk)
{
return false ;
}
$chunk = trim( $chunk ) ;
if ( preg_match( "/<!DOCTYPE\W*X?HTML/sim", $chunk ) )
{
return true;
}
$tags = array( '<body', '<head', '<html', '<img', '<pre', '<script', '<table', '<title' ) ;
foreach( $tags as $tag )
{
if( false !== strpos( $chunk, $tag ) )
{
return true ;
}
}
//type = javascript
if ( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) )
{
return true ;
}
//href = javascript
//src = javascript
//data = javascript
if ( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) )
{
return true ;
}
//url(javascript
if ( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) )
{
return true ;
}
return false ;
}
/**
* Check file content.
* Currently this function validates only image files.
* Returns false if file is invalid.
*
* @param string $filePath absolute path to file
* @param string $extension file extension
* @param integer $detectionLevel 0 = none, 1 = use getimagesize for images, 2 = use DetectHtml for images
* @return boolean
*/
function IsImageValid( $filePath, $extension )
{
$imageCheckExtensions = array('gif', 'jpeg', 'jpg', 'png', 'swf', 'psd', 'bmp', 'iff');
// version_compare is available since PHP4 >= 4.0.7
if ( function_exists( 'version_compare' ) ) {
$sCurrentVersion = phpversion();
if ( version_compare( $sCurrentVersion, "4.2.0" ) >= 0 ) {
$imageCheckExtensions[] = "tiff";
$imageCheckExtensions[] = "tif";
}
if ( version_compare( $sCurrentVersion, "4.3.0" ) >= 0 ) {
$imageCheckExtensions[] = "swc";
}
if ( version_compare( $sCurrentVersion, "4.3.2" ) >= 0 ) {
$imageCheckExtensions[] = "jpc";
$imageCheckExtensions[] = "jp2";
$imageCheckExtensions[] = "jpx";
$imageCheckExtensions[] = "jb2";
$imageCheckExtensions[] = "xbm";
$imageCheckExtensions[] = "wbmp";
}
}
if ( !in_array( $extension, $imageCheckExtensions ) ) {
return true;
}
if ( @getimagesize( $filePath ) === false ) {
return false ;
}
return true;
}
?>

View file

@ -0,0 +1,135 @@
#!/usr/bin/env python
"""
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2007 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Configuration file for the File Manager Connector for Python
"""
# INSTALLATION NOTE: You must set up your server environment accordingly to run
# python scripts. This connector requires Python 2.4 or greater.
#
# Supported operation modes:
# * WSGI (recommended): You'll need apache + mod_python + modpython_gateway
# or any web server capable of the WSGI python standard
# * Plain Old CGI: Any server capable of running standard python scripts
# (although mod_python is recommended for performance)
# This was the previous connector version operation mode
#
# If you're using Apache web server, replace the htaccess.txt to to .htaccess,
# and set the proper options and paths.
# For WSGI and mod_python, you may need to download modpython_gateway from:
# http://projects.amor.org/misc/svn/modpython_gateway.py and copy it in this
# directory.
# SECURITY: You must explicitly enable this "connector". (Set it to "True").
# WARNING: don't just set "ConfigIsEnabled = True", you must be sure that only
# authenticated users can access this file or use some kind of session checking.
Enabled = False
# Path to user files relative to the document root.
UserFilesPath = '/userfiles/'
# Fill the following value it you prefer to specify the absolute path for the
# user files directory. Useful if you are using a virtual directory, symbolic
# link or alias. Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
# Attention: The above 'UserFilesPath' must point to the same directory.
# WARNING: GetRootPath may not work in virtual or mod_python configurations, and
# may not be thread safe. Use this configuration parameter instead.
UserFilesAbsolutePath = ''
# Due to security issues with Apache modules, it is recommended to leave the
# following setting enabled.
ForceSingleExtension = True
# What the user can do with this connector
ConfigAllowedCommands = [ 'QuickUpload', 'FileUpload', 'GetFolders', 'GetFoldersAndFiles', 'CreateFolder' ]
# Allowed Resource Types
ConfigAllowedTypes = ['File', 'Image', 'Flash', 'Media']
# Do not touch this 3 lines, see "Configuration settings for each Resource Type"
AllowedExtensions = {}; DeniedExtensions = {};
FileTypesPath = {}; FileTypesAbsolutePath = {};
QuickUploadPath = {}; QuickUploadAbsolutePath = {};
# Configuration settings for each Resource Type
#
# - AllowedExtensions: the possible extensions that can be allowed.
# If it is empty then any file type can be uploaded.
# - DeniedExtensions: The extensions that won't be allowed.
# If it is empty then no restrictions are done here.
#
# For a file to be uploaded it has to fulfill both the AllowedExtensions
# and DeniedExtensions (that's it: not being denied) conditions.
#
# - FileTypesPath: the virtual folder relative to the document root where
# these resources will be located.
# Attention: It must start and end with a slash: '/'
#
# - FileTypesAbsolutePath: the physical path to the above folder. It must be
# an absolute path.
# If it's an empty string then it will be autocalculated.
# Useful if you are using a virtual directory, symbolic link or alias.
# Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
# Attention: The above 'FileTypesPath' must point to the same directory.
# Attention: It must end with a slash: '/'
#
#
# - QuickUploadPath: the virtual folder relative to the document root where
# these resources will be uploaded using the Upload tab in the resources
# dialogs.
# Attention: It must start and end with a slash: '/'
#
# - QuickUploadAbsolutePath: the physical path to the above folder. It must be
# an absolute path.
# If it's an empty string then it will be autocalculated.
# Useful if you are using a virtual directory, symbolic link or alias.
# Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
# Attention: The above 'QuickUploadPath' must point to the same directory.
# Attention: It must end with a slash: '/'
AllowedExtensions['File'] = ['7z','aiff','asf','avi','bmp','csv','doc','fla','flv','gif','gz','gzip','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','ods','odt','pdf','png','ppt','pxd','qt','ram','rar','rm','rmi','rmvb','rtf','sdc','sitd','swf','sxc','sxw','tar','tgz','tif','tiff','txt','vsd','wav','wma','wmv','xls','xml','zip']
DeniedExtensions['File'] = []
FileTypesPath['File'] = UserFilesPath + 'file/'
FileTypesAbsolutePath['File'] = (not UserFilesAbsolutePath == '') and (UserFilesAbsolutePath + 'file/') or ''
QuickUploadPath['File'] = FileTypesPath['File']
QuickUploadAbsolutePath['File'] = FileTypesAbsolutePath['File']
AllowedExtensions['Image'] = ['bmp','gif','jpeg','jpg','png']
DeniedExtensions['Image'] = []
FileTypesPath['Image'] = UserFilesPath + 'image/'
FileTypesAbsolutePath['Image'] = (not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'image/' or ''
QuickUploadPath['Image'] = FileTypesPath['Image']
QuickUploadAbsolutePath['Image']= FileTypesAbsolutePath['Image']
AllowedExtensions['Flash'] = ['swf','flv']
DeniedExtensions['Flash'] = []
FileTypesPath['Flash'] = UserFilesPath + 'flash/'
FileTypesAbsolutePath['Flash'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'flash/' or ''
QuickUploadPath['Flash'] = FileTypesPath['Flash']
QuickUploadAbsolutePath['Flash']= FileTypesAbsolutePath['Flash']
AllowedExtensions['Media'] = ['aiff','asf','avi','bmp','fla', 'flv','gif','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','png','qt','ram','rm','rmi','rmvb','swf','tif','tiff','wav','wma','wmv']
DeniedExtensions['Media'] = []
FileTypesPath['Media'] = UserFilesPath + 'media/'
FileTypesAbsolutePath['Media'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'media/' or ''
QuickUploadPath['Media'] = FileTypesPath['Media']
QuickUploadAbsolutePath['Media']= FileTypesAbsolutePath['Media']

View file

@ -0,0 +1,118 @@
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2007 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python (CGI and WSGI).
See config.py for configuration settings
"""
import os
from fckutil import *
from fckcommands import * # default command's implementation
from fckoutput import * # base http, xml and html output mixins
from fckconnector import FCKeditorConnectorBase # import base connector
import config as Config
class FCKeditorConnector( FCKeditorConnectorBase,
GetFoldersCommandMixin,
GetFoldersAndFilesCommandMixin,
CreateFolderCommandMixin,
UploadFileCommandMixin,
BaseHttpMixin, BaseXmlMixin, BaseHtmlMixin ):
"The Standard connector class."
def doResponse(self):
"Main function. Process the request, set headers and return a string as response."
s = ""
# Check if this connector is disabled
if not(Config.Enabled):
return self.sendError(1, "This connector is disabled. Please check the connector configurations in \"editor/filemanager/connectors/py/config.py\" and try again.")
# Make sure we have valid inputs
for key in ("Command","Type","CurrentFolder"):
if not self.request.has_key (key):
return
# Get command, resource type and current folder
command = self.request.get("Command")
resourceType = self.request.get("Type")
currentFolder = getCurrentFolder(self.request.get("CurrentFolder"))
# Check for invalid paths
if currentFolder is None:
return self.sendError(102, "")
# Check if it is an allowed command
if ( not command in Config.ConfigAllowedCommands ):
return self.sendError( 1, 'The %s command isn\'t allowed' % command )
if ( not resourceType in Config.ConfigAllowedTypes ):
return self.sendError( 1, 'Invalid type specified' )
# Setup paths
if command == "QuickUpload":
self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType]
self.webUserFilesFolder = Config.QuickUploadPath[resourceType]
else:
self.userFilesFolder = Config.FileTypesAbsolutePath[resourceType]
self.webUserFilesFolder = Config.FileTypesPath[resourceType]
if not self.userFilesFolder: # no absolute path given (dangerous...)
self.userFilesFolder = mapServerPath(self.environ,
self.webUserFilesFolder)
# Ensure that the directory exists.
if not os.path.exists(self.userFilesFolder):
try:
self.createServerFoldercreateServerFolder( self.userFilesFolder )
except:
return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ")
# File upload doesn't have to return XML, so intercept here
if (command == "FileUpload"):
return self.uploadFile(resourceType, currentFolder)
# Create Url
url = combinePaths( self.webUserFilesFolder, currentFolder )
# Begin XML
s += self.createXmlHeader(command, resourceType, currentFolder, url)
# Execute the command
selector = {"GetFolders": self.getFolders,
"GetFoldersAndFiles": self.getFoldersAndFiles,
"CreateFolder": self.createFolder,
}
s += selector[command](resourceType, currentFolder)
s += self.createXmlFooter()
return s
# Running from command line (plain old CGI)
if __name__ == '__main__':
try:
# Create a Connector Instance
conn = FCKeditorConnector()
data = conn.doResponse()
for header in conn.headers:
print '%s: %s' % header
print
print data
except:
print "Content-Type: text/plain"
print
import cgi
cgi.print_exception()

View file

@ -0,0 +1,181 @@
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2007 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python (CGI and WSGI).
"""
import os
try: # Windows needs stdio set for binary mode for file upload to work.
import msvcrt
msvcrt.setmode (0, os.O_BINARY) # stdin = 0
msvcrt.setmode (1, os.O_BINARY) # stdout = 1
except ImportError:
pass
from fckutil import *
from fckoutput import *
import config as Config
class GetFoldersCommandMixin (object):
def getFolders(self, resourceType, currentFolder):
"""
Purpose: command to recieve a list of folders
"""
# Map the virtual path to our local server
serverPath = mapServerFolder(self.userFilesFolder,currentFolder)
s = """<Folders>""" # Open the folders node
for someObject in os.listdir(serverPath):
someObjectPath = mapServerFolder(serverPath, someObject)
if os.path.isdir(someObjectPath):
s += """<Folder name="%s" />""" % (
convertToXmlAttribute(someObject)
)
s += """</Folders>""" # Close the folders node
return s
class GetFoldersAndFilesCommandMixin (object):
def getFoldersAndFiles(self, resourceType, currentFolder):
"""
Purpose: command to recieve a list of folders and files
"""
# Map the virtual path to our local server
serverPath = mapServerFolder(self.userFilesFolder,currentFolder)
# Open the folders / files node
folders = """<Folders>"""
files = """<Files>"""
for someObject in os.listdir(serverPath):
someObjectPath = mapServerFolder(serverPath, someObject)
if os.path.isdir(someObjectPath):
folders += """<Folder name="%s" />""" % (
convertToXmlAttribute(someObject)
)
elif os.path.isfile(someObjectPath):
size = os.path.getsize(someObjectPath)
files += """<File name="%s" size="%s" />""" % (
convertToXmlAttribute(someObject),
os.path.getsize(someObjectPath)
)
# Close the folders / files node
folders += """</Folders>"""
files += """</Files>"""
return folders + files
class CreateFolderCommandMixin (object):
def createFolder(self, resourceType, currentFolder):
"""
Purpose: command to create a new folder
"""
errorNo = 0; errorMsg ='';
if self.request.has_key("NewFolderName"):
newFolder = self.request.get("NewFolderName", None)
newFolder = sanitizeFolderName (newFolder)
try:
newFolderPath = mapServerFolder(self.userFilesFolder, combinePaths(currentFolder, newFolder))
self.createServerFolder(newFolderPath)
except Exception, e:
errorMsg = str(e).decode('iso-8859-1').encode('utf-8') # warning with encodigns!!!
if hasattr(e,'errno'):
if e.errno==17: #file already exists
errorNo=0
elif e.errno==13: # permission denied
errorNo = 103
elif e.errno==36 or e.errno==2 or e.errno==22: # filename too long / no such file / invalid name
errorNo = 102
else:
errorNo = 110
else:
errorNo = 102
return self.sendErrorNode ( errorNo, errorMsg )
def createServerFolder(self, folderPath):
"Purpose: physically creates a folder on the server"
# No need to check if the parent exists, just create all hierachy
oldumask = os.umask(0)
os.makedirs(folderPath,mode=0755)
os.umask( oldumask )
class UploadFileCommandMixin (object):
def uploadFile(self, resourceType, currentFolder):
"""
Purpose: command to upload files to server (same as FileUpload)
"""
errorNo = 0
if self.request.has_key("NewFile"):
# newFile has all the contents we need
newFile = self.request.get("NewFile", "")
# Get the file name
newFileName = newFile.filename
newFileName = sanitizeFileName( newFileName )
newFileNameOnly = removeExtension(newFileName)
newFileExtension = getExtension(newFileName).lower()
allowedExtensions = Config.AllowedExtensions[resourceType]
deniedExtensions = Config.DeniedExtensions[resourceType]
if (allowedExtensions):
# Check for allowed
isAllowed = False
if (newFileExtension in allowedExtensions):
isAllowed = True
elif (deniedExtensions):
# Check for denied
isAllowed = True
if (newFileExtension in deniedExtensions):
isAllowed = False
else:
# No extension limitations
isAllowed = True
if (isAllowed):
# Upload to operating system
# Map the virtual path to the local server path
currentFolderPath = mapServerFolder(self.userFilesFolder, currentFolder)
i = 0
while (True):
newFilePath = os.path.join (currentFolderPath,newFileName)
if os.path.exists(newFilePath):
i += 1
newFileName = "%s(%04d).%s" % (
newFileNameOnly, i, newFileExtension
)
errorNo= 201 # file renamed
else:
# Read file contents and write to the desired path (similar to php's move_uploaded_file)
fout = file(newFilePath, 'wb')
while (True):
chunk = newFile.file.read(100000)
if not chunk: break
fout.write (chunk)
fout.close()
if os.path.exists ( newFilePath ):
oldumask = os.umask(0)
os.chmod( newFilePath, 0755 )
os.umask( oldumask )
newFileUrl = self.webUserFilesFolder + currentFolder + newFileName
return self.sendUploadResults( errorNo , newFileUrl, newFileName )
else:
return self.sendUploadResults( errorNo = 203, customMsg = "Extension not allowed" )
else:
return self.sendUploadResults( errorNo = 202, customMsg = "No File" )

View file

@ -0,0 +1,90 @@
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2007 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Base Connector for Python (CGI and WSGI).
See config.py for configuration settings
"""
import cgi, os
from fckutil import *
from fckcommands import * # default command's implementation
from fckoutput import * # base http, xml and html output mixins
import config as Config
class FCKeditorConnectorBase( object ):
"The base connector class. Subclass it to extend functionality (see Zope example)"
def __init__(self, environ=None):
"Constructor: Here you should parse request fields, initialize variables, etc."
self.request = FCKeditorRequest(environ) # Parse request
self.headers = [] # Clean Headers
if environ:
self.environ = environ
else:
self.environ = os.environ
# local functions
def setHeader(self, key, value):
self.headers.append ((key, value))
return
class FCKeditorRequest(object):
"A wrapper around the request object"
def __init__(self, environ):
if environ: # WSGI
self.request = cgi.FieldStorage(fp=environ['wsgi.input'],
environ=environ,
keep_blank_values=1)
self.environ = environ
else: # plain old cgi
self.environ = os.environ
self.request = cgi.FieldStorage()
if 'REQUEST_METHOD' in self.environ and 'QUERY_STRING' in self.environ:
if self.environ['REQUEST_METHOD'].upper()=='POST':
# we are in a POST, but GET query_string exists
# cgi parses by default POST data, so parse GET QUERY_STRING too
self.get_request = cgi.FieldStorage(fp=None,
environ={
'REQUEST_METHOD':'GET',
'QUERY_STRING':self.environ['QUERY_STRING'],
},
)
else:
self.get_request={}
def has_key(self, key):
return self.request.has_key(key) or self.get_request.has_key(key)
def get(self, key, default=None):
if key in self.request.keys():
field = self.request[key]
elif key in self.get_request.keys():
field = self.get_request[key]
else:
return default
if hasattr(field,"filename") and field.filename: #file upload, do not convert return value
return field
else:
return field.value

View file

@ -0,0 +1,111 @@
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2007 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python (CGI and WSGI).
"""
from time import gmtime, strftime
import string
def escape(text, replace=string.replace):
"""
Converts the special characters '<', '>', and '&'.
RFC 1866 specifies that these characters be represented
in HTML as &lt; &gt; and &amp; respectively. In Python
1.5 we use the new string.replace() function for speed.
"""
text = replace(text, '&', '&amp;') # must be done 1st
text = replace(text, '<', '&lt;')
text = replace(text, '>', '&gt;')
text = replace(text, '"', '&quot;')
return text
def convertToXmlAttribute(value):
if (value is None):
value = ""
return escape(value)
class BaseHttpMixin(object):
def setHttpHeaders(self, content_type='text/xml'):
"Purpose: to prepare the headers for the xml to return"
# Prevent the browser from caching the result.
# Date in the past
self.setHeader('Expires','Mon, 26 Jul 1997 05:00:00 GMT')
# always modified
self.setHeader('Last-Modified',strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime()))
# HTTP/1.1
self.setHeader('Cache-Control','no-store, no-cache, must-revalidate')
self.setHeader('Cache-Control','post-check=0, pre-check=0')
# HTTP/1.0
self.setHeader('Pragma','no-cache')
# Set the response format.
self.setHeader( 'Content-Type', content_type + '; charset=utf-8' )
return
class BaseXmlMixin(object):
def createXmlHeader(self, command, resourceType, currentFolder, url):
"Purpose: returns the xml header"
self.setHttpHeaders()
# Create the XML document header
s = """<?xml version="1.0" encoding="utf-8" ?>"""
# Create the main connector node
s += """<Connector command="%s" resourceType="%s">""" % (
command,
resourceType
)
# Add the current folder node
s += """<CurrentFolder path="%s" url="%s" />""" % (
convertToXmlAttribute(currentFolder),
convertToXmlAttribute(url),
)
return s
def createXmlFooter(self):
"Purpose: returns the xml footer"
return """</Connector>"""
def sendError(self, number, text):
"Purpose: in the event of an error, return an xml based error"
self.setHttpHeaders()
return ("""<?xml version="1.0" encoding="utf-8" ?>""" +
"""<Connector>""" +
self.sendErrorNode (number, text) +
"""</Connector>""" )
def sendErrorNode(self, number, text):
return """<Error number="%s" text="%s" />""" % (number, convertToXmlAttribute(text))
class BaseHtmlMixin(object):
def sendUploadResults( self, errorNo = 0, fileUrl = '', fileName = '', customMsg = '' ):
self.setHttpHeaders("text/html")
"This is the function that sends the results of the uploading process"
return """<script type="text/javascript">
window.parent.OnUploadCompleted(%(errorNumber)s,"%(fileUrl)s","%(fileName)s","%(customMsg)s");
</script>""" % {
'errorNumber': errorNo,
'fileUrl': fileUrl.replace ('"', '\\"'),
'fileName': fileName.replace ( '"', '\\"' ) ,
'customMsg': customMsg.replace ( '"', '\\"' ),
}

View file

@ -0,0 +1,127 @@
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2007 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Utility functions for the File Manager Connector for Python
"""
import string, re
import os
import config as Config
# Generic manipulation functions
def removeExtension(fileName):
index = fileName.rindex(".")
newFileName = fileName[0:index]
return newFileName
def getExtension(fileName):
index = fileName.rindex(".") + 1
fileExtension = fileName[index:]
return fileExtension
def removeFromStart(string, char):
return string.lstrip(char)
def removeFromEnd(string, char):
return string.rstrip(char)
# Path functions
def combinePaths( basePath, folder ):
return removeFromEnd( basePath, '/' ) + '/' + removeFromStart( folder, '/' )
def getFileName(filename):
" Purpose: helper function to extrapolate the filename "
for splitChar in ["/", "\\"]:
array = filename.split(splitChar)
if (len(array) > 1):
filename = array[-1]
return filename
def sanitizeFolderName( newFolderName ):
"Do a cleanup of the folder name to avoid possible problems"
# Remove . \ / | : ? *
return re.sub( '\\.|\\\\|\\/|\\||\\:|\\?|\\*', '_', newFolderName )
def sanitizeFileName( newFileName ):
"Do a cleanup of the file name to avoid possible problems"
# Replace dots in the name with underscores (only one dot can be there... security issue).
if ( Config.ForceSingleExtension ): # remove dots
newFileName = re.sub ( '/\\.(?![^.]*$)/', '_', newFileName ) ;
newFileName = newFileName.replace('\\','/') # convert windows to unix path
newFileName = os.path.basename (newFileName) # strip directories
# Remove \ / | : ? *
return re.sub ( '/\\\\|\\/|\\||\\:|\\?|\\*/', '_', newFileName )
def getCurrentFolder(currentFolder):
if not currentFolder:
currentFolder = '/'
# Check the current folder syntax (must begin and end with a slash).
if (currentFolder[-1] <> "/"):
currentFolder += "/"
if (currentFolder[0] <> "/"):
currentFolder = "/" + currentFolder
# Ensure the folder path has no double-slashes
while '//' in currentFolder:
currentFolder = currentFolder.replace('//','/')
# Check for invalid folder paths (..)
if '..' in currentFolder:
return None
return currentFolder
def mapServerPath( environ, url):
" Emulate the asp Server.mapPath function. Given an url path return the physical directory that it corresponds to "
# This isn't correct but for the moment there's no other solution
# If this script is under a virtual directory or symlink it will detect the problem and stop
return combinePaths( getRootPath(environ), url )
def mapServerFolder(resourceTypePath, folderPath):
return combinePaths ( resourceTypePath , folderPath )
def getRootPath(environ):
"Purpose: returns the root path on the server"
# WARNING: this may not be thread safe, and doesn't work w/ VirtualServer/mod_python
# Use Config.UserFilesAbsolutePath instead
if environ.has_key('DOCUMENT_ROOT'):
return environ['DOCUMENT_ROOT']
else:
realPath = os.path.realpath( './' )
selfPath = environ['SCRIPT_FILENAME']
selfPath = selfPath [ : selfPath.rfind( '/' ) ]
selfPath = selfPath.replace( '/', os.path.sep)
position = realPath.find(selfPath)
# This can check only that this script isn't run from a virtual dir
# But it avoids the problems that arise if it isn't checked
raise realPath
if ( position < 0 or position <> len(realPath) - len(selfPath) or realPath[ : position ]==''):
raise Exception('Sorry, can\'t map "UserFilesPath" to a physical path. You must set the "UserFilesAbsolutePath" value in "editor/filemanager/connectors/py/config.py".')
return realPath[ : position ]

View file

@ -0,0 +1,23 @@
# replace the name of this file to .htaccess (if using apache),
# and set the proper options and paths according your enviroment
Allow from all
# If using mod_python uncomment this:
PythonPath "[r'C:\Archivos de programa\Apache Software Foundation\Apache2.2\htdocs\fckeditor\editor\filemanager\connectors\py'] + sys.path"
# Recomended: WSGI application running with mod_python and modpython_gateway
SetHandler python-program
PythonHandler modpython_gateway::handler
PythonOption wsgi.application wsgi::App
# Emulated CGI with mod_python and cgihandler
#AddHandler mod_python .py
#PythonHandler mod_python.cgihandler
# Plain old CGI
#Options +ExecCGI
#AddHandler cgi-script py

View file

@ -0,0 +1,88 @@
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2007 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
This is the "File Uploader" for Python
"""
import os
from fckutil import *
from fckcommands import * # default command's implementation
from fckconnector import FCKeditorConnectorBase # import base connector
import config as Config
class FCKeditorQuickUpload( FCKeditorConnectorBase,
UploadFileCommandMixin,
BaseHttpMixin, BaseHtmlMixin):
def doResponse(self):
"Main function. Process the request, set headers and return a string as response."
# Check if this connector is disabled
if not(Config.Enabled):
return self.sendUploadResults(1, "This file uploader is disabled. Please check the \"editor/filemanager/connectors/py/config.py\"")
command = 'QuickUpload'
# The file type (from the QueryString, by default 'File').
resourceType = self.request.get('Type','File')
currentFolder = getCurrentFolder(self.request.get("CurrentFolder",""))
# Check for invalid paths
if currentFolder is None:
return self.sendUploadResults(102, '', '', "")
# Check if it is an allowed command
if ( not command in Config.ConfigAllowedCommands ):
return self.sendUploadResults( 1, '', '', 'The %s command isn\'t allowed' % command )
if ( not resourceType in Config.ConfigAllowedTypes ):
return self.sendUploadResults( 1, '', '', 'Invalid type specified' )
# Setup paths
self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType]
self.webUserFilesFolder = Config.QuickUploadPath[resourceType]
if not self.userFilesFolder: # no absolute path given (dangerous...)
self.userFilesFolder = mapServerPath(self.environ,
self.webUserFilesFolder)
# Ensure that the directory exists.
if not os.path.exists(self.userFilesFolder):
try:
self.createServerFoldercreateServerFolder( self.userFilesFolder )
except:
return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ")
# File upload doesn't have to return XML, so intercept here
return self.uploadFile(resourceType, currentFolder)
# Running from command line (plain old CGI)
if __name__ == '__main__':
try:
# Create a Connector Instance
conn = FCKeditorQuickUpload()
data = conn.doResponse()
for header in conn.headers:
if not header is None:
print '%s: %s' % header
print
print data
except:
print "Content-Type: text/plain"
print
import cgi
cgi.print_exception()

View file

@ -0,0 +1,58 @@
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2007 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector/QuickUpload for Python (WSGI wrapper).
See config.py for configuration settings
"""
from connector import FCKeditorConnector
from upload import FCKeditorQuickUpload
import cgitb
from cStringIO import StringIO
# Running from WSGI capable server (recomended)
def App(environ, start_response):
"WSGI entry point. Run the connector"
if environ['SCRIPT_NAME'].endswith("connector.py"):
conn = FCKeditorConnector(environ)
elif environ['SCRIPT_NAME'].endswith("upload.py"):
conn = FCKeditorQuickUpload(environ)
else:
start_response ("200 Ok", [('Content-Type','text/html')])
yield "Unknown page requested: "
yield environ['SCRIPT_NAME']
return
try:
# run the connector
data = conn.doResponse()
# Start WSGI response:
start_response ("200 Ok", conn.headers)
# Send response text
yield data
except:
start_response("500 Internal Server Error",[("Content-type","text/html")])
file = StringIO()
cgitb.Hook(file = file).handle()
yield file.getvalue()

View file

@ -0,0 +1,189 @@
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2007 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python and Zope.
This code was not tested at all.
It just was ported from pre 2.5 release, so for further reference see
\editor\filemanager\browser\default\connectors\py\connector.py in previous
releases.
"""
from fckutil import *
from connector import *
import config as Config
class FCKeditorConnectorZope(FCKeditorConnector):
"""
Zope versiof FCKeditorConnector
"""
# Allow access (Zope)
__allow_access_to_unprotected_subobjects__ = 1
def __init__(self, context=None):
"""
Constructor
"""
FCKeditorConnector.__init__(self, environ=None) # call superclass constructor
# Instance Attributes
self.context = context
self.request = FCKeditorRequest(context)
def getZopeRootContext(self):
if self.zopeRootContext is None:
self.zopeRootContext = self.context.getPhysicalRoot()
return self.zopeRootContext
def getZopeUploadContext(self):
if self.zopeUploadContext is None:
folderNames = self.userFilesFolder.split("/")
c = self.getZopeRootContext()
for folderName in folderNames:
if (folderName <> ""):
c = c[folderName]
self.zopeUploadContext = c
return self.zopeUploadContext
def setHeader(self, key, value):
self.context.REQUEST.RESPONSE.setHeader(key, value)
def getFolders(self, resourceType, currentFolder):
# Open the folders node
s = ""
s += """<Folders>"""
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
for (name, o) in zopeFolder.objectItems(["Folder"]):
s += """<Folder name="%s" />""" % (
convertToXmlAttribute(name)
)
# Close the folders node
s += """</Folders>"""
return s
def getZopeFoldersAndFiles(self, resourceType, currentFolder):
folders = self.getZopeFolders(resourceType, currentFolder)
files = self.getZopeFiles(resourceType, currentFolder)
s = folders + files
return s
def getZopeFiles(self, resourceType, currentFolder):
# Open the files node
s = ""
s += """<Files>"""
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
for (name, o) in zopeFolder.objectItems(["File","Image"]):
s += """<File name="%s" size="%s" />""" % (
convertToXmlAttribute(name),
((o.get_size() / 1024) + 1)
)
# Close the files node
s += """</Files>"""
return s
def findZopeFolder(self, resourceType, folderName):
# returns the context of the resource / folder
zopeFolder = self.getZopeUploadContext()
folderName = self.removeFromStart(folderName, "/")
folderName = self.removeFromEnd(folderName, "/")
if (resourceType <> ""):
try:
zopeFolder = zopeFolder[resourceType]
except:
zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=resourceType, title=resourceType)
zopeFolder = zopeFolder[resourceType]
if (folderName <> ""):
folderNames = folderName.split("/")
for folderName in folderNames:
zopeFolder = zopeFolder[folderName]
return zopeFolder
def createFolder(self, resourceType, currentFolder):
# Find out where we are
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
errorNo = 0
errorMsg = ""
if self.request.has_key("NewFolderName"):
newFolder = self.request.get("NewFolderName", None)
zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=newFolder, title=newFolder)
else:
errorNo = 102
return self.sendErrorNode ( errorNo, errorMsg )
def uploadFile(self, resourceType, currentFolder, count=None):
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
file = self.request.get("NewFile", None)
fileName = self.getFileName(file.filename)
fileNameOnly = self.removeExtension(fileName)
fileExtension = self.getExtension(fileName).lower()
if (count):
nid = "%s.%s.%s" % (fileNameOnly, count, fileExtension)
else:
nid = fileName
title = nid
try:
zopeFolder.manage_addProduct['OFSP'].manage_addFile(
id=nid,
title=title,
file=file.read()
)
except:
if (count):
count += 1
else:
count = 1
return self.zopeFileUpload(resourceType, currentFolder, count)
return self.sendUploadResults( 0 )
class FCKeditorRequest(object):
"A wrapper around the request object"
def __init__(self, context=None):
r = context.REQUEST
self.request = r
def has_key(self, key):
return self.request.has_key(key)
def get(self, key, default=None):
return self.request.get(key, default)
"""
Running from zope, you will need to modify this connector.
If you have uploaded the FCKeditor into Zope (like me), you need to
move this connector out of Zope, and replace the "connector" with an
alias as below. The key to it is to pass the Zope context in, as
we then have a like to the Zope context.
## Script (Python) "connector.py"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=*args, **kws
##title=ALIAS
##
import Products.zope as connector
return connector.FCKeditorConnectorZope(context=context).doResponse()
"""

View file

@ -0,0 +1,177 @@
<!--
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2007 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Test page for the File Browser connectors.
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>FCKeditor - Connectors Tests</title>
<script type="text/javascript">
function BuildBaseUrl( command )
{
var sUrl =
document.getElementById('cmbConnector').value +
'?Command=' + command +
'&Type=' + document.getElementById('cmbType').value +
'&CurrentFolder=' + encodeURIComponent(document.getElementById('txtFolder').value) ;
return sUrl ;
}
function SetFrameUrl( url )
{
document.getElementById('eRunningFrame').src = url ;
document.getElementById('eUrl').innerHTML = url ;
}
function GetFolders()
{
SetFrameUrl( BuildBaseUrl( 'GetFolders' ) ) ;
return false ;
}
function GetFoldersAndFiles()
{
SetFrameUrl( BuildBaseUrl( 'GetFoldersAndFiles' ) ) ;
return false ;
}
function CreateFolder()
{
var sFolder = prompt( 'Type the folder name:', 'Test Folder' ) ;
if ( ! sFolder )
return false ;
var sUrl = BuildBaseUrl( 'CreateFolder' ) ;
sUrl += '&NewFolderName=' + encodeURIComponent( sFolder ) ;
SetFrameUrl( sUrl ) ;
return false ;
}
function OnUploadCompleted( errorNumber, fileName )
{
switch ( errorNumber )
{
case 0 :
alert( 'File uploaded with no errors' ) ;
break ;
case 201 :
GetFoldersAndFiles() ;
alert( 'A file with the same name is already available. The uploaded file has been renamed to "' + fileName + '"' ) ;
break ;
case 202 :
alert( 'Invalid file' ) ;
break ;
default :
alert( 'Error on file upload. Error number: ' + errorNumber ) ;
break ;
}
}
this.frames.frmUpload = this ;
function SetAction()
{
var sUrl = BuildBaseUrl( 'FileUpload' ) ;
document.getElementById('eUrl').innerHTML = sUrl ;
document.getElementById('frmUpload').action = sUrl ;
}
</script>
</head>
<body>
<table height="100%" cellspacing="0" cellpadding="0" width="100%" border="0">
<tr>
<td>
<table cellspacing="0" cellpadding="0" border="0">
<tr>
<td>
Connector:<br />
<select id="cmbConnector" name="cmbConnector">
<option value="asp/connector.asp" selected="selected">ASP</option>
<option value="aspx/connector.aspx">ASP.Net</option>
<option value="cfm/connector.cfm">ColdFusion</option>
<option value="lasso/connector.lasso">Lasso</option>
<option value="perl/connector.cgi">Perl</option>
<option value="php/connector.php">PHP</option>
<option value="py/connector.py">Python</option>
</select>
</td>
<td>
&nbsp;&nbsp;&nbsp;</td>
<td>
Current Folder<br />
<input id="txtFolder" type="text" value="/" name="txtFolder" /></td>
<td>
&nbsp;&nbsp;&nbsp;</td>
<td>
Resource Type<br />
<select id="cmbType" name="cmbType">
<option value="File" selected="selected">File</option>
<option value="Image">Image</option>
<option value="Flash">Flash</option>
<option value="Media">Media</option>
<option value="Invalid">Invalid Type (for testing)</option>
</select>
</td>
</tr>
</table>
<br />
<table cellspacing="0" cellpadding="0" border="0">
<tr>
<td valign="top">
<a href="#" onclick="GetFolders();">Get Folders</a></td>
<td>
&nbsp;&nbsp;&nbsp;</td>
<td valign="top">
<a href="#" onclick="GetFoldersAndFiles();">Get Folders and Files</a></td>
<td>
&nbsp;&nbsp;&nbsp;</td>
<td valign="top">
<a href="#" onclick="CreateFolder();">Create Folder</a></td>
<td>
&nbsp;&nbsp;&nbsp;</td>
<td valign="top">
<form id="frmUpload" action="" target="eRunningFrame" method="post" enctype="multipart/form-data">
File Upload<br />
<input id="txtFileUpload" type="file" name="NewFile" />
<input type="submit" value="Upload" onclick="SetAction();" />
</form>
</td>
</tr>
</table>
<br />
URL: <span id="eUrl"></span>
</td>
</tr>
<tr>
<td height="100%" valign="top">
<iframe id="eRunningFrame" src="javascript:void(0)" name="eRunningFrame" width="100%"
height="100%"></iframe>
</td>
</tr>
</table>
</body>
</html>

View file

@ -0,0 +1,149 @@
<!--
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2007 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Test page for the "File Uploaders".
-->
<html>
<head>
<title>FCKeditor - Uploaders Tests</title>
<script type="text/javascript">
function SendFile()
{
var sUploaderUrl = cmbUploaderUrl.value ;
if ( sUploaderUrl.length == 0 )
sUploaderUrl = txtCustomUrl.value ;
if ( sUploaderUrl.length == 0 )
{
alert( 'Please provide your custom URL or select a default one' ) ;
return ;
}
eURL.innerHTML = sUploaderUrl ;
txtUrl.value = '' ;
frmUpload.action = sUploaderUrl;
if (document.getElementById('cmbType').value) {
frmUpload.action = frmUpload.action + '?Type='+document.getElementById('cmbType').value;
}
frmUpload.submit() ;
}
function OnUploadCompleted( errorNumber, fileUrl, fileName, customMsg )
{
switch ( errorNumber )
{
case 0 : // No errors
txtUrl.value = fileUrl ;
alert( 'File uploaded with no errors' ) ;
break ;
case 1 : // Custom error
alert( customMsg ) ;
break ;
case 10 : // Custom warning
txtUrl.value = fileUrl ;
alert( customMsg ) ;
break ;
case 201 :
txtUrl.value = fileUrl ;
alert( 'A file with the same name is already available. The uploaded file has been renamed to "' + fileName + '"' ) ;
break ;
case 202 :
alert( 'Invalid file' ) ;
break ;
case 203 :
alert( "Security error. You probably don't have enough permissions to upload. Please check your server." ) ;
break ;
default :
alert( 'Error on file upload. Error number: ' + errorNumber ) ;
break ;
}
}
</script>
</head>
<body>
<table cellSpacing="0" cellPadding="0" width="100%" border="0" height="100%">
<tr>
<td>
<table cellSpacing="0" cellPadding="0" width="100%" border="0">
<tr>
<td nowrap>
Select the "File Uploader" to use:<br>
<select id="cmbUploaderUrl">
<option selected value="asp/upload.asp">ASP</option>
<option value="aspx/upload.aspx">ASP.Net</option>
<option value="cfm/upload.cfm">ColdFusion</option>
<option value="lasso/upload.lasso">Lasso</option>
<option value="perl/upload.cgi">Perl</option>
<option value="php/upload.php">PHP</option>
<option value="py/upload.py">Python</option>
<option value="">(Custom)</option>
</select>
</td>
<td>
Resource Type<br />
<select id="cmbType" name="cmbType">
<option value="">None</option>
<option value="File">File</option>
<option value="Image">Image</option>
<option value="Flash">Flash</option>
<option value="Media">Media</option>
<option value="Invalid">Invalid Type (for testing)</option>
</select>
</td>
<td nowrap>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
<td width="100%">
Custom Uploader URL:<BR>
<input id="txtCustomUrl" style="WIDTH: 100%; BACKGROUND-COLOR: #dcdcdc" disabled type="text">
</td>
</tr>
</table>
<br>
<table cellSpacing="0" cellPadding="0" width="100%" border="0">
<tr>
<td noWrap>
<form id="frmUpload" target="UploadWindow" enctype="multipart/form-data" action="" method="post">
Upload a new file:<br>
<input type="file" name="NewFile"><br>
<input type="button" value="Send it to the Server" onclick="SendFile();">
</form>
</td>
<td style="WIDTH: 16px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
<td vAlign="top" width="100%">
Uploaded File URL:<br>
<INPUT id="txtUrl" style="WIDTH: 100%" readonly type="text">
</td>
</tr>
</table>
<br>
Post URL: <span id="eURL">&nbsp;</span>
</td>
</tr>
<tr>
<td height="100%">
<iframe name="UploadWindow" width="100%" height="100%" src="javascript:void(0)"></iframe>
</td>
</tr>
</table>
</body>
</html>