code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <!-- * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Form dialog window. --> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta content="noindex, nofollow" name="robots" /> <script src="common/fck_dialog_common.js" type="text/javascript"></script> <script type="text/javascript"> var dialog = window.parent ; var oEditor = dialog.InnerDialogLoaded() ; var FCK = oEditor.FCK ; var FCKLang = oEditor.FCKLang ; var FCKBrowserInfo = oEditor.FCKBrowserInfo ; var FCKStyles = oEditor.FCKStyles ; var FCKElementPath = oEditor.FCKElementPath ; var FCKDomRange = oEditor.FCKDomRange ; var FCKDomTools = oEditor.FCKDomTools ; var FCKDomRangeIterator = oEditor.FCKDomRangeIterator ; var FCKListsLib = oEditor.FCKListsLib ; var AlwaysCreate = dialog.Args().CustomValue ; String.prototype.IEquals = function() { var thisUpper = this.toUpperCase() ; var aArgs = arguments ; // The arguments could also be a single array. if ( aArgs.length == 1 && aArgs[0].pop ) aArgs = aArgs[0] ; for ( var i = 0 ; i < aArgs.length ; i++ ) { if ( thisUpper == aArgs[i].toUpperCase() ) return true ; } return false ; } var CurrentContainers = [] ; if ( !AlwaysCreate ) { dialog.Selection.EnsureSelection() ; CurrentContainers = FCKDomTools.GetSelectedDivContainers() ; } // Add some tabs dialog.AddTab( 'General', FCKLang.DlgDivGeneralTab ); dialog.AddTab( 'Advanced', FCKLang.DlgDivAdvancedTab ) ; function AddStyleOption( styleName ) { var el = GetE( 'selStyle' ) ; var opt = document.createElement( 'option' ) ; opt.text = opt.value = styleName ; if ( FCKBrowserInfo.IsIE ) el.add( opt ) ; else el.add( opt, null ) ; } function OnDialogTabChange( tabCode ) { ShowE( 'divGeneral', tabCode == 'General' ) ; ShowE( 'divAdvanced', tabCode == 'Advanced' ) ; dialog.SetAutoSize( true ) ; } function GetNearestAncestorDirection( node ) { var dir = 'ltr' ; // HTML default. while ( ( node = node.parentNode ) ) { if ( node.dir ) dir = node.dir ; } return dir ; } window.onload = function() { // First of all, translate the dialog box texts oEditor.FCKLanguageManager.TranslatePage(document) ; dialog.SetOkButton( true ) ; dialog.SetAutoSize( true ) ; // Popuplate the style menu var styles = FCKStyles.GetStyles() ; var selectableStyles = {} ; for ( var i in styles ) { if ( ! /^_FCK_/.test( i ) && styles[i].Element == 'div' ) selectableStyles[i] = styles[i] ; } if ( CurrentContainers.length <= 1 ) { var target = CurrentContainers[0] ; var match = null ; for ( var i in selectableStyles ) { if ( target && styles[i].CheckElementRemovable( target, true ) ) match = i ; } if ( !match ) AddStyleOption( "" ) ; for ( var i in selectableStyles ) AddStyleOption( i ) ; if ( match ) GetE( 'selStyle' ).value = match ; // Set the value for other inputs if ( target ) { GetE( 'txtClass' ).value = target.className ; GetE( 'txtId' ).value = target.id ; GetE( 'txtLang' ).value = target.lang ; GetE( 'txtInlineStyle').value = target.style.cssText ; GetE( 'txtTitle' ).value = target.title ; GetE( 'selLangDir').value = target.dir || GetNearestAncestorDirection( target ) ; } } else { GetE( 'txtId' ).disabled = true ; AddStyleOption( "" ) ; for ( var i in selectableStyles ) AddStyleOption( i ) ; } } function CreateDiv() { var newBlocks = [] ; var range = new FCKDomRange( FCK.EditorWindow ) ; range.MoveToSelection() ; var bookmark = range.CreateBookmark() ; // Kludge for #1592: if the bookmark nodes are in the beginning of // $tagName, then move them to the nearest block element in the // $tagName. if ( FCKBrowserInfo.IsIE ) { var bStart = range.GetBookmarkNode( bookmark, true ) ; var bEnd = range.GetBookmarkNode( bookmark, false ) ; var cursor ; if ( bStart && bStart.parentNode.nodeName.IEquals( 'div' ) && !bStart.previousSibling ) { cursor = bStart ; while ( ( cursor = cursor.nextSibling ) ) { if ( FCKListsLib.BlockElements[ cursor.nodeName.toLowerCase() ] ) FCKDomTools.MoveNode( bStart, cursor, true ) ; } } if ( bEnd && bEnd.parentNode.nodeName.IEquals( 'div' ) && !bEnd.previousSibling ) { cursor = bEnd ; while ( ( cursor = cursor.nextSibling ) ) { if ( FCKListsLib.BlockElements[ cursor.nodeName.toLowerCase() ] ) { if ( cursor.firstChild == bStart ) FCKDomTools.InsertAfterNode( bStart, bEnd ) ; else FCKDomTools.MoveNode( bEnd, cursor, true ) ; } } } } var iterator = new FCKDomRangeIterator( range ) ; var block ; var paragraphs = [] ; while ( ( block = iterator.GetNextParagraph() ) ) paragraphs.push( block ) ; // Make sure all paragraphs have the same parent. var commonParent = paragraphs[0].parentNode ; var tmp = [] ; for ( var i = 0 ; i < paragraphs.length ; i++ ) { block = paragraphs[i] ; commonParent = FCKDomTools.GetCommonParents( block.parentNode, commonParent ).pop() ; } // The common parent must not be the following tags: table, tbody, tr, ol, ul. while ( commonParent.nodeName.IEquals( 'table', 'tbody', 'tr', 'ol', 'ul' ) ) commonParent = commonParent.parentNode ; // Reconstruct the block list to be processed such that all resulting blocks // satisfy parentNode == commonParent. var lastBlock = null ; while ( paragraphs.length > 0 ) { block = paragraphs.shift() ; while ( block.parentNode != commonParent ) block = block.parentNode ; if ( block != lastBlock ) tmp.push( block ) ; lastBlock = block ; } paragraphs = tmp ; // Split the paragraphs into groups depending on their BlockLimit element. var groups = [] ; var lastBlockLimit = null ; for ( var i = 0 ; i < paragraphs.length ; i++ ) { block = paragraphs[i] ; var elementPath = new FCKElementPath( block ) ; if ( elementPath.BlockLimit != lastBlockLimit ) { groups.push( [] ) ; lastBlockLimit = elementPath.BlockLimit ; } groups[groups.length - 1].push( block ) ; } // Create a DIV container for each group. for ( var i = 0 ; i < groups.length ; i++ ) { var divNode = FCK.EditorDocument.createElement( 'div' ) ; groups[i][0].parentNode.insertBefore( divNode, groups[i][0] ) ; for ( var j = 0 ; j < groups[i].length ; j++ ) FCKDomTools.MoveNode( groups[i][j], divNode ) ; newBlocks.push( divNode ) ; } range.MoveToBookmark( bookmark ) ; range.Select() ; FCK.Focus() ; FCK.Events.FireEvent( 'OnSelectionChange' ) ; return newBlocks ; } function Ok() { oEditor.FCKUndo.SaveUndoStep() ; if ( CurrentContainers.length < 1 ) CurrentContainers = CreateDiv(); var setValue = function( attrName, inputName ) { var val = GetE( inputName ).value ; for ( var i = 0 ; i < CurrentContainers.length ; i++ ) { if ( val == '' ) CurrentContainers[i].removeAttribute( attrName ) ; else CurrentContainers[i].setAttribute( attrName, val ) ; } } // Apply modifications to the DIV container according to dialog inputs. if ( CurrentContainers.length == 1 ) { setValue( 'class', 'txtClass' ) ; setValue( 'id', 'txtId' ) ; } setValue( 'lang', 'txtLang' ) ; if ( FCKBrowserInfo.IsIE ) { for ( var i = 0 ; i < CurrentContainers.length ; i++ ) CurrentContainers[i].style.cssText = GetE( 'txtInlineStyle' ).value ; } else setValue( 'style', 'txtInlineStyle' ) ; setValue( 'title', 'txtTitle' ) ; for ( var i = 0 ; i < CurrentContainers.length ; i++ ) { var dir = GetE( 'selLangDir' ).value ; var styleName = GetE( 'selStyle' ).value ; if ( GetNearestAncestorDirection( CurrentContainers[i] ) != dir ) CurrentContainers[i].dir = dir ; else CurrentContainers[i].removeAttribute( 'dir' ) ; if ( styleName ) FCKStyles.GetStyle( styleName ).ApplyToObject( CurrentContainers[i] ) ; } return true ; } </script> </head> <body style="overflow: hidden"> <div id="divGeneral"> <table cellspacing="0" cellpadding="0" width="100%" border="0"> <colgroup span="2"> <col width="49%" /> <col width="2%" /> <col width="49%" /> </colgroup> <tr> <td> <span fcklang="DlgDivStyle">Style</span><br /> <select id="selStyle" style="width: 100%;"> </select> </td> <td>&nbsp;</td> <td> <span fcklang="DlgGenClass">Stylesheet Classes</span><br /> <input id="txtClass" style="width: 100%" type="text" /> </td> </tr> </table> </div> <div id="divAdvanced" style="display: none"> <table cellspacing="0" cellpadding="0" width="100%" border="0"> <colgroup span="2"> <col width="49%" /> <col width="2%" /> <col width="49%" /> </colgroup> <tr> <td> <span fcklang="DlgGenId">Id</span><br /> <input style="width: 100%" type="text" id="txtId" /> </td> <td>&nbsp;</td> <td> <span fcklang="DlgGenLangCode">Language Code</span><br /> <input style="width: 100%" type="text" id="txtLang" /> </td> </tr> <tr> <td colspan="3">&nbsp;</td> </tr> <tr> <td colspan="3"> <span fcklang="DlgDivInlineStyle">Inline Style</span><br /> <input style="width: 100%" type="text" id="txtInlineStyle" /> </td> </tr> <tr> <td colspan="3">&nbsp;</td> </tr> <tr> <td colspan="3"> <span fcklang="DlgGenTitle">Advisory Title</span><br /> <input style="width: 100%" type="text" id="txtTitle" /> </td> </tr> <tr> <td>&nbsp;</td> </tr> <tr> <td> <span fcklang="DlgGenLangDir">Language Direction</span><br /> <select id="selLangDir"> <option fcklang="DlgGenLangDirLtr" value="ltr">Left to Right (LTR) <option fcklang="DlgGenLangDirRtl" value="rtl">Right to Left (RTL) </select> </td> </tr> </table> </div> </body> </html>
10npsite
trunk/guanli/system/fckeditor/editor/dialog/fck_div.html
HTML
asf20
10,792
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <!-- * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Spell Check dialog window. --> <html> <head> <title>Spell Check</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta content="noindex, nofollow" name="robots"> <script src="common/fck_dialog_common.js" type="text/javascript"></script> <script src="fck_spellerpages/spellerpages/spellChecker.js"></script> <script type="text/javascript"> var oEditor = window.parent.InnerDialogLoaded() ; var FCKLang = oEditor.FCKLang ; window.onload = function() { document.getElementById('txtHtml').value = oEditor.FCK.EditorDocument.body.innerHTML ; var oSpeller = new spellChecker( document.getElementById('txtHtml') ) ; oSpeller.spellCheckScript = oEditor.FCKConfig.SpellerPagesServerScript || 'server-scripts/spellchecker.php' ; oSpeller.OnFinished = oSpeller_OnFinished ; oSpeller.openChecker() ; } function OnSpellerControlsLoad( controlsWindow ) { // Translate the dialog box texts oEditor.FCKLanguageManager.TranslatePage( controlsWindow.document ) ; } function oSpeller_OnFinished( numberOCorrections ) { if ( numberOCorrections > 0 ) { oEditor.FCKUndo.SaveUndoStep() ; oEditor.FCK.EditorDocument.body.innerHTML = document.getElementById('txtHtml').value ; if ( oEditor.FCKBrowserInfo.IsIE ) oEditor.FCKSelection.Collapse( true ) ; } window.parent.Cancel() ; } </script> </head> <body style="OVERFLOW: hidden" scroll="no" style="padding:0px;"> <input type="hidden" id="txtHtml" value=""> <iframe id="frmSpell" src="javascript:void(0)" name="spellchecker" width="100%" height="100%" frameborder="0"></iframe> </body> </html>
10npsite
trunk/guanli/system/fckeditor/editor/dialog/fck_spellerpages.html
HTML
asf20
2,339
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <!-- * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Text field dialog window. --> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta content="noindex, nofollow" name="robots" /> <script src="common/fck_dialog_common.js" type="text/javascript"></script> <script type="text/javascript"> var dialog = window.parent ; var oEditor = dialog.InnerDialogLoaded() ; // Gets the document DOM var oDOM = oEditor.FCK.EditorDocument ; var oActiveEl = dialog.Selection.GetSelectedElement() ; window.onload = function() { // First of all, translate the dialog box texts oEditor.FCKLanguageManager.TranslatePage(document) ; if ( oActiveEl && oActiveEl.tagName == 'INPUT' && ( oActiveEl.type == 'text' || oActiveEl.type == 'password' ) ) { GetE('txtName').value = oActiveEl.name ; GetE('txtValue').value = oActiveEl.value ; GetE('txtSize').value = GetAttribute( oActiveEl, 'size' ) ; GetE('txtMax').value = GetAttribute( oActiveEl, 'maxLength' ) ; GetE('txtType').value = oActiveEl.type ; } else oActiveEl = null ; dialog.SetOkButton( true ) ; dialog.SetAutoSize( true ) ; SelectField( 'txtName' ) ; } function Ok() { if ( isNaN( GetE('txtMax').value ) || GetE('txtMax').value < 0 ) { alert( "Maximum characters must be a positive number." ) ; GetE('txtMax').focus() ; return false ; } else if( isNaN( GetE('txtSize').value ) || GetE('txtSize').value < 0 ) { alert( "Width must be a positive number." ) ; GetE('txtSize').focus() ; return false ; } oEditor.FCKUndo.SaveUndoStep() ; oActiveEl = CreateNamedElement( oEditor, oActiveEl, 'INPUT', {name: GetE('txtName').value, type: GetE('txtType').value } ) ; SetAttribute( oActiveEl, 'value' , GetE('txtValue').value ) ; SetAttribute( oActiveEl, 'size' , GetE('txtSize').value ) ; SetAttribute( oActiveEl, 'maxlength', GetE('txtMax').value ) ; return true ; } </script> </head> <body style="overflow: hidden"> <table width="100%" style="height: 100%"> <tr> <td align="center"> <table cellspacing="0" cellpadding="0" border="0"> <tr> <td> <span fcklang="DlgTextName">Name</span><br /> <input id="txtName" type="text" size="20" /> </td> <td> </td> <td> <span fcklang="DlgTextValue">Value</span><br /> <input id="txtValue" type="text" size="25" /> </td> </tr> <tr> <td> <span fcklang="DlgTextCharWidth">Character Width</span><br /> <input id="txtSize" type="text" size="5" /> </td> <td> </td> <td> <span fcklang="DlgTextMaxChars">Maximum Characters</span><br /> <input id="txtMax" type="text" size="5" /> </td> </tr> <tr> <td> <span fcklang="DlgTextType">Type</span><br /> <select id="txtType"> <option value="text" selected="selected" fcklang="DlgTextTypeText">Text</option> <option value="password" fcklang="DlgTextTypePass">Password</option> </select> </td> <td> &nbsp;</td> <td> </td> </tr> </table> </td> </tr> </table> </body> </html>
10npsite
trunk/guanli/system/fckeditor/editor/dialog/fck_textfield.html
HTML
asf20
3,935
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <!-- * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Smileys (emoticons) dialog window. --> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="robots" content="noindex, nofollow" /> <style type="text/css"> .Hand { cursor: pointer; cursor: hand; } </style> <script src="common/fck_dialog_common.js" type="text/javascript"></script> <script type="text/javascript"> var dialog = window.parent ; var oEditor = dialog.InnerDialogLoaded() ; window.onload = function () { // First of all, translate the dialog box texts oEditor.FCKLanguageManager.TranslatePage(document) ; dialog.SetAutoSize( true ) ; } function InsertSmiley( url ) { oEditor.FCKUndo.SaveUndoStep() ; var oImg = oEditor.FCK.InsertElement( 'img' ) ; oImg.src = url ; oImg.setAttribute( '_fcksavedurl', url ) ; // For long smileys list, it seams that IE continues loading the images in // the background when you quickly select one image. so, let's clear // everything before closing. document.body.innerHTML = '' ; dialog.Cancel() ; } function over(td) { td.className = 'LightBackground Hand' ; } function out(td) { td.className = 'DarkBackground Hand' ; } </script> </head> <body style="overflow: hidden"> <table cellpadding="2" cellspacing="2" align="center" border="0" width="100%" height="100%"> <script type="text/javascript"> var FCKConfig = oEditor.FCKConfig ; var sBasePath = FCKConfig.SmileyPath ; var aImages = FCKConfig.SmileyImages ; var iCols = FCKConfig.SmileyColumns ; var iColWidth = parseInt( 100 / iCols, 10 ) ; var i = 0 ; while (i < aImages.length) { document.write( '<tr>' ) ; for(var j = 0 ; j < iCols ; j++) { if (aImages[i]) { var sUrl = sBasePath + aImages[i] ; document.write( '<td width="' + iColWidth + '%" align="center" class="DarkBackground Hand" onclick="InsertSmiley(\'' + sUrl.replace(/'/g, "\\'" ) + '\')" onmouseover="over(this)" onmouseout="out(this)">' ) ; document.write( '<img src="' + sUrl + '" border="0" />' ) ; } else document.write( '<td width="' + iColWidth + '%" class="DarkBackground">&nbsp;' ) ; document.write( '<\/td>' ) ; i++ ; } document.write('<\/tr>') ; } </script> </table> </body> </html>
10npsite
trunk/guanli/system/fckeditor/editor/dialog/fck_smiley.html
HTML
asf20
3,020
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <!-- * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Text Area dialog window. --> <html> <head> <title>Text Area Properties</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta content="noindex, nofollow" name="robots"> <script src="common/fck_dialog_common.js" type="text/javascript"></script> <script type="text/javascript"> var dialog = window.parent ; var oEditor = dialog.InnerDialogLoaded() ; // Gets the document DOM var oDOM = oEditor.FCK.EditorDocument ; var oActiveEl = dialog.Selection.GetSelectedElement() ; window.onload = function() { // First of all, translate the dialog box texts oEditor.FCKLanguageManager.TranslatePage(document) ; if ( oActiveEl && oActiveEl.tagName == 'TEXTAREA' ) { GetE('txtName').value = oActiveEl.name ; GetE('txtCols').value = GetAttribute( oActiveEl, 'cols' ) ; GetE('txtRows').value = GetAttribute( oActiveEl, 'rows' ) ; } else oActiveEl = null ; dialog.SetOkButton( true ) ; dialog.SetAutoSize( true ) ; SelectField( 'txtName' ) ; } function Ok() { oEditor.FCKUndo.SaveUndoStep() ; oActiveEl = CreateNamedElement( oEditor, oActiveEl, 'TEXTAREA', {name: GetE('txtName').value} ) ; SetAttribute( oActiveEl, 'cols', GetE('txtCols').value ) ; SetAttribute( oActiveEl, 'rows', GetE('txtRows').value ) ; return true ; } </script> </head> <body style="overflow: hidden"> <table height="100%" width="100%"> <tr> <td align="center"> <table border="0" cellpadding="0" cellspacing="0" width="80%"> <tr> <td> <span fckLang="DlgTextareaName">Name</span><br> <input type="text" id="txtName" style="WIDTH: 100%"> <span fckLang="DlgTextareaCols">Collumns</span><br> <input id="txtCols" type="text" size="5"> <br> <span fckLang="DlgTextareaRows">Rows</span><br> <input id="txtRows" type="text" size="5"> </td> </tr> </table> </td> </tr> </table> </body> </html>
10npsite
trunk/guanli/system/fckeditor/editor/dialog/fck_textarea.html
HTML
asf20
2,697
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <!-- * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Color Selection dialog window. --> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="robots" content="noindex, nofollow" /> <style TYPE="text/css"> #ColorTable { cursor: pointer ; cursor: hand ; } #hicolor { height: 74px ; width: 74px ; border-width: 1px ; border-style: solid ; } #hicolortext { width: 75px ; text-align: right ; margin-bottom: 7px ; } #selhicolor { height: 20px ; width: 74px ; border-width: 1px ; border-style: solid ; } #selcolor { width: 75px ; height: 20px ; margin-top: 0px ; margin-bottom: 7px ; } #btnClear { width: 75px ; height: 22px ; margin-bottom: 6px ; } .ColorCell { height: 15px ; width: 15px ; } </style> <script src="common/fck_dialog_common.js" type="text/javascript"></script> <script type="text/javascript"> var oEditor = window.parent.InnerDialogLoaded() ; function OnLoad() { // First of all, translate the dialog box texts oEditor.FCKLanguageManager.TranslatePage(document) ; CreateColorTable() ; window.parent.SetOkButton( true ) ; window.parent.SetAutoSize( true ) ; } function CreateColorTable() { // Get the target table. var oTable = document.getElementById('ColorTable') ; // Create the base colors array. var aColors = ['00','33','66','99','cc','ff'] ; // This function combines two ranges of three values from the color array into a row. function AppendColorRow( rangeA, rangeB ) { for ( var i = rangeA ; i < rangeA + 3 ; i++ ) { var oRow = oTable.insertRow(-1) ; for ( var j = rangeB ; j < rangeB + 3 ; j++ ) { for ( var n = 0 ; n < 6 ; n++ ) { AppendColorCell( oRow, '#' + aColors[j] + aColors[n] + aColors[i] ) ; } } } } // This function create a single color cell in the color table. function AppendColorCell( targetRow, color ) { var oCell = targetRow.insertCell(-1) ; oCell.className = 'ColorCell' ; oCell.bgColor = color ; oCell.onmouseover = function() { document.getElementById('hicolor').style.backgroundColor = this.bgColor ; document.getElementById('hicolortext').innerHTML = this.bgColor ; } oCell.onclick = function() { document.getElementById('selhicolor').style.backgroundColor = this.bgColor ; document.getElementById('selcolor').value = this.bgColor ; } } AppendColorRow( 0, 0 ) ; AppendColorRow( 3, 0 ) ; AppendColorRow( 0, 3 ) ; AppendColorRow( 3, 3 ) ; // Create the last row. var oRow = oTable.insertRow(-1) ; // Create the gray scale colors cells. for ( var n = 0 ; n < 6 ; n++ ) { AppendColorCell( oRow, '#' + aColors[n] + aColors[n] + aColors[n] ) ; } // Fill the row with black cells. for ( var i = 0 ; i < 12 ; i++ ) { AppendColorCell( oRow, '#000000' ) ; } } function Clear() { document.getElementById('selhicolor').style.backgroundColor = '' ; document.getElementById('selcolor').value = '' ; } function ClearActual() { document.getElementById('hicolor').style.backgroundColor = '' ; document.getElementById('hicolortext').innerHTML = '&nbsp;' ; } function UpdateColor() { try { document.getElementById('selhicolor').style.backgroundColor = document.getElementById('selcolor').value ; } catch (e) { Clear() ; } } function Ok() { if ( typeof(window.parent.Args().CustomValue) == 'function' ) window.parent.Args().CustomValue( document.getElementById('selcolor').value ) ; return true ; } </script> </head> <body onload="OnLoad()" scroll="no" style="OVERFLOW: hidden"> <table cellpadding="0" cellspacing="0" border="0" width="100%" height="100%"> <tr> <td align="center" valign="middle"> <table border="0" cellspacing="5" cellpadding="0" width="100%"> <tr> <td valign="top" align="center" nowrap width="100%"> <table id="ColorTable" border="0" cellspacing="0" cellpadding="0" width="270" onmouseout="ClearActual();"> </table> </td> <td valign="top" align="left" nowrap> <span fckLang="DlgColorHighlight">Highlight</span> <div id="hicolor"></div> <div id="hicolortext">&nbsp;</div> <span fckLang="DlgColorSelected">Selected</span> <div id="selhicolor"></div> <input id="selcolor" type="text" maxlength="20" onchange="UpdateColor();"> <br> <input id="btnClear" type="button" fckLang="DlgColorBtnClear" value="Clear" onclick="Clear();" /> </td> </tr> </table> </td> </tr> </table> </body> </html>
10npsite
trunk/guanli/system/fckeditor/editor/dialog/fck_colorselector.html
HTML
asf20
5,289
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 CSS file used for interface details in some dialog * windows. */ /* ######### * WARNING * ######### * When changing this file, the minified version of it must be updated in the * fck_dialog_common.js file (see GetCommonDialogCss). */ .ImagePreviewArea { border: #000000 1px solid; overflow: auto; width: 100%; height: 170px; background-color: #ffffff; } .FlashPreviewArea { border: #000000 1px solid; padding: 5px; overflow: auto; width: 100%; height: 170px; background-color: #ffffff; } .BtnReset { float: left; background-position: center center; background-image: url(images/reset.gif); width: 16px; height: 16px; background-repeat: no-repeat; border: 1px none; font-size: 1px ; } .BtnLocked, .BtnUnlocked { float: left; background-position: center center; background-image: url(images/locked.gif); width: 16px; height: 16px; background-repeat: no-repeat; border: none 1px; font-size: 1px ; } .BtnUnlocked { background-image: url(images/unlocked.gif); } .BtnOver { border: outset 1px; cursor: pointer; cursor: hand; }
10npsite
trunk/guanli/system/fckeditor/editor/dialog/common/fck_dialog_common.css
CSS
asf20
1,773
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Useful functions used by almost all dialog window pages. * Dialogs should link to this file as the very first script on the page. */ // Automatically detect the correct document.domain (#123). (function() { var d = document.domain ; while ( true ) { // Test if we can access a parent property. try { var test = window.parent.document.domain ; break ; } catch( e ) {} // Remove a domain part: www.mytest.example.com => mytest.example.com => example.com ... d = d.replace( /.*?(?:\.|$)/, '' ) ; if ( d.length == 0 ) break ; // It was not able to detect the domain. try { document.domain = d ; } catch (e) { break ; } } })() ; // Attention: FCKConfig must be available in the page. function GetCommonDialogCss( prefix ) { // CSS minified by http://iceyboard.no-ip.org/projects/css_compressor (see _dev/css_compression.txt). return FCKConfig.BasePath + 'dialog/common/' + '|.ImagePreviewArea{border:#000 1px solid;overflow:auto;width:100%;height:170px;background-color:#fff}.FlashPreviewArea{border:#000 1px solid;padding:5px;overflow:auto;width:100%;height:170px;background-color:#fff}.BtnReset{float:left;background-position:center center;background-image:url(images/reset.gif);width:16px;height:16px;background-repeat:no-repeat;border:1px none;font-size:1px}.BtnLocked,.BtnUnlocked{float:left;background-position:center center;background-image:url(images/locked.gif);width:16px;height:16px;background-repeat:no-repeat;border:none 1px;font-size:1px}.BtnUnlocked{background-image:url(images/unlocked.gif)}.BtnOver{border:outset 1px;cursor:pointer;cursor:hand}' ; } // Gets a element by its Id. Used for shorter coding. function GetE( elementId ) { return document.getElementById( elementId ) ; } function ShowE( element, isVisible ) { if ( typeof( element ) == 'string' ) element = GetE( element ) ; element.style.display = isVisible ? '' : 'none' ; } function SetAttribute( element, attName, attValue ) { if ( attValue == null || attValue.length == 0 ) element.removeAttribute( attName, 0 ) ; // 0 : Case Insensitive else element.setAttribute( attName, attValue, 0 ) ; // 0 : Case Insensitive } function GetAttribute( element, attName, valueIfNull ) { var oAtt = element.attributes[attName] ; if ( oAtt == null || !oAtt.specified ) return valueIfNull ? valueIfNull : '' ; var oValue = element.getAttribute( attName, 2 ) ; if ( oValue == null ) oValue = oAtt.nodeValue ; return ( oValue == null ? valueIfNull : oValue ) ; } function SelectField( elementId ) { var element = GetE( elementId ) ; element.focus() ; // element.select may not be available for some fields (like <select>). if ( element.select ) element.select() ; } // Functions used by text fields to accept numbers only. var IsDigit = ( function() { var KeyIdentifierMap = { End : 35, Home : 36, Left : 37, Right : 39, 'U+00007F' : 46 // Delete } ; return function ( e ) { if ( !e ) e = event ; var iCode = ( e.keyCode || e.charCode ) ; if ( !iCode && e.keyIdentifier && ( e.keyIdentifier in KeyIdentifierMap ) ) iCode = KeyIdentifierMap[ e.keyIdentifier ] ; return ( ( iCode >= 48 && iCode <= 57 ) // Numbers || (iCode >= 35 && iCode <= 40) // Arrows, Home, End || iCode == 8 // Backspace || iCode == 46 // Delete || iCode == 9 // Tab ) ; } } )() ; String.prototype.Trim = function() { return this.replace( /(^\s*)|(\s*$)/g, '' ) ; } String.prototype.StartsWith = function( value ) { return ( this.substr( 0, value.length ) == value ) ; } String.prototype.Remove = function( start, length ) { var s = '' ; if ( start > 0 ) s = this.substring( 0, start ) ; if ( start + length < this.length ) s += this.substring( start + length , this.length ) ; return s ; } String.prototype.ReplaceAll = function( searchArray, replaceArray ) { var replaced = this ; for ( var i = 0 ; i < searchArray.length ; i++ ) { replaced = replaced.replace( searchArray[i], replaceArray[i] ) ; } return replaced ; } function OpenFileBrowser( url, width, height ) { // oEditor must be defined. var iLeft = ( oEditor.FCKConfig.ScreenWidth - width ) / 2 ; var iTop = ( oEditor.FCKConfig.ScreenHeight - height ) / 2 ; var sOptions = "toolbar=no,status=no,resizable=yes,dependent=yes,scrollbars=yes" ; sOptions += ",width=" + width ; sOptions += ",height=" + height ; sOptions += ",left=" + iLeft ; sOptions += ",top=" + iTop ; window.open( url, 'FCKBrowseWindow', sOptions ) ; } /** Utility function to create/update an element with a name attribute in IE, so it behaves properly when moved around It also allows to change the name or other special attributes in an existing node oEditor : instance of FCKeditor where the element will be created oOriginal : current element being edited or null if it has to be created nodeName : string with the name of the element to create oAttributes : Hash object with the attributes that must be set at creation time in IE Those attributes will be set also after the element has been created for any other browser to avoid redudant code */ function CreateNamedElement( oEditor, oOriginal, nodeName, oAttributes ) { var oNewNode ; // IE doesn't allow easily to change properties of an existing object, // so remove the old and force the creation of a new one. var oldNode = null ; if ( oOriginal && oEditor.FCKBrowserInfo.IsIE ) { // Force the creation only if some of the special attributes have changed: var bChanged = false; for( var attName in oAttributes ) bChanged |= ( oOriginal.getAttribute( attName, 2) != oAttributes[attName] ) ; if ( bChanged ) { oldNode = oOriginal ; oOriginal = null ; } } // If the node existed (and it's not IE), then we just have to update its attributes if ( oOriginal ) { oNewNode = oOriginal ; } else { // #676, IE doesn't play nice with the name or type attribute if ( oEditor.FCKBrowserInfo.IsIE ) { var sbHTML = [] ; sbHTML.push( '<' + nodeName ) ; for( var prop in oAttributes ) { sbHTML.push( ' ' + prop + '="' + oAttributes[prop] + '"' ) ; } sbHTML.push( '>' ) ; if ( !oEditor.FCKListsLib.EmptyElements[nodeName.toLowerCase()] ) sbHTML.push( '</' + nodeName + '>' ) ; oNewNode = oEditor.FCK.EditorDocument.createElement( sbHTML.join('') ) ; // Check if we are just changing the properties of an existing node: copy its properties if ( oldNode ) { CopyAttributes( oldNode, oNewNode, oAttributes ) ; oEditor.FCKDomTools.MoveChildren( oldNode, oNewNode ) ; oldNode.parentNode.removeChild( oldNode ) ; oldNode = null ; if ( oEditor.FCK.Selection.SelectionData ) { // Trick to refresh the selection object and avoid error in // fckdialog.html Selection.EnsureSelection var oSel = oEditor.FCK.EditorDocument.selection ; oEditor.FCK.Selection.SelectionData = oSel.createRange() ; // Now oSel.type will be 'None' reflecting the real situation } } oNewNode = oEditor.FCK.InsertElement( oNewNode ) ; // FCK.Selection.SelectionData is broken by now since we've // deleted the previously selected element. So we need to reassign it. if ( oEditor.FCK.Selection.SelectionData ) { var range = oEditor.FCK.EditorDocument.body.createControlRange() ; range.add( oNewNode ) ; oEditor.FCK.Selection.SelectionData = range ; } } else { oNewNode = oEditor.FCK.InsertElement( nodeName ) ; } } // Set the basic attributes for( var attName in oAttributes ) oNewNode.setAttribute( attName, oAttributes[attName], 0 ) ; // 0 : Case Insensitive return oNewNode ; } // Copy all the attributes from one node to the other, kinda like a clone // But oSkipAttributes is an object with the attributes that must NOT be copied function CopyAttributes( oSource, oDest, oSkipAttributes ) { var aAttributes = oSource.attributes ; for ( var n = 0 ; n < aAttributes.length ; n++ ) { var oAttribute = aAttributes[n] ; if ( oAttribute.specified ) { var sAttName = oAttribute.nodeName ; // We can set the type only once, so do it with the proper value, not copying it. if ( sAttName in oSkipAttributes ) continue ; var sAttValue = oSource.getAttribute( sAttName, 2 ) ; if ( sAttValue == null ) sAttValue = oAttribute.nodeValue ; oDest.setAttribute( sAttName, sAttValue, 0 ) ; // 0 : Case Insensitive } } // The style: if ( oSource.style.cssText !== '' ) oDest.style.cssText = oSource.style.cssText ; } /** * Replaces a tag with another one, keeping its contents: * for example TD --> TH, and TH --> TD. * input: the original node, and the new tag name * http://www.w3.org/TR/DOM-Level-3-Core/core.html#Document3-renameNode */ function RenameNode( oNode , newTag ) { // TODO: if the browser natively supports document.renameNode call it. // does any browser currently support it in order to test? // Only rename element nodes. if ( oNode.nodeType != 1 ) return null ; // If it's already correct exit here. if ( oNode.nodeName == newTag ) return oNode ; var oDoc = oNode.ownerDocument ; // Create the new node var newNode = oDoc.createElement( newTag ) ; // Copy all attributes CopyAttributes( oNode, newNode, {} ) ; // Move children to the new node FCKDomTools.MoveChildren( oNode, newNode ) ; // Finally replace the node and return the new one oNode.parentNode.replaceChild( newNode, oNode ) ; return newNode ; }
10npsite
trunk/guanli/system/fckeditor/editor/dialog/common/fck_dialog_common.js
JavaScript
asf20
10,481
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <!-- * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Anchor dialog window. --> <html> <head> <title>Anchor Properties</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta content="noindex, nofollow" name="robots"> <script src="common/fck_dialog_common.js" type="text/javascript"></script> <script type="text/javascript"> var dialog = window.parent ; var oEditor = dialog.InnerDialogLoaded() ; var FCK = oEditor.FCK ; var FCKBrowserInfo = oEditor.FCKBrowserInfo ; var FCKTools = oEditor.FCKTools ; var FCKRegexLib = oEditor.FCKRegexLib ; var oDOM = FCK.EditorDocument ; var oFakeImage = dialog.Selection.GetSelectedElement() ; var oAnchor ; if ( oFakeImage ) { if ( oFakeImage.tagName == 'IMG' && oFakeImage.getAttribute('_fckanchor') ) oAnchor = FCK.GetRealElement( oFakeImage ) ; else oFakeImage = null ; } //Search for a real anchor if ( !oFakeImage ) { oAnchor = FCK.Selection.MoveToAncestorNode( 'A' ) ; if ( oAnchor ) FCK.Selection.SelectNode( oAnchor ) ; } window.onload = function() { // First of all, translate the dialog box texts oEditor.FCKLanguageManager.TranslatePage(document) ; if ( oAnchor ) GetE('txtName').value = oAnchor.name ; else oAnchor = null ; window.parent.SetOkButton( true ) ; window.parent.SetAutoSize( true ) ; SelectField( 'txtName' ) ; } function Ok() { var sNewName = GetE('txtName').value ; // Remove any illegal character in a name attribute: // A name should start with a letter, but the validator passes anyway. sNewName = sNewName.replace( /[^\w-_\.:]/g, '_' ) ; if ( sNewName.length == 0 ) { // Remove the anchor if the user leaves the name blank if ( oAnchor ) { // Removes the current anchor from the document using the new command FCK.Commands.GetCommand( 'AnchorDelete' ).Execute() ; return true ; } alert( oEditor.FCKLang.DlgAnchorErrorName ) ; return false ; } oEditor.FCKUndo.SaveUndoStep() ; if ( oAnchor ) // Modifying an existent anchor. { ReadjustLinksToAnchor( oAnchor.name, sNewName ); // Buggy explorer, bad bad browser. http://alt-tag.com/blog/archives/2006/02/ie-dom-bugs/ // Instead of just replacing the .name for the existing anchor (in order to preserve the content), we must remove the .name // and assign .name, although it won't appear until it's specially processed in fckxhtml.js // We remove the previous name oAnchor.removeAttribute( 'name' ) ; // Now we set it, but later we must process it specially oAnchor.name = sNewName ; return true ; } // Create a new anchor preserving the current selection var aNewAnchors = oEditor.FCK.CreateLink( '#' ) ; if ( aNewAnchors.length == 0 ) aNewAnchors.push( oEditor.FCK.InsertElement( 'a' ) ) ; else { // Remove the fake href for ( var i = 0 ; i < aNewAnchors.length ; i++ ) aNewAnchors[i].removeAttribute( 'href' ) ; } // More than one anchors may have been created, so interact through all of them (see #220). for ( var i = 0 ; i < aNewAnchors.length ; i++ ) { oAnchor = aNewAnchors[i] ; // Set the name if ( FCKBrowserInfo.IsIE ) { // Setting anchor names directly in IE will trash the HTML code stored // in FCKTempBin after undos. See #2263. var replaceAnchor = oEditor.FCK.EditorDocument.createElement( '<a name="' + FCKTools.HTMLEncode( sNewName ).replace( '"', '&quot;' ) + '">' ) ; oEditor.FCKDomTools.MoveChildren( oAnchor, replaceAnchor ) ; oAnchor.parentNode.replaceChild( replaceAnchor, oAnchor ) ; oAnchor = replaceAnchor ; } else oAnchor.name = sNewName ; // IE does require special processing to show the Anchor's image // Opera doesn't allow to select empty anchors if ( FCKBrowserInfo.IsIE || FCKBrowserInfo.IsOpera ) { if ( oAnchor.innerHTML != '' ) { if ( FCKBrowserInfo.IsIE ) oAnchor.className += ' FCK__AnchorC' ; } else { // Create a fake image for both IE and Opera var oImg = oEditor.FCKDocumentProcessor_CreateFakeImage( 'FCK__Anchor', oAnchor.cloneNode(true) ) ; oImg.setAttribute( '_fckanchor', 'true', 0 ) ; oAnchor.parentNode.insertBefore( oImg, oAnchor ) ; oAnchor.parentNode.removeChild( oAnchor ) ; } } } return true ; } // Checks all the links in the current page pointing to the current name and changes them to the new name function ReadjustLinksToAnchor( sCurrent, sNew ) { var oDoc = FCK.EditorDocument ; var aLinks = oDoc.getElementsByTagName( 'A' ) ; var sReference = '#' + sCurrent ; // The url of the document, so we check absolute and partial references. var sFullReference = oDoc.location.href.replace( /(#.*$)/, '') ; sFullReference += sReference ; var oLink ; var i = aLinks.length - 1 ; while ( i >= 0 && ( oLink = aLinks[i--] ) ) { var sHRef = oLink.getAttribute( '_fcksavedurl' ) ; if ( sHRef == null ) sHRef = oLink.getAttribute( 'href' , 2 ) || '' ; if ( sHRef == sReference || sHRef == sFullReference ) { oLink.href = '#' + sNew ; SetAttribute( oLink, '_fcksavedurl', '#' + sNew ) ; } } } </script> </head> <body style="overflow: hidden"> <table height="100%" width="100%"> <tr> <td align="center"> <table border="0" cellpadding="0" cellspacing="0" width="80%"> <tr> <td> <span fckLang="DlgAnchorName">Anchor Name</span><BR> <input id="txtName" style="WIDTH: 100%" type="text"> </td> </tr> </table> </td> </tr> </table> </body> </html>
10npsite
trunk/guanli/system/fckeditor/editor/dialog/fck_anchor.html
HTML
asf20
6,315
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <!-- * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Preview page for the Image dialog window. * * Curiosity: http://en.wikipedia.org/wiki/Lorem_ipsum --> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="robots" content="noindex, nofollow" /> <script src="../common/fck_dialog_common.js" type="text/javascript"></script> <script type="text/javascript"> var FCKTools = window.parent.FCKTools ; var FCKConfig = window.parent.FCKConfig ; // Set the preview CSS document.write( FCKTools.GetStyleHtml( FCKConfig.EditorAreaCSS ) ) ; document.write( FCKTools.GetStyleHtml( FCKConfig.EditorAreaStyles ) ) ; if ( window.parent.FCKConfig.BaseHref.length > 0 ) document.write( '<base href="' + window.parent.FCKConfig.BaseHref + '">' ) ; window.onload = function() { window.parent.SetPreviewElements( document.getElementById( 'imgPreview' ), document.getElementById( 'lnkPreview' ) ) ; } </script> </head> <body> <div> <a id="lnkPreview" onclick="return false;" style="cursor: default"> <img id="imgPreview" onload="window.parent.UpdateOriginal();" style="display: none" alt="" /></a>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas feugiat consequat diam. Maecenas metus. Vivamus diam purus, cursus a, commodo non, facilisis vitae, nulla. Aenean dictum lacinia tortor. Nunc iaculis, nibh non iaculis aliquam, orci felis euismod neque, sed ornare massa mauris sed velit. Nulla pretium mi et risus. Fusce mi pede, tempor id, cursus ac, ullamcorper nec, enim. Sed tortor. Curabitur molestie. Duis velit augue, condimentum at, ultrices a, luctus ut, orci. Donec pellentesque egestas eros. Integer cursus, augue in cursus faucibus, eros pede bibendum sem, in tempus tellus justo quis ligula. Etiam eget tortor. Vestibulum rutrum, est ut placerat elementum, lectus nisl aliquam velit, tempor aliquam eros nunc nonummy metus. In eros metus, gravida a, gravida sed, lobortis id, turpis. Ut ultrices, ipsum at venenatis fringilla, sem nulla lacinia tellus, eget aliquet turpis mauris non enim. Nam turpis. Suspendisse lacinia. Curabitur ac tortor ut ipsum egestas elementum. Nunc imperdiet gravida mauris. </div> </body> </html>
10npsite
trunk/guanli/system/fckeditor/editor/dialog/fck_image/fck_image_preview.html
HTML
asf20
2,975
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Scripts related to the Image dialog window (see fck_image.html). */ var dialog = window.parent ; var oEditor = dialog.InnerDialogLoaded() ; var FCK = oEditor.FCK ; var FCKLang = oEditor.FCKLang ; var FCKConfig = oEditor.FCKConfig ; var FCKDebug = oEditor.FCKDebug ; var FCKTools = oEditor.FCKTools ; var bImageButton = ( document.location.search.length > 0 && document.location.search.substr(1) == 'ImageButton' ) ; //#### Dialog Tabs // Set the dialog tabs. dialog.AddTab( 'Info', FCKLang.DlgImgInfoTab ) ; if ( !bImageButton && !FCKConfig.ImageDlgHideLink ) dialog.AddTab( 'Link', FCKLang.DlgImgLinkTab ) ; if ( FCKConfig.ImageUpload ) dialog.AddTab( 'Upload', FCKLang.DlgLnkUpload ) ; if ( !FCKConfig.ImageDlgHideAdvanced ) dialog.AddTab( 'Advanced', FCKLang.DlgAdvancedTag ) ; // Function called when a dialog tag is selected. function OnDialogTabChange( tabCode ) { ShowE('divInfo' , ( tabCode == 'Info' ) ) ; ShowE('divLink' , ( tabCode == 'Link' ) ) ; ShowE('divUpload' , ( tabCode == 'Upload' ) ) ; ShowE('divAdvanced' , ( tabCode == 'Advanced' ) ) ; } // Get the selected image (if available). var oImage = dialog.Selection.GetSelectedElement() ; if ( oImage && oImage.tagName != 'IMG' && !( oImage.tagName == 'INPUT' && oImage.type == 'image' ) ) oImage = null ; // Get the active link. var oLink = dialog.Selection.GetSelection().MoveToAncestorNode( 'A' ) ; var oImageOriginal ; function UpdateOriginal( resetSize ) { if ( !eImgPreview ) return ; if ( GetE('txtUrl').value.length == 0 ) { oImageOriginal = null ; return ; } oImageOriginal = document.createElement( 'IMG' ) ; // new Image() ; if ( resetSize ) { oImageOriginal.onload = function() { this.onload = null ; ResetSizes() ; } } oImageOriginal.src = eImgPreview.src ; } var bPreviewInitialized ; window.onload = function() { // Translate the dialog box texts. oEditor.FCKLanguageManager.TranslatePage(document) ; GetE('btnLockSizes').title = FCKLang.DlgImgLockRatio ; GetE('btnResetSize').title = FCKLang.DlgBtnResetSize ; // Load the selected element information (if any). LoadSelection() ; // Show/Hide the "Browse Server" button. GetE('tdBrowse').style.display = FCKConfig.ImageBrowser ? '' : 'none' ; GetE('divLnkBrowseServer').style.display = FCKConfig.LinkBrowser ? '' : 'none' ; UpdateOriginal() ; // Set the actual uploader URL. if ( FCKConfig.ImageUpload ) GetE('frmUpload').action = FCKConfig.ImageUploadURL ; dialog.SetAutoSize( true ) ; // Activate the "OK" button. dialog.SetOkButton( true ) ; SelectField( 'txtUrl' ) ; } function LoadSelection() { if ( ! oImage ) return ; var sUrl = oImage.getAttribute( '_fcksavedurl' ) ; if ( sUrl == null ) sUrl = GetAttribute( oImage, 'src', '' ) ; GetE('txtUrl').value = sUrl ; GetE('txtAlt').value = GetAttribute( oImage, 'alt', '' ) ; GetE('txtVSpace').value = GetAttribute( oImage, 'vspace', '' ) ; GetE('txtHSpace').value = GetAttribute( oImage, 'hspace', '' ) ; GetE('txtBorder').value = GetAttribute( oImage, 'border', '' ) ; GetE('cmbAlign').value = GetAttribute( oImage, 'align', '' ) ; var iWidth, iHeight ; var regexSize = /^\s*(\d+)px\s*$/i ; if ( oImage.style.width ) { var aMatchW = oImage.style.width.match( regexSize ) ; if ( aMatchW ) { iWidth = aMatchW[1] ; oImage.style.width = '' ; SetAttribute( oImage, 'width' , iWidth ) ; } } if ( oImage.style.height ) { var aMatchH = oImage.style.height.match( regexSize ) ; if ( aMatchH ) { iHeight = aMatchH[1] ; oImage.style.height = '' ; SetAttribute( oImage, 'height', iHeight ) ; } } GetE('txtWidth').value = iWidth ? iWidth : GetAttribute( oImage, "width", '' ) ; GetE('txtHeight').value = iHeight ? iHeight : GetAttribute( oImage, "height", '' ) ; // Get Advances Attributes GetE('txtAttId').value = oImage.id ; GetE('cmbAttLangDir').value = oImage.dir ; GetE('txtAttLangCode').value = oImage.lang ; GetE('txtAttTitle').value = oImage.title ; GetE('txtLongDesc').value = oImage.longDesc ; if ( oEditor.FCKBrowserInfo.IsIE ) { GetE('txtAttClasses').value = oImage.className || '' ; GetE('txtAttStyle').value = oImage.style.cssText ; } else { GetE('txtAttClasses').value = oImage.getAttribute('class',2) || '' ; GetE('txtAttStyle').value = oImage.getAttribute('style',2) ; } if ( oLink ) { var sLinkUrl = oLink.getAttribute( '_fcksavedurl' ) ; if ( sLinkUrl == null ) sLinkUrl = oLink.getAttribute('href',2) ; GetE('txtLnkUrl').value = sLinkUrl ; GetE('cmbLnkTarget').value = oLink.target ; } UpdatePreview() ; } //#### The OK button was hit. function Ok() { if ( GetE('txtUrl').value.length == 0 ) { dialog.SetSelectedTab( 'Info' ) ; GetE('txtUrl').focus() ; alert( FCKLang.DlgImgAlertUrl ) ; return false ; } var bHasImage = ( oImage != null ) ; if ( bHasImage && bImageButton && oImage.tagName == 'IMG' ) { if ( confirm( 'Do you want to transform the selected image on a image button?' ) ) oImage = null ; } else if ( bHasImage && !bImageButton && oImage.tagName == 'INPUT' ) { if ( confirm( 'Do you want to transform the selected image button on a simple image?' ) ) oImage = null ; } oEditor.FCKUndo.SaveUndoStep() ; if ( !bHasImage ) { if ( bImageButton ) { oImage = FCK.EditorDocument.createElement( 'input' ) ; oImage.type = 'image' ; oImage = FCK.InsertElement( oImage ) ; } else oImage = FCK.InsertElement( 'img' ) ; } UpdateImage( oImage ) ; var sLnkUrl = GetE('txtLnkUrl').value.Trim() ; if ( sLnkUrl.length == 0 ) { if ( oLink ) FCK.ExecuteNamedCommand( 'Unlink' ) ; } else { if ( oLink ) // Modifying an existent link. oLink.href = sLnkUrl ; else // Creating a new link. { if ( !bHasImage ) oEditor.FCKSelection.SelectNode( oImage ) ; oLink = oEditor.FCK.CreateLink( sLnkUrl )[0] ; if ( !bHasImage ) { oEditor.FCKSelection.SelectNode( oLink ) ; oEditor.FCKSelection.Collapse( false ) ; } } SetAttribute( oLink, '_fcksavedurl', sLnkUrl ) ; SetAttribute( oLink, 'target', GetE('cmbLnkTarget').value ) ; } return true ; } function UpdateImage( e, skipId ) { e.src = GetE('txtUrl').value ; SetAttribute( e, "_fcksavedurl", GetE('txtUrl').value ) ; SetAttribute( e, "alt" , GetE('txtAlt').value ) ; SetAttribute( e, "width" , GetE('txtWidth').value ) ; SetAttribute( e, "height", GetE('txtHeight').value ) ; SetAttribute( e, "vspace", GetE('txtVSpace').value ) ; SetAttribute( e, "hspace", GetE('txtHSpace').value ) ; SetAttribute( e, "border", GetE('txtBorder').value ) ; SetAttribute( e, "align" , GetE('cmbAlign').value ) ; // Advances Attributes if ( ! skipId ) SetAttribute( e, 'id', GetE('txtAttId').value ) ; SetAttribute( e, 'dir' , GetE('cmbAttLangDir').value ) ; SetAttribute( e, 'lang' , GetE('txtAttLangCode').value ) ; SetAttribute( e, 'title' , GetE('txtAttTitle').value ) ; SetAttribute( e, 'longDesc' , GetE('txtLongDesc').value ) ; if ( oEditor.FCKBrowserInfo.IsIE ) { e.className = GetE('txtAttClasses').value ; e.style.cssText = GetE('txtAttStyle').value ; } else { SetAttribute( e, 'class' , GetE('txtAttClasses').value ) ; SetAttribute( e, 'style', GetE('txtAttStyle').value ) ; } } var eImgPreview ; var eImgPreviewLink ; function SetPreviewElements( imageElement, linkElement ) { eImgPreview = imageElement ; eImgPreviewLink = linkElement ; UpdatePreview() ; UpdateOriginal() ; bPreviewInitialized = true ; } function UpdatePreview() { if ( !eImgPreview || !eImgPreviewLink ) return ; if ( GetE('txtUrl').value.length == 0 ) eImgPreviewLink.style.display = 'none' ; else { UpdateImage( eImgPreview, true ) ; if ( GetE('txtLnkUrl').value.Trim().length > 0 ) eImgPreviewLink.href = 'javascript:void(null);' ; else SetAttribute( eImgPreviewLink, 'href', '' ) ; eImgPreviewLink.style.display = '' ; } } var bLockRatio = true ; function SwitchLock( lockButton ) { bLockRatio = !bLockRatio ; lockButton.className = bLockRatio ? 'BtnLocked' : 'BtnUnlocked' ; lockButton.title = bLockRatio ? 'Lock sizes' : 'Unlock sizes' ; if ( bLockRatio ) { if ( GetE('txtWidth').value.length > 0 ) OnSizeChanged( 'Width', GetE('txtWidth').value ) ; else OnSizeChanged( 'Height', GetE('txtHeight').value ) ; } } // Fired when the width or height input texts change function OnSizeChanged( dimension, value ) { // Verifies if the aspect ration has to be maintained if ( oImageOriginal && bLockRatio ) { var e = dimension == 'Width' ? GetE('txtHeight') : GetE('txtWidth') ; if ( value.length == 0 || isNaN( value ) ) { e.value = '' ; return ; } if ( dimension == 'Width' ) value = value == 0 ? 0 : Math.round( oImageOriginal.height * ( value / oImageOriginal.width ) ) ; else value = value == 0 ? 0 : Math.round( oImageOriginal.width * ( value / oImageOriginal.height ) ) ; if ( !isNaN( value ) ) e.value = value ; } UpdatePreview() ; } // Fired when the Reset Size button is clicked function ResetSizes() { if ( ! oImageOriginal ) return ; if ( oEditor.FCKBrowserInfo.IsGecko && !oImageOriginal.complete ) { setTimeout( ResetSizes, 50 ) ; return ; } GetE('txtWidth').value = oImageOriginal.width ; GetE('txtHeight').value = oImageOriginal.height ; UpdatePreview() ; } function BrowseServer() { OpenServerBrowser( 'Image', FCKConfig.ImageBrowserURL, FCKConfig.ImageBrowserWindowWidth, FCKConfig.ImageBrowserWindowHeight ) ; } function LnkBrowseServer() { OpenServerBrowser( 'Link', FCKConfig.LinkBrowserURL, FCKConfig.LinkBrowserWindowWidth, FCKConfig.LinkBrowserWindowHeight ) ; } function OpenServerBrowser( type, url, width, height ) { sActualBrowser = type ; OpenFileBrowser( url, width, height ) ; } var sActualBrowser ; function SetUrl( url, width, height, alt ) { if ( sActualBrowser == 'Link' ) { GetE('txtLnkUrl').value = url ; UpdatePreview() ; } else { GetE('txtUrl').value = url ; GetE('txtWidth').value = width ? width : '' ; GetE('txtHeight').value = height ? height : '' ; if ( alt ) GetE('txtAlt').value = alt; UpdatePreview() ; UpdateOriginal( true ) ; } dialog.SetSelectedTab( 'Info' ) ; } function OnUploadCompleted( errorNumber, fileUrl, fileName, customMsg ) { // Remove animation window.parent.Throbber.Hide() ; GetE( 'divUpload' ).style.display = '' ; switch ( errorNumber ) { case 0 : // No errors alert( 'Your file has been successfully uploaded' ) ; break ; case 1 : // Custom error alert( customMsg ) ; return ; case 101 : // Custom warning alert( customMsg ) ; break ; case 201 : alert( 'A file with the same name is already available. The uploaded file has been renamed to "' + fileName + '"' ) ; break ; case 202 : alert( 'Invalid file type' ) ; return ; case 203 : alert( "Security error. You probably don't have enough permissions to upload. Please check your server." ) ; return ; case 500 : alert( 'The connector is disabled' ) ; break ; default : alert( 'Error on file upload. Error number: ' + errorNumber ) ; return ; } sActualBrowser = '' ; SetUrl( fileUrl ) ; GetE('frmUpload').reset() ; } var oUploadAllowedExtRegex = new RegExp( FCKConfig.ImageUploadAllowedExtensions, 'i' ) ; var oUploadDeniedExtRegex = new RegExp( FCKConfig.ImageUploadDeniedExtensions, 'i' ) ; function CheckUpload() { var sFile = GetE('txtUploadFile').value ; if ( sFile.length == 0 ) { alert( 'Please select a file to upload' ) ; return false ; } if ( ( FCKConfig.ImageUploadAllowedExtensions.length > 0 && !oUploadAllowedExtRegex.test( sFile ) ) || ( FCKConfig.ImageUploadDeniedExtensions.length > 0 && oUploadDeniedExtRegex.test( sFile ) ) ) { OnUploadCompleted( 202 ) ; return false ; } // Show animation window.parent.Throbber.Show( 100 ) ; GetE( 'divUpload' ).style.display = 'none' ; return true ; }
10npsite
trunk/guanli/system/fckeditor/editor/dialog/fck_image/fck_image.js
JavaScript
asf20
13,079
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <!-- * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Table dialog window. --> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Table Properties</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="robots" content="noindex, nofollow" /> <script src="common/fck_dialog_common.js" type="text/javascript"></script> <script type="text/javascript"> var dialog = window.parent ; var oEditor = dialog.InnerDialogLoaded() ; var FCKDomTools = oEditor.FCKDomTools ; // Gets the table if there is one selected. var table ; var e = dialog.Selection.GetSelectedElement() ; var hasColumnHeaders ; if ( ( !e && document.location.search.substr(1) == 'Parent' ) || ( e && e.tagName != 'TABLE' ) ) e = oEditor.FCKSelection.MoveToAncestorNode( 'TABLE' ) ; if ( e && e.tagName == "TABLE" ) table = e ; // Fired when the window loading process is finished. It sets the fields with the // actual values if a table is selected in the editor. window.onload = function() { // First of all, translate the dialog box texts oEditor.FCKLanguageManager.TranslatePage(document) ; if (table) { document.getElementById('txtRows').value = table.rows.length ; document.getElementById('txtColumns').value = table.rows[0].cells.length ; // Gets the value from the Width or the Style attribute var iWidth = (table.style.width ? table.style.width : table.width ) ; var iHeight = (table.style.height ? table.style.height : table.height ) ; if (iWidth.indexOf('%') >= 0) // Percentual = % { iWidth = parseInt( iWidth.substr(0,iWidth.length - 1), 10 ) ; document.getElementById('selWidthType').value = "percent" ; } else if (iWidth.indexOf('px') >= 0) // Style Pixel = px { // iWidth = iWidth.substr(0,iWidth.length - 2); document.getElementById('selWidthType').value = "pixels" ; } if (iHeight && iHeight.indexOf('px') >= 0) // Style Pixel = px iHeight = iHeight.substr(0,iHeight.length - 2); document.getElementById('txtWidth').value = iWidth || '' ; document.getElementById('txtHeight').value = iHeight || '' ; document.getElementById('txtBorder').value = GetAttribute( table, 'border', '' ) ; document.getElementById('selAlignment').value = GetAttribute( table, 'align', '' ) ; document.getElementById('txtCellPadding').value = GetAttribute( table, 'cellPadding', '' ) ; document.getElementById('txtCellSpacing').value = GetAttribute( table, 'cellSpacing', '' ) ; document.getElementById('txtSummary').value = GetAttribute( table, 'summary', '' ) ; // document.getElementById('cmbFontStyle').value = table.className ; var eCaption = oEditor.FCKDomTools.GetFirstChild( table, 'CAPTION' ) ; if ( eCaption ) document.getElementById('txtCaption').value = eCaption.innerHTML ; hasColumnHeaders = true ; // Check if all the first cells in every row are TH for (var row=0; row<table.rows.length; row++) { // If just one cell isn't a TH then it isn't a header column if ( table.rows[row].cells[0].nodeName != 'TH' ) { hasColumnHeaders = false ; break; } } // Check if the table contains <thead> if ((table.tHead !== null) ) { if (hasColumnHeaders) GetE('selHeaders').value = 'both' ; else GetE('selHeaders').value = 'row' ; } else { if (hasColumnHeaders) GetE('selHeaders').value = 'col' ; else GetE('selHeaders').value = '' ; } document.getElementById('txtRows').disabled = true ; document.getElementById('txtColumns').disabled = true ; SelectField( 'txtWidth' ) ; } else SelectField( 'txtRows' ) ; dialog.SetOkButton( true ) ; dialog.SetAutoSize( true ) ; } // Fired when the user press the OK button function Ok() { var bExists = ( table != null ) ; var oDoc = oEditor.FCK.EditorDocument ; oEditor.FCKUndo.SaveUndoStep() ; if ( ! bExists ) table = oDoc.createElement( "TABLE" ) ; // Removes the Width and Height styles if ( bExists && table.style.width ) table.style.width = null ; //.removeAttribute("width") ; if ( bExists && table.style.height ) table.style.height = null ; //.removeAttribute("height") ; var sWidth = GetE('txtWidth').value ; if ( sWidth.length > 0 && GetE('selWidthType').value == 'percent' ) sWidth += '%' ; SetAttribute( table, 'width' , sWidth ) ; SetAttribute( table, 'height' , GetE('txtHeight').value ) ; SetAttribute( table, 'border' , GetE('txtBorder').value ) ; SetAttribute( table, 'align' , GetE('selAlignment').value ) ; SetAttribute( table, 'cellPadding' , GetE('txtCellPadding').value ) ; SetAttribute( table, 'cellSpacing' , GetE('txtCellSpacing').value ) ; SetAttribute( table, 'summary' , GetE('txtSummary').value ) ; var headers = GetE('selHeaders').value ; if ( bExists ) { // Should we make a <thead>? if ( table.tHead==null && (headers=='row' || headers=='both') ) { var oThead = table.createTHead() ; var tbody = FCKDomTools.GetFirstChild( table, 'TBODY' ) ; var theRow= FCKDomTools.GetFirstChild( tbody, 'TR' ) ; //now change TD to TH: for (var i = 0; i<theRow.childNodes.length ; i++) { var th = RenameNode(theRow.childNodes[i], 'TH') ; if (th != null) th.scope='col' ; } oThead.appendChild( theRow ) ; } if ( table.tHead!==null && !(headers=='row' || headers=='both') ) { // Move the row out of the THead and put it in the TBody: var tHead = table.tHead ; var tbody = FCKDomTools.GetFirstChild( table, 'TBODY' ) ; var previousFirstRow = tbody.firstChild ; while ( tHead.firstChild ) { var theRow = tHead.firstChild ; for (var i = 0; i < theRow.childNodes.length ; i++ ) { var newCell = RenameNode( theRow.childNodes[i], 'TD' ) ; if ( newCell != null ) newCell.removeAttribute( 'scope' ) ; } tbody.insertBefore( theRow, previousFirstRow ) ; } table.removeChild( tHead ) ; } // Should we make all first cells in a row TH? if ( (!hasColumnHeaders) && (headers=='col' || headers=='both') ) { for( var row=0 ; row < table.rows.length ; row++ ) { var newCell = RenameNode(table.rows[row].cells[0], 'TH') ; if ( newCell != null ) newCell.scope = 'row' ; } } // Should we make all first TH-cells in a row make TD? If 'yes' we do it the other way round :-) if ( (hasColumnHeaders) && !(headers=='col' || headers=='both') ) { for( var row=0 ; row < table.rows.length ; row++ ) { var oRow = table.rows[row] ; if ( oRow.parentNode.nodeName == 'TBODY' ) { var newCell = RenameNode(oRow.cells[0], 'TD') ; if (newCell != null) newCell.removeAttribute( 'scope' ) ; } } } } if (! bExists) { var iRows = GetE('txtRows').value ; var iCols = GetE('txtColumns').value ; var startRow = 0 ; // Should we make a <thead> ? if (headers=='row' || headers=='both') { startRow++ ; var oThead = table.createTHead() ; var oRow = table.insertRow(-1) ; oThead.appendChild(oRow); for ( var c = 0 ; c < iCols ; c++ ) { var oThcell = oDoc.createElement( 'TH' ) ; oThcell.scope = 'col' ; oRow.appendChild( oThcell ) ; if ( oEditor.FCKBrowserInfo.IsGeckoLike ) oEditor.FCKTools.AppendBogusBr( oThcell ) ; } } // Opera automatically creates a tbody when a thead has been added var oTbody = FCKDomTools.GetFirstChild( table, 'TBODY' ) ; if ( !oTbody ) { // make TBODY if it doesn't exist oTbody = oDoc.createElement( 'TBODY' ) ; table.appendChild( oTbody ) ; } for ( var r = startRow ; r < iRows; r++ ) { var oRow = oDoc.createElement( 'TR' ) ; oTbody.appendChild(oRow) ; var startCol = 0 ; // Is the first column a header? if (headers=='col' || headers=='both') { var oThcell = oDoc.createElement( 'TH' ) ; oThcell.scope = 'row' ; oRow.appendChild( oThcell ) ; if ( oEditor.FCKBrowserInfo.IsGeckoLike ) oEditor.FCKTools.AppendBogusBr( oThcell ) ; startCol++ ; } for ( var c = startCol ; c < iCols ; c++ ) { // IE will leave the TH at the end of the row if we use now oRow.insertCell(-1) var oCell = oDoc.createElement( 'TD' ) ; oRow.appendChild( oCell ) ; if ( oEditor.FCKBrowserInfo.IsGeckoLike ) oEditor.FCKTools.AppendBogusBr( oCell ) ; } } oEditor.FCK.InsertElement( table ) ; } var eCaption = oEditor.FCKDomTools.GetFirstChild( table, 'CAPTION' ) ; if ( eCaption && !oEditor.FCKBrowserInfo.IsIE ) eCaption.parentNode.removeChild( eCaption ) ; if ( document.getElementById('txtCaption').value != '' ) { if ( !eCaption || !oEditor.FCKBrowserInfo.IsIE ) { eCaption = oDoc.createElement( 'CAPTION' ) ; table.insertBefore( eCaption, table.firstChild ) ; } eCaption.innerHTML = document.getElementById('txtCaption').value ; } else if ( bExists && eCaption ) { // TODO: It causes an IE internal error if using removeChild or // table.deleteCaption() (see #505). if ( oEditor.FCKBrowserInfo.IsIE ) eCaption.innerHTML = '' ; } return true ; } </script> </head> <body style="overflow: hidden"> <table id="otable" cellspacing="0" cellpadding="0" width="100%" border="0" style="height: 100%"> <tr> <td> <table cellspacing="1" cellpadding="1" width="100%" border="0"> <tr> <td valign="top"> <table cellspacing="1" cellpadding="0" border="0"> <tr> <td> <span fcklang="DlgTableRows">Rows</span>:</td> <td> &nbsp;<input id="txtRows" type="text" maxlength="3" size="2" value="3" onkeypress="return IsDigit(event);" /></td> </tr> <tr> <td> <span fcklang="DlgTableColumns">Columns</span>:</td> <td> &nbsp;<input id="txtColumns" type="text" maxlength="2" size="2" value="2" onkeypress="return IsDigit(event);" /></td> </tr> <tr> <td><span fcklang="DlgTableHeaders">Headers</span>:</td> <td> &nbsp;<select id="selHeaders"> <option fcklang="DlgTableHeadersNone" value="">None</option> <option fcklang="DlgTableHeadersRow" value="row">First row</option> <option fcklang="DlgTableHeadersColumn" value="col">First column</option> <option fcklang="DlgTableHeadersBoth" value="both">Both</option> </select> </td> </tr> <tr> <td> <span fcklang="DlgTableBorder">Border size</span>:</td> <td> &nbsp;<input id="txtBorder" type="text" maxlength="2" size="2" value="1" onkeypress="return IsDigit(event);" /></td> </tr> <tr> <td> <span fcklang="DlgTableAlign">Alignment</span>:</td> <td> &nbsp;<select id="selAlignment"> <option fcklang="DlgTableAlignNotSet" value="" selected="selected">&lt;Not set&gt;</option> <option fcklang="DlgTableAlignLeft" value="left">Left</option> <option fcklang="DlgTableAlignCenter" value="center">Center</option> <option fcklang="DlgTableAlignRight" value="right">Right</option> </select></td> </tr> </table> </td> <td> &nbsp;&nbsp;&nbsp;</td> <td align="right" valign="top"> <table cellspacing="0" cellpadding="0" border="0"> <tr> <td> <span fcklang="DlgTableWidth">Width</span>:</td> <td> &nbsp;<input id="txtWidth" type="text" maxlength="4" size="3" value="200" onkeypress="return IsDigit(event);" /></td> <td> &nbsp;<select id="selWidthType"> <option fcklang="DlgTableWidthPx" value="pixels" selected="selected">pixels</option> <option fcklang="DlgTableWidthPc" value="percent">percent</option> </select></td> </tr> <tr> <td> <span fcklang="DlgTableHeight">Height</span>:</td> <td> &nbsp;<input id="txtHeight" type="text" maxlength="4" size="3" onkeypress="return IsDigit(event);" /></td> <td> &nbsp;<span fcklang="DlgTableWidthPx">pixels</span></td> </tr> <tr> <td colspan="3">&nbsp;</td> </tr> <tr> <td nowrap="nowrap"> <span fcklang="DlgTableCellSpace">Cell spacing</span>:</td> <td> &nbsp;<input id="txtCellSpacing" type="text" maxlength="2" size="2" value="1" onkeypress="return IsDigit(event);" /></td> <td> &nbsp;</td> </tr> <tr> <td nowrap="nowrap"> <span fcklang="DlgTableCellPad">Cell padding</span>:</td> <td> &nbsp;<input id="txtCellPadding" type="text" maxlength="2" size="2" value="1" onkeypress="return IsDigit(event);" /></td> <td> &nbsp;</td> </tr> </table> </td> </tr> </table> <table cellspacing="0" cellpadding="0" width="100%" border="0"> <tr> <td nowrap="nowrap"> <span fcklang="DlgTableCaption">Caption</span>:&nbsp;</td> <td> &nbsp;</td> <td width="100%" nowrap="nowrap"> <input id="txtCaption" type="text" style="width: 100%" /></td> </tr> <tr> <td nowrap="nowrap"> <span fcklang="DlgTableSummary">Summary</span>:&nbsp;</td> <td> &nbsp;</td> <td width="100%" nowrap="nowrap"> <input id="txtSummary" type="text" style="width: 100%" /></td> </tr> </table> </td> </tr> </table> </body> </html>
10npsite
trunk/guanli/system/fckeditor/editor/dialog/fck_table.html
HTML
asf20
14,549
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <!-- * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Preview page for the Flash dialog window. --> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="robots" content="noindex, nofollow"> <script src="../common/fck_dialog_common.js" type="text/javascript"></script> <script language="javascript"> var FCKTools = window.parent.FCKTools ; var FCKConfig = window.parent.FCKConfig ; // Sets the Skin CSS document.write( FCKTools.GetStyleHtml( FCKConfig.SkinDialogCSS ) ) ; document.write( FCKTools.GetStyleHtml( GetCommonDialogCss( '../' ) ) ) ; if ( window.parent.FCKConfig.BaseHref.length > 0 ) document.write( '<base href="' + window.parent.FCKConfig.BaseHref + '">' ) ; window.onload = function() { window.parent.SetPreviewElement( document.body ) ; } </script> </head> <body style="COLOR: #000000; BACKGROUND-COLOR: #ffffff"></body> </html>
10npsite
trunk/guanli/system/fckeditor/editor/dialog/fck_flash/fck_flash_preview.html
HTML
asf20
1,593
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Scripts related to the Flash dialog window (see fck_flash.html). */ var dialog = window.parent ; var oEditor = dialog.InnerDialogLoaded() ; var FCK = oEditor.FCK ; var FCKLang = oEditor.FCKLang ; var FCKConfig = oEditor.FCKConfig ; var FCKTools = oEditor.FCKTools ; //#### Dialog Tabs // Set the dialog tabs. dialog.AddTab( 'Info', oEditor.FCKLang.DlgInfoTab ) ; if ( FCKConfig.FlashUpload ) dialog.AddTab( 'Upload', FCKLang.DlgLnkUpload ) ; if ( !FCKConfig.FlashDlgHideAdvanced ) dialog.AddTab( 'Advanced', oEditor.FCKLang.DlgAdvancedTag ) ; // Function called when a dialog tag is selected. function OnDialogTabChange( tabCode ) { ShowE('divInfo' , ( tabCode == 'Info' ) ) ; ShowE('divUpload' , ( tabCode == 'Upload' ) ) ; ShowE('divAdvanced' , ( tabCode == 'Advanced' ) ) ; } // Get the selected flash embed (if available). var oFakeImage = dialog.Selection.GetSelectedElement() ; var oEmbed ; if ( oFakeImage ) { if ( oFakeImage.tagName == 'IMG' && oFakeImage.getAttribute('_fckflash') ) oEmbed = FCK.GetRealElement( oFakeImage ) ; else oFakeImage = null ; } window.onload = function() { // Translate the dialog box texts. oEditor.FCKLanguageManager.TranslatePage(document) ; // Load the selected element information (if any). LoadSelection() ; // Show/Hide the "Browse Server" button. GetE('tdBrowse').style.display = FCKConfig.FlashBrowser ? '' : 'none' ; // Set the actual uploader URL. if ( FCKConfig.FlashUpload ) GetE('frmUpload').action = FCKConfig.FlashUploadURL ; dialog.SetAutoSize( true ) ; // Activate the "OK" button. dialog.SetOkButton( true ) ; SelectField( 'txtUrl' ) ; } function LoadSelection() { if ( ! oEmbed ) return ; GetE('txtUrl').value = GetAttribute( oEmbed, 'src', '' ) ; GetE('txtWidth').value = GetAttribute( oEmbed, 'width', '' ) ; GetE('txtHeight').value = GetAttribute( oEmbed, 'height', '' ) ; // Get Advances Attributes GetE('txtAttId').value = oEmbed.id ; GetE('chkAutoPlay').checked = GetAttribute( oEmbed, 'play', 'true' ) == 'true' ; GetE('chkLoop').checked = GetAttribute( oEmbed, 'loop', 'true' ) == 'true' ; GetE('chkMenu').checked = GetAttribute( oEmbed, 'menu', 'true' ) == 'true' ; GetE('cmbScale').value = GetAttribute( oEmbed, 'scale', '' ).toLowerCase() ; GetE('txtAttTitle').value = oEmbed.title ; if ( oEditor.FCKBrowserInfo.IsIE ) { GetE('txtAttClasses').value = oEmbed.getAttribute('className') || '' ; GetE('txtAttStyle').value = oEmbed.style.cssText ; } else { GetE('txtAttClasses').value = oEmbed.getAttribute('class',2) || '' ; GetE('txtAttStyle').value = oEmbed.getAttribute('style',2) || '' ; } UpdatePreview() ; } //#### The OK button was hit. function Ok() { if ( GetE('txtUrl').value.length == 0 ) { dialog.SetSelectedTab( 'Info' ) ; GetE('txtUrl').focus() ; alert( oEditor.FCKLang.DlgAlertUrl ) ; return false ; } oEditor.FCKUndo.SaveUndoStep() ; if ( !oEmbed ) { oEmbed = FCK.EditorDocument.createElement( 'EMBED' ) ; oFakeImage = null ; } UpdateEmbed( oEmbed ) ; if ( !oFakeImage ) { oFakeImage = oEditor.FCKDocumentProcessor_CreateFakeImage( 'FCK__Flash', oEmbed ) ; oFakeImage.setAttribute( '_fckflash', 'true', 0 ) ; oFakeImage = FCK.InsertElement( oFakeImage ) ; } oEditor.FCKEmbedAndObjectProcessor.RefreshView( oFakeImage, oEmbed ) ; return true ; } function UpdateEmbed( e ) { SetAttribute( e, 'type' , 'application/x-shockwave-flash' ) ; SetAttribute( e, 'pluginspage' , 'http://www.macromedia.com/go/getflashplayer' ) ; SetAttribute( e, 'src', GetE('txtUrl').value ) ; SetAttribute( e, "width" , GetE('txtWidth').value ) ; SetAttribute( e, "height", GetE('txtHeight').value ) ; // Advances Attributes SetAttribute( e, 'id' , GetE('txtAttId').value ) ; SetAttribute( e, 'scale', GetE('cmbScale').value ) ; SetAttribute( e, 'play', GetE('chkAutoPlay').checked ? 'true' : 'false' ) ; SetAttribute( e, 'loop', GetE('chkLoop').checked ? 'true' : 'false' ) ; SetAttribute( e, 'menu', GetE('chkMenu').checked ? 'true' : 'false' ) ; SetAttribute( e, 'title' , GetE('txtAttTitle').value ) ; if ( oEditor.FCKBrowserInfo.IsIE ) { SetAttribute( e, 'className', GetE('txtAttClasses').value ) ; e.style.cssText = GetE('txtAttStyle').value ; } else { SetAttribute( e, 'class', GetE('txtAttClasses').value ) ; SetAttribute( e, 'style', GetE('txtAttStyle').value ) ; } } var ePreview ; function SetPreviewElement( previewEl ) { ePreview = previewEl ; if ( GetE('txtUrl').value.length > 0 ) UpdatePreview() ; } function UpdatePreview() { if ( !ePreview ) return ; while ( ePreview.firstChild ) ePreview.removeChild( ePreview.firstChild ) ; if ( GetE('txtUrl').value.length == 0 ) ePreview.innerHTML = '&nbsp;' ; else { var oDoc = ePreview.ownerDocument || ePreview.document ; var e = oDoc.createElement( 'EMBED' ) ; SetAttribute( e, 'src', GetE('txtUrl').value ) ; SetAttribute( e, 'type', 'application/x-shockwave-flash' ) ; SetAttribute( e, 'width', '100%' ) ; SetAttribute( e, 'height', '100%' ) ; ePreview.appendChild( e ) ; } } // <embed id="ePreview" src="fck_flash/claims.swf" width="100%" height="100%" style="visibility:hidden" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"> function BrowseServer() { OpenFileBrowser( FCKConfig.FlashBrowserURL, FCKConfig.FlashBrowserWindowWidth, FCKConfig.FlashBrowserWindowHeight ) ; } function SetUrl( url, width, height ) { GetE('txtUrl').value = url ; if ( width ) GetE('txtWidth').value = width ; if ( height ) GetE('txtHeight').value = height ; UpdatePreview() ; dialog.SetSelectedTab( 'Info' ) ; } function OnUploadCompleted( errorNumber, fileUrl, fileName, customMsg ) { // Remove animation window.parent.Throbber.Hide() ; GetE( 'divUpload' ).style.display = '' ; switch ( errorNumber ) { case 0 : // No errors alert( 'Your file has been successfully uploaded' ) ; break ; case 1 : // Custom error alert( customMsg ) ; return ; case 101 : // Custom warning alert( customMsg ) ; break ; case 201 : alert( 'A file with the same name is already available. The uploaded file has been renamed to "' + fileName + '"' ) ; break ; case 202 : alert( 'Invalid file type' ) ; return ; case 203 : alert( "Security error. You probably don't have enough permissions to upload. Please check your server." ) ; return ; case 500 : alert( 'The connector is disabled' ) ; break ; default : alert( 'Error on file upload. Error number: ' + errorNumber ) ; return ; } SetUrl( fileUrl ) ; GetE('frmUpload').reset() ; } var oUploadAllowedExtRegex = new RegExp( FCKConfig.FlashUploadAllowedExtensions, 'i' ) ; var oUploadDeniedExtRegex = new RegExp( FCKConfig.FlashUploadDeniedExtensions, 'i' ) ; function CheckUpload() { var sFile = GetE('txtUploadFile').value ; if ( sFile.length == 0 ) { alert( 'Please select a file to upload' ) ; return false ; } if ( ( FCKConfig.FlashUploadAllowedExtensions.length > 0 && !oUploadAllowedExtRegex.test( sFile ) ) || ( FCKConfig.FlashUploadDeniedExtensions.length > 0 && oUploadDeniedExtRegex.test( sFile ) ) ) { OnUploadCompleted( 202 ) ; return false ; } // Show animation window.parent.Throbber.Show( 100 ) ; GetE( 'divUpload' ).style.display = 'none' ; return true ; }
10npsite
trunk/guanli/system/fckeditor/editor/dialog/fck_flash/fck_flash.js
JavaScript
asf20
8,279
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <!-- * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Link dialog window. --> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" > <meta content="noindex, nofollow" name="robots" > <script src="common/fck_dialog_common.js" type="text/javascript"></script> <script type="text/javascript"> var oEditor = window.parent.InnerDialogLoaded() ; var FCK = oEditor.FCK ; var FCKLang = oEditor.FCKLang ; var FCKConfig = oEditor.FCKConfig ; //#### Dialog Tabs // Set the dialog tabs. window.parent.AddTab( 'General' , FCKLang.DlgDocGeneralTab ) ; window.parent.AddTab( 'Background' , FCKLang.DlgDocBackTab ) ; window.parent.AddTab( 'Colors' , FCKLang.DlgDocColorsTab ) ; window.parent.AddTab( 'Meta' , FCKLang.DlgDocMetaTab ) ; // Function called when a dialog tag is selected. function OnDialogTabChange( tabCode ) { ShowE( 'divGeneral' , ( tabCode == 'General' ) ) ; ShowE( 'divBackground' , ( tabCode == 'Background' ) ) ; ShowE( 'divColors' , ( tabCode == 'Colors' ) ) ; ShowE( 'divMeta' , ( tabCode == 'Meta' ) ) ; ShowE( 'ePreview' , ( tabCode == 'Background' || tabCode == 'Colors' ) ) ; } //#### Get Base elements from the document: BEGIN // The HTML element of the document. var oHTML = FCK.EditorDocument.getElementsByTagName('html')[0] ; // The HEAD element of the document. var oHead = oHTML.getElementsByTagName('head')[0] ; var oBody = FCK.EditorDocument.body ; // This object contains all META tags defined in the document. var oMetaTags = new Object() ; // Get all META tags defined in the document. AppendMetaCollection( oMetaTags, oHead.getElementsByTagName('meta') ) ; AppendMetaCollection( oMetaTags, oHead.getElementsByTagName('fck:meta') ) ; function AppendMetaCollection( targetObject, metaCollection ) { // Loop throw all METAs and put it in the HashTable. for ( var i = 0 ; i < metaCollection.length ; i++ ) { // Try to get the "name" attribute. var sName = GetAttribute( metaCollection[i], 'name', GetAttribute( metaCollection[i], '___fcktoreplace:name', '' ) ) ; // If no "name", try with the "http-equiv" attribute. if ( sName.length == 0 ) { if ( oEditor.FCKBrowserInfo.IsIE ) { // Get the http-equiv value from the outerHTML. var oHttpEquivMatch = metaCollection[i].outerHTML.match( oEditor.FCKRegexLib.MetaHttpEquiv ) ; if ( oHttpEquivMatch ) sName = oHttpEquivMatch[1] ; } else sName = GetAttribute( metaCollection[i], 'http-equiv', '' ) ; } if ( sName.length > 0 ) targetObject[ sName.toLowerCase() ] = metaCollection[i] ; } } //#### END // Set a META tag in the document. function SetMetadata( name, content, isHttp ) { if ( content.length == 0 ) { RemoveMetadata( name ) ; return ; } var oMeta = oMetaTags[ name.toLowerCase() ] ; if ( !oMeta ) { oMeta = oHead.appendChild( FCK.EditorDocument.createElement('META') ) ; if ( isHttp ) SetAttribute( oMeta, 'http-equiv', name ) ; else { // On IE, it is not possible to set the "name" attribute of the META tag. // So a temporary attribute is used and it is replaced when getting the // editor's HTML/XHTML value. This is sad, I know :( if ( oEditor.FCKBrowserInfo.IsIE ) SetAttribute( oMeta, '___fcktoreplace:name', name ) ; else SetAttribute( oMeta, 'name', name ) ; } oMetaTags[ name.toLowerCase() ] = oMeta ; } SetAttribute( oMeta, 'content', content ) ; // oMeta.content = content ; } function RemoveMetadata( name ) { var oMeta = oMetaTags[ name.toLowerCase() ] ; if ( oMeta && oMeta != null ) { oMeta.parentNode.removeChild( oMeta ) ; oMetaTags[ name.toLowerCase() ] = null ; } } function GetMetadata( name ) { var oMeta = oMetaTags[ name.toLowerCase() ] ; if ( oMeta && oMeta != null ) return oMeta.getAttribute( 'content', 2 ) ; else return '' ; } window.onload = function () { // Show/Hide the "Browse Server" button. GetE('tdBrowse').style.display = oEditor.FCKConfig.ImageBrowser ? "" : "none"; // First of all, translate the dialog box texts oEditor.FCKLanguageManager.TranslatePage( document ) ; FillFields() ; UpdatePreview() ; // Show the "Ok" button. window.parent.SetOkButton( true ) ; window.parent.SetAutoSize( true ) ; } function FillFields() { // ### General Info GetE('txtPageTitle').value = FCK.EditorDocument.title ; GetE('selDirection').value = GetAttribute( oHTML, 'dir', '' ) ; GetE('txtLang').value = GetAttribute( oHTML, 'xml:lang', GetAttribute( oHTML, 'lang', '' ) ) ; // "xml:lang" takes precedence to "lang". // Character Set Encoding. // if ( oEditor.FCKBrowserInfo.IsIE ) // var sCharSet = FCK.EditorDocument.charset ; // else var sCharSet = GetMetadata( 'Content-Type' ) ; if ( sCharSet != null && sCharSet.length > 0 ) { // if ( !oEditor.FCKBrowserInfo.IsIE ) sCharSet = sCharSet.match( /[^=]*$/ ) ; GetE('selCharSet').value = sCharSet ; if ( GetE('selCharSet').selectedIndex == -1 ) { GetE('selCharSet').value = '...' ; GetE('txtCustomCharSet').value = sCharSet ; CheckOther( GetE('selCharSet'), 'txtCustomCharSet' ) ; } } // Document Type. if ( FCK.DocTypeDeclaration && FCK.DocTypeDeclaration.length > 0 ) { GetE('selDocType').value = FCK.DocTypeDeclaration ; if ( GetE('selDocType').selectedIndex == -1 ) { GetE('selDocType').value = '...' ; GetE('txtDocType').value = FCK.DocTypeDeclaration ; CheckOther( GetE('selDocType'), 'txtDocType' ) ; } } // Document Type. GetE('chkIncXHTMLDecl').checked = ( FCK.XmlDeclaration && FCK.XmlDeclaration.length > 0 ) ; // ### Background GetE('txtBackColor').value = GetAttribute( oBody, 'bgColor' , '' ) ; GetE('txtBackImage').value = GetAttribute( oBody, 'background' , '' ) ; GetE('chkBackNoScroll').checked = ( GetAttribute( oBody, 'bgProperties', '' ).toLowerCase() == 'fixed' ) ; // ### Colors GetE('txtColorText').value = GetAttribute( oBody, 'text' , '' ) ; GetE('txtColorLink').value = GetAttribute( oBody, 'link' , '' ) ; GetE('txtColorVisited').value = GetAttribute( oBody, 'vLink' , '' ) ; GetE('txtColorActive').value = GetAttribute( oBody, 'aLink' , '' ) ; // ### Margins GetE('txtMarginTop').value = GetAttribute( oBody, 'topMargin' , '' ) ; GetE('txtMarginLeft').value = GetAttribute( oBody, 'leftMargin' , '' ) ; GetE('txtMarginRight').value = GetAttribute( oBody, 'rightMargin' , '' ) ; GetE('txtMarginBottom').value = GetAttribute( oBody, 'bottomMargin' , '' ) ; // ### Meta Data GetE('txtMetaKeywords').value = GetMetadata( 'keywords' ) ; GetE('txtMetaDescription').value = GetMetadata( 'description' ) ; GetE('txtMetaAuthor').value = GetMetadata( 'author' ) ; GetE('txtMetaCopyright').value = GetMetadata( 'copyright' ) ; } // Called when the "Ok" button is clicked. function Ok() { // ### General Info FCK.EditorDocument.title = GetE('txtPageTitle').value ; var oHTML = FCK.EditorDocument.getElementsByTagName('html')[0] ; SetAttribute( oHTML, 'dir' , GetE('selDirection').value ) ; SetAttribute( oHTML, 'lang' , GetE('txtLang').value ) ; SetAttribute( oHTML, 'xml:lang' , GetE('txtLang').value ) ; // Character Set Enconding. var sCharSet = GetE('selCharSet').value ; if ( sCharSet == '...' ) sCharSet = GetE('txtCustomCharSet').value ; if ( sCharSet.length > 0 ) sCharSet = 'text/html; charset=' + sCharSet ; // if ( oEditor.FCKBrowserInfo.IsIE ) // FCK.EditorDocument.charset = sCharSet ; // else SetMetadata( 'Content-Type', sCharSet, true ) ; // Document Type var sDocType = GetE('selDocType').value ; if ( sDocType == '...' ) sDocType = GetE('txtDocType').value ; FCK.DocTypeDeclaration = sDocType ; // XHTML Declarations. if ( GetE('chkIncXHTMLDecl').checked ) { if ( sCharSet.length == 0 ) sCharSet = 'utf-8' ; FCK.XmlDeclaration = '<' + '?xml version="1.0" encoding="' + sCharSet + '"?>' ; SetAttribute( oHTML, 'xmlns', 'http://www.w3.org/1999/xhtml' ) ; } else { FCK.XmlDeclaration = null ; oHTML.removeAttribute( 'xmlns', 0 ) ; } // ### Background SetAttribute( oBody, 'bgcolor' , GetE('txtBackColor').value ) ; SetAttribute( oBody, 'background' , GetE('txtBackImage').value ) ; SetAttribute( oBody, 'bgproperties' , GetE('chkBackNoScroll').checked ? 'fixed' : '' ) ; // ### Colors SetAttribute( oBody, 'text' , GetE('txtColorText').value ) ; SetAttribute( oBody, 'link' , GetE('txtColorLink').value ) ; SetAttribute( oBody, 'vlink', GetE('txtColorVisited').value ) ; SetAttribute( oBody, 'alink', GetE('txtColorActive').value ) ; // ### Margins SetAttribute( oBody, 'topmargin' , GetE('txtMarginTop').value ) ; SetAttribute( oBody, 'leftmargin' , GetE('txtMarginLeft').value ) ; SetAttribute( oBody, 'rightmargin' , GetE('txtMarginRight').value ) ; SetAttribute( oBody, 'bottommargin' , GetE('txtMarginBottom').value ) ; // ### Meta data SetMetadata( 'keywords' , GetE('txtMetaKeywords').value ) ; SetMetadata( 'description' , GetE('txtMetaDescription').value ) ; SetMetadata( 'author' , GetE('txtMetaAuthor').value ) ; SetMetadata( 'copyright' , GetE('txtMetaCopyright').value ) ; return true ; } var bPreviewIsLoaded = false ; var oPreviewWindow ; var oPreviewBody ; // Called by the Preview page when loaded. function OnPreviewLoad( previewWindow, previewBody ) { oPreviewWindow = previewWindow ; oPreviewBody = previewBody ; bPreviewIsLoaded = true ; UpdatePreview() ; } function UpdatePreview() { if ( !bPreviewIsLoaded ) return ; // ### Background SetAttribute( oPreviewBody, 'bgcolor' , GetE('txtBackColor').value ) ; SetAttribute( oPreviewBody, 'background' , GetE('txtBackImage').value ) ; SetAttribute( oPreviewBody, 'bgproperties' , GetE('chkBackNoScroll').checked ? 'fixed' : '' ) ; // ### Colors SetAttribute( oPreviewBody, 'text', GetE('txtColorText').value ) ; oPreviewWindow.SetLinkColor( GetE('txtColorLink').value ) ; oPreviewWindow.SetVisitedColor( GetE('txtColorVisited').value ) ; oPreviewWindow.SetActiveColor( GetE('txtColorActive').value ) ; } function CheckOther( combo, txtField ) { var bNotOther = ( combo.value != '...' ) ; GetE(txtField).style.backgroundColor = ( bNotOther ? '#cccccc' : '' ) ; GetE(txtField).disabled = bNotOther ; } function SetColor( inputId, color ) { GetE( inputId ).value = color + '' ; UpdatePreview() ; } function SelectBackColor( color ) { SetColor('txtBackColor', color ) ; } function SelectColorText( color ) { SetColor('txtColorText', color ) ; } function SelectColorLink( color ) { SetColor('txtColorLink', color ) ; } function SelectColorVisited( color ) { SetColor('txtColorVisited', color ) ; } function SelectColorActive( color ) { SetColor('txtColorActive', color ) ; } function SelectColor( wich ) { switch ( wich ) { case 'Back' : oEditor.FCKDialog.OpenDialog( 'FCKDialog_Color', FCKLang.DlgColorTitle, 'dialog/fck_colorselector.html', 410, 320, SelectBackColor ) ; return ; case 'ColorText' : oEditor.FCKDialog.OpenDialog( 'FCKDialog_Color', FCKLang.DlgColorTitle, 'dialog/fck_colorselector.html', 410, 320, SelectColorText ) ; return ; case 'ColorLink' : oEditor.FCKDialog.OpenDialog( 'FCKDialog_Color', FCKLang.DlgColorTitle, 'dialog/fck_colorselector.html', 410, 320, SelectColorLink ) ; return ; case 'ColorVisited' : oEditor.FCKDialog.OpenDialog( 'FCKDialog_Color', FCKLang.DlgColorTitle, 'dialog/fck_colorselector.html', 410, 320, SelectColorVisited ) ; return ; case 'ColorActive' : oEditor.FCKDialog.OpenDialog( 'FCKDialog_Color', FCKLang.DlgColorTitle, 'dialog/fck_colorselector.html', 410, 320, SelectColorActive ) ; return ; } } function BrowseServerBack() { OpenFileBrowser( FCKConfig.ImageBrowserURL, FCKConfig.ImageBrowserWindowWidth, FCKConfig.ImageBrowserWindowHeight ) ; } function SetUrl( url ) { GetE('txtBackImage').value = url ; UpdatePreview() ; } </script> </head> <body style="overflow: hidden"> <table cellspacing="0" cellpadding="0" width="100%" border="0" style="height: 100%"> <tr> <td valign="top" style="height: 100%"> <div id="divGeneral"> <span fcklang="DlgDocPageTitle">Page Title</span><br /> <input id="txtPageTitle" style="width: 100%" type="text" /> <br /> <table cellspacing="0" cellpadding="0" border="0"> <tr> <td> <span fcklang="DlgDocLangDir">Language Direction</span><br /> <select id="selDirection"> <option value="" selected="selected"></option> <option value="ltr" fcklang="DlgDocLangDirLTR">Left to Right (LTR)</option> <option value="rtl" fcklang="DlgDocLangDirRTL">Right to Left (RTL)</option> </select> </td> <td> &nbsp;&nbsp;&nbsp;</td> <td> <span fcklang="DlgDocLangCode">Language Code</span><br /> <input id="txtLang" type="text" /> </td> </tr> </table> <br /> <table cellspacing="0" cellpadding="0" width="100%" border="0"> <tr> <td style="white-space: nowrap"> <span fcklang="DlgDocCharSet">Character Set Encoding</span><br /> <select id="selCharSet" onchange="CheckOther( this, 'txtCustomCharSet' );"> <option value="" selected="selected"></option> <option value="us-ascii">ASCII</option> <option fcklang="DlgDocCharSetCE" value="iso-8859-2">Central European</option> <option fcklang="DlgDocCharSetCT" value="big5">Chinese Traditional (Big5)</option> <option fcklang="DlgDocCharSetCR" value="iso-8859-5">Cyrillic</option> <option fcklang="DlgDocCharSetGR" value="iso-8859-7">Greek</option> <option fcklang="DlgDocCharSetJP" value="iso-2022-jp">Japanese</option> <option fcklang="DlgDocCharSetKR" value="iso-2022-kr">Korean</option> <option fcklang="DlgDocCharSetTR" value="iso-8859-9">Turkish</option> <option fcklang="DlgDocCharSetUN" value="utf-8">Unicode (UTF-8)</option> <option fcklang="DlgDocCharSetWE" value="iso-8859-1">Western European</option> <option fcklang="DlgOpOther" value="...">&lt;Other&gt;</option> </select> </td> <td> &nbsp;&nbsp;&nbsp;</td> <td width="100%"> <span fcklang="DlgDocCharSetOther">Other Character Set Encoding</span><br /> <input id="txtCustomCharSet" style="width: 100%; background-color: #cccccc" disabled="disabled" type="text" /> </td> </tr> <tr> <td colspan="3"> &nbsp;</td> </tr> <tr> <td nowrap="nowrap"> <span fcklang="DlgDocDocType">Document Type Heading</span><br /> <select id="selDocType" onchange="CheckOther( this, 'txtDocType' );"> <option value="" selected="selected"></option> <option value='&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt;'>HTML 4.01 Transitional</option> <option value='&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt;'> HTML 4.01 Strict</option> <option value='&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd"&gt;'> HTML 4.01 Frameset</option> <option value='&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;'> XHTML 1.0 Transitional</option> <option value='&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;'> XHTML 1.0 Strict</option> <option value='&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"&gt;'> XHTML 1.0 Frameset</option> <option value='&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"&gt;'> XHTML 1.1</option> <option value='&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"&gt;'>HTML 3.2</option> <option value='&lt;!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"&gt;'>HTML 2.0</option> <option value="..." fcklang="DlgOpOther">&lt;Other&gt;</option> </select> </td> <td> </td> <td width="100%"> <span fcklang="DlgDocDocTypeOther">Other Document Type Heading</span><br /> <input id="txtDocType" style="width: 100%; background-color: #cccccc" disabled="disabled" type="text" /> </td> </tr> </table> <br /> <input id="chkIncXHTMLDecl" type="checkbox" /> <label for="chkIncXHTMLDecl" fcklang="DlgDocIncXHTML"> Include XHTML Declarations</label> </div> <div id="divBackground" style="display: none"> <span fcklang="DlgDocBgColor">Background Color</span><br /> <input id="txtBackColor" type="text" onchange="UpdatePreview();" onkeyup="UpdatePreview();" />&nbsp;<input id="btnSelBackColor" onclick="SelectColor( 'Back' )" type="button" value="Select..." fcklang="DlgCellBtnSelect" /><br /> <br /> <span fcklang="DlgDocBgImage">Background Image URL</span><br /> <table cellspacing="0" cellpadding="0" width="100%" border="0"> <tr> <td width="100%"> <input id="txtBackImage" style="width: 100%" type="text" onchange="UpdatePreview();" onkeyup="UpdatePreview();" /></td> <td id="tdBrowse" nowrap="nowrap"> &nbsp;<input id="btnBrowse" onclick="BrowseServerBack();" type="button" fcklang="DlgBtnBrowseServer" value="Browse Server" /></td> </tr> </table> <input id="chkBackNoScroll" type="checkbox" onclick="UpdatePreview();" /> <label for="chkBackNoScroll" fcklang="DlgDocBgNoScroll"> Nonscrolling Background</label> </div> <div id="divColors" style="display: none"> <table cellspacing="0" cellpadding="0" width="100%" border="0"> <tr> <td> <span fcklang="DlgDocCText">Text</span><br /> <input id="txtColorText" type="text" onchange="UpdatePreview();" onkeyup="UpdatePreview();" /><input onclick="SelectColor( 'ColorText' )" type="button" value="Select..." fcklang="DlgCellBtnSelect" /> <br /> <span fcklang="DlgDocCLink">Link</span><br /> <input id="txtColorLink" type="text" onchange="UpdatePreview();" onkeyup="UpdatePreview();" /><input onclick="SelectColor( 'ColorLink' )" type="button" value="Select..." fcklang="DlgCellBtnSelect" /> <br /> <span fcklang="DlgDocCVisited">Visited Link</span><br /> <input id="txtColorVisited" type="text" onchange="UpdatePreview();" onkeyup="UpdatePreview();" /><input onclick="SelectColor( 'ColorVisited' )" type="button" value="Select..." fcklang="DlgCellBtnSelect" /> <br /> <span fcklang="DlgDocCActive">Active Link</span><br /> <input id="txtColorActive" type="text" onchange="UpdatePreview();" onkeyup="UpdatePreview();" /><input onclick="SelectColor( 'ColorActive' )" type="button" value="Select..." fcklang="DlgCellBtnSelect" /> </td> <td valign="middle" align="center"> <table cellspacing="2" cellpadding="0" border="0"> <tr> <td> <span fcklang="DlgDocMargins">Page Margins</span></td> </tr> <tr> <td style="border: #000000 1px solid; padding: 5px"> <table cellpadding="0" cellspacing="0" border="0" dir="ltr"> <tr> <td align="center" colspan="3"> <span fcklang="DlgDocMaTop">Top</span><br /> <input id="txtMarginTop" type="text" size="3" /> </td> </tr> <tr> <td align="left"> <span fcklang="DlgDocMaLeft">Left</span><br /> <input id="txtMarginLeft" type="text" size="3" /> </td> <td> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td> <td align="right"> <span fcklang="DlgDocMaRight">Right</span><br /> <input id="txtMarginRight" type="text" size="3" /> </td> </tr> <tr> <td align="center" colspan="3"> <span fcklang="DlgDocMaBottom">Bottom</span><br /> <input id="txtMarginBottom" type="text" size="3" /> </td> </tr> </table> </td> </tr> </table> </td> </tr> </table> </div> <div id="divMeta" style="display: none"> <span fcklang="DlgDocMeIndex">Document Indexing Keywords (comma separated)</span><br /> <textarea id="txtMetaKeywords" style="width: 100%" rows="2" cols="20"></textarea> <br /> <span fcklang="DlgDocMeDescr">Document Description</span><br /> <textarea id="txtMetaDescription" style="width: 100%" rows="4" cols="20"></textarea> <br /> <span fcklang="DlgDocMeAuthor">Author</span><br /> <input id="txtMetaAuthor" style="width: 100%" type="text" /><br /> <br /> <span fcklang="DlgDocMeCopy">Copyright</span><br /> <input id="txtMetaCopyright" type="text" style="width: 100%" /> </div> </td> </tr> <tr id="ePreview" style="display: none"> <td> <span fcklang="DlgDocPreview">Preview</span><br /> <iframe id="frmPreview" src="fck_docprops/fck_document_preview.html" width="100%" height="100"></iframe> </td> </tr> </table> </body> </html>
10npsite
trunk/guanli/system/fckeditor/editor/dialog/fck_docprops.html
HTML
asf20
22,602
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Plugin to insert "Placeholders" in the editor. */ // Register the related command. FCKCommands.RegisterCommand( 'Placeholder', new FCKDialogCommand( 'Placeholder', FCKLang.PlaceholderDlgTitle, FCKPlugins.Items['placeholder'].Path + 'fck_placeholder.html', 340, 160 ) ) ; // Create the "Plaholder" toolbar button. var oPlaceholderItem = new FCKToolbarButton( 'Placeholder', FCKLang.PlaceholderBtn ) ; oPlaceholderItem.IconPath = FCKPlugins.Items['placeholder'].Path + 'placeholder.gif' ; FCKToolbarItems.RegisterItem( 'Placeholder', oPlaceholderItem ) ; // The object used for all Placeholder operations. var FCKPlaceholders = new Object() ; // Add a new placeholder at the actual selection. FCKPlaceholders.Add = function( name ) { var oSpan = FCK.InsertElement( 'span' ) ; this.SetupSpan( oSpan, name ) ; } FCKPlaceholders.SetupSpan = function( span, name ) { span.innerHTML = '[[ ' + name + ' ]]' ; span.style.backgroundColor = '#ffff00' ; span.style.color = '#000000' ; if ( FCKBrowserInfo.IsGecko ) span.style.cursor = 'default' ; span._fckplaceholder = name ; span.contentEditable = false ; // To avoid it to be resized. span.onresizestart = function() { FCK.EditorWindow.event.returnValue = false ; return false ; } } // On Gecko we must do this trick so the user select all the SPAN when clicking on it. FCKPlaceholders._SetupClickListener = function() { FCKPlaceholders._ClickListener = function( e ) { if ( e.target.tagName == 'SPAN' && e.target._fckplaceholder ) FCKSelection.SelectNode( e.target ) ; } FCK.EditorDocument.addEventListener( 'click', FCKPlaceholders._ClickListener, true ) ; } // Open the Placeholder dialog on double click. FCKPlaceholders.OnDoubleClick = function( span ) { if ( span.tagName == 'SPAN' && span._fckplaceholder ) FCKCommands.GetCommand( 'Placeholder' ).Execute() ; } FCK.RegisterDoubleClickHandler( FCKPlaceholders.OnDoubleClick, 'SPAN' ) ; // Check if a Placholder name is already in use. FCKPlaceholders.Exist = function( name ) { var aSpans = FCK.EditorDocument.getElementsByTagName( 'SPAN' ) ; for ( var i = 0 ; i < aSpans.length ; i++ ) { if ( aSpans[i]._fckplaceholder == name ) return true ; } return false ; } if ( FCKBrowserInfo.IsIE ) { FCKPlaceholders.Redraw = function() { if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG ) return ; var aPlaholders = FCK.EditorDocument.body.innerText.match( /\[\[[^\[\]]+\]\]/g ) ; if ( !aPlaholders ) return ; var oRange = FCK.EditorDocument.body.createTextRange() ; for ( var i = 0 ; i < aPlaholders.length ; i++ ) { if ( oRange.findText( aPlaholders[i] ) ) { var sName = aPlaholders[i].match( /\[\[\s*([^\]]*?)\s*\]\]/ )[1] ; oRange.pasteHTML( '<span style="color: #000000; background-color: #ffff00" contenteditable="false" _fckplaceholder="' + sName + '">' + aPlaholders[i] + '</span>' ) ; } } } } else { FCKPlaceholders.Redraw = function() { if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG ) return ; var oInteractor = FCK.EditorDocument.createTreeWalker( FCK.EditorDocument.body, NodeFilter.SHOW_TEXT, FCKPlaceholders._AcceptNode, true ) ; var aNodes = new Array() ; while ( ( oNode = oInteractor.nextNode() ) ) { aNodes[ aNodes.length ] = oNode ; } for ( var n = 0 ; n < aNodes.length ; n++ ) { var aPieces = aNodes[n].nodeValue.split( /(\[\[[^\[\]]+\]\])/g ) ; for ( var i = 0 ; i < aPieces.length ; i++ ) { if ( aPieces[i].length > 0 ) { if ( aPieces[i].indexOf( '[[' ) == 0 ) { var sName = aPieces[i].match( /\[\[\s*([^\]]*?)\s*\]\]/ )[1] ; var oSpan = FCK.EditorDocument.createElement( 'span' ) ; FCKPlaceholders.SetupSpan( oSpan, sName ) ; aNodes[n].parentNode.insertBefore( oSpan, aNodes[n] ) ; } else aNodes[n].parentNode.insertBefore( FCK.EditorDocument.createTextNode( aPieces[i] ) , aNodes[n] ) ; } } aNodes[n].parentNode.removeChild( aNodes[n] ) ; } FCKPlaceholders._SetupClickListener() ; } FCKPlaceholders._AcceptNode = function( node ) { if ( /\[\[[^\[\]]+\]\]/.test( node.nodeValue ) ) return NodeFilter.FILTER_ACCEPT ; else return NodeFilter.FILTER_SKIP ; } } FCK.Events.AttachEvent( 'OnAfterSetHTML', FCKPlaceholders.Redraw ) ; // We must process the SPAN tags to replace then with the real resulting value of the placeholder. FCKXHtml.TagProcessors['span'] = function( node, htmlNode ) { if ( htmlNode._fckplaceholder ) node = FCKXHtml.XML.createTextNode( '[[' + htmlNode._fckplaceholder + ']]' ) ; else FCKXHtml._AppendChildNodes( node, htmlNode, false ) ; return node ; }
10npsite
trunk/guanli/system/fckeditor/editor/plugins/placeholder/fckplugin.js
JavaScript
asf20
5,416
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Placholder Italian language file. */ FCKLang.PlaceholderBtn = 'Aggiungi/Modifica Placeholder' ; FCKLang.PlaceholderDlgTitle = 'Proprietà del Placeholder' ; FCKLang.PlaceholderDlgName = 'Nome del Placeholder' ; FCKLang.PlaceholderErrNoName = 'Digitare il nome del placeholder' ; FCKLang.PlaceholderErrNameInUse = 'Il nome inserito è già in uso' ;
10npsite
trunk/guanli/system/fckeditor/editor/plugins/placeholder/lang/it.js
JavaScript
asf20
993
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Placholder German language file. */ FCKLang.PlaceholderBtn = 'Einfügen/editieren Platzhalter' ; FCKLang.PlaceholderDlgTitle = 'Platzhalter Eigenschaften' ; FCKLang.PlaceholderDlgName = 'Platzhalter Name' ; FCKLang.PlaceholderErrNoName = 'Bitte den Namen des Platzhalters schreiben' ; FCKLang.PlaceholderErrNameInUse = 'Der angegebene Namen ist schon in Gebrauch' ;
10npsite
trunk/guanli/system/fckeditor/editor/plugins/placeholder/lang/de.js
JavaScript
asf20
1,010
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Placholder Polish language file. */ FCKLang.PlaceholderBtn = 'Wstaw/Edytuj nagłówek' ; FCKLang.PlaceholderDlgTitle = 'Właśności nagłówka' ; FCKLang.PlaceholderDlgName = 'Nazwa nagłówka' ; FCKLang.PlaceholderErrNoName = 'Proszę wprowadzić nazwę nagłówka' ; FCKLang.PlaceholderErrNameInUse = 'Podana nazwa jest już w użyciu' ;
10npsite
trunk/guanli/system/fckeditor/editor/plugins/placeholder/lang/pl.js
JavaScript
asf20
985
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Placeholder French language file. */ FCKLang.PlaceholderBtn = "Insérer/Modifier l'Espace réservé" ; FCKLang.PlaceholderDlgTitle = "Propriétés de l'Espace réservé" ; FCKLang.PlaceholderDlgName = "Nom de l'Espace réservé" ; FCKLang.PlaceholderErrNoName = "Veuillez saisir le nom de l'Espace réservé" ; FCKLang.PlaceholderErrNameInUse = "Ce nom est déjà utilisé" ;
10npsite
trunk/guanli/system/fckeditor/editor/plugins/placeholder/lang/fr.js
JavaScript
asf20
1,020
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Placholder English language file. */ FCKLang.PlaceholderBtn = 'Insert/Edit Placeholder' ; FCKLang.PlaceholderDlgTitle = 'Placeholder Properties' ; FCKLang.PlaceholderDlgName = 'Placeholder Name' ; FCKLang.PlaceholderErrNoName = 'Please type the placeholder name' ; FCKLang.PlaceholderErrNameInUse = 'The specified name is already in use' ;
10npsite
trunk/guanli/system/fckeditor/editor/plugins/placeholder/lang/en.js
JavaScript
asf20
984
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Placholder Spanish language file. */ FCKLang.PlaceholderBtn = 'Insertar/Editar contenedor' ; FCKLang.PlaceholderDlgTitle = 'Propiedades del contenedor ' ; FCKLang.PlaceholderDlgName = 'Nombre de contenedor' ; FCKLang.PlaceholderErrNoName = 'Por favor escriba el nombre de contenedor' ; FCKLang.PlaceholderErrNameInUse = 'El nombre especificado ya esta en uso' ;
10npsite
trunk/guanli/system/fckeditor/editor/plugins/placeholder/lang/es.js
JavaScript
asf20
1,006
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <!-- * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Placeholder Plugin. --> <html> <head> <title>Placeholder Properties</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta content="noindex, nofollow" name="robots"> <script src="../../dialog/common/fck_dialog_common.js" type="text/javascript"></script> <script language="javascript"> var dialog = window.parent ; var oEditor = dialog.InnerDialogLoaded() ; var FCKLang = oEditor.FCKLang ; var FCKPlaceholders = oEditor.FCKPlaceholders ; window.onload = function () { // First of all, translate the dialog box texts oEditor.FCKLanguageManager.TranslatePage( document ) ; LoadSelected() ; // Show the "Ok" button. dialog.SetOkButton( true ) ; // Select text field on load. SelectField( 'txtName' ) ; } var eSelected = dialog.Selection.GetSelectedElement() ; function LoadSelected() { if ( !eSelected ) return ; if ( eSelected.tagName == 'SPAN' && eSelected._fckplaceholder ) document.getElementById('txtName').value = eSelected._fckplaceholder ; else eSelected == null ; } function Ok() { var sValue = document.getElementById('txtName').value ; if ( eSelected && eSelected._fckplaceholder == sValue ) return true ; if ( sValue.length == 0 ) { alert( FCKLang.PlaceholderErrNoName ) ; return false ; } if ( FCKPlaceholders.Exist( sValue ) ) { alert( FCKLang.PlaceholderErrNameInUse ) ; return false ; } FCKPlaceholders.Add( sValue ) ; return true ; } </script> </head> <body scroll="no" style="OVERFLOW: hidden"> <table height="100%" cellSpacing="0" cellPadding="0" width="100%" border="0"> <tr> <td> <table cellSpacing="0" cellPadding="0" align="center" border="0"> <tr> <td> <span fckLang="PlaceholderDlgName">Placeholder Name</span><br> <input id="txtName" type="text"> </td> </tr> </table> </td> </tr> </table> </body> </html>
10npsite
trunk/guanli/system/fckeditor/editor/plugins/placeholder/fck_placeholder.html
HTML
asf20
2,669
var FCKDragTableHandler = { "_DragState" : 0, "_LeftCell" : null, "_RightCell" : null, "_MouseMoveMode" : 0, // 0 - find candidate cells for resizing, 1 - drag to resize "_ResizeBar" : null, "_OriginalX" : null, "_MinimumX" : null, "_MaximumX" : null, "_LastX" : null, "_TableMap" : null, "_doc" : document, "_IsInsideNode" : function( w, domNode, pos ) { var myCoords = FCKTools.GetWindowPosition( w, domNode ) ; var xMin = myCoords.x ; var yMin = myCoords.y ; var xMax = parseInt( xMin, 10 ) + parseInt( domNode.offsetWidth, 10 ) ; var yMax = parseInt( yMin, 10 ) + parseInt( domNode.offsetHeight, 10 ) ; if ( pos.x >= xMin && pos.x <= xMax && pos.y >= yMin && pos.y <= yMax ) return true; return false; }, "_GetBorderCells" : function( w, tableNode, tableMap, mouse ) { // Enumerate all the cells in the table. var cells = [] ; for ( var i = 0 ; i < tableNode.rows.length ; i++ ) { var r = tableNode.rows[i] ; for ( var j = 0 ; j < r.cells.length ; j++ ) cells.push( r.cells[j] ) ; } if ( cells.length < 1 ) return null ; // Get the cells whose right or left border is nearest to the mouse cursor's x coordinate. var minRxDist = null ; var lxDist = null ; var minYDist = null ; var rbCell = null ; var lbCell = null ; for ( var i = 0 ; i < cells.length ; i++ ) { var pos = FCKTools.GetWindowPosition( w, cells[i] ) ; var rightX = pos.x + parseInt( cells[i].clientWidth, 10 ) ; var rxDist = mouse.x - rightX ; var yDist = mouse.y - ( pos.y + ( cells[i].clientHeight / 2 ) ) ; if ( minRxDist == null || ( Math.abs( rxDist ) <= Math.abs( minRxDist ) && ( minYDist == null || Math.abs( yDist ) <= Math.abs( minYDist ) ) ) ) { minRxDist = rxDist ; minYDist = yDist ; rbCell = cells[i] ; } } /* var rowNode = FCKTools.GetElementAscensor( rbCell, "tr" ) ; var cellIndex = rbCell.cellIndex + 1 ; if ( cellIndex >= rowNode.cells.length ) return null ; lbCell = rowNode.cells.item( cellIndex ) ; */ var rowIdx = rbCell.parentNode.rowIndex ; var colIdx = FCKTableHandler._GetCellIndexSpan( tableMap, rowIdx, rbCell ) ; var colSpan = isNaN( rbCell.colSpan ) ? 1 : rbCell.colSpan ; lbCell = tableMap[rowIdx][colIdx + colSpan] ; if ( ! lbCell ) return null ; // Abort if too far from the border. lxDist = mouse.x - FCKTools.GetWindowPosition( w, lbCell ).x ; if ( lxDist < 0 && minRxDist < 0 && minRxDist < -2 ) return null ; if ( lxDist > 0 && minRxDist > 0 && lxDist > 3 ) return null ; return { "leftCell" : rbCell, "rightCell" : lbCell } ; }, "_GetResizeBarPosition" : function() { var row = FCKTools.GetElementAscensor( this._RightCell, "tr" ) ; return FCKTableHandler._GetCellIndexSpan( this._TableMap, row.rowIndex, this._RightCell ) ; }, "_ResizeBarMouseDownListener" : function( evt ) { if ( FCKDragTableHandler._LeftCell ) FCKDragTableHandler._MouseMoveMode = 1 ; if ( FCKBrowserInfo.IsIE ) FCKDragTableHandler._ResizeBar.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 50 ; else FCKDragTableHandler._ResizeBar.style.opacity = 0.5 ; FCKDragTableHandler._OriginalX = evt.clientX ; // Calculate maximum and minimum x-coordinate delta. var borderIndex = FCKDragTableHandler._GetResizeBarPosition() ; var offset = FCKDragTableHandler._GetIframeOffset(); var table = FCKTools.GetElementAscensor( FCKDragTableHandler._LeftCell, "table" ); var minX = null ; var maxX = null ; for ( var r = 0 ; r < FCKDragTableHandler._TableMap.length ; r++ ) { var leftCell = FCKDragTableHandler._TableMap[r][borderIndex - 1] ; var rightCell = FCKDragTableHandler._TableMap[r][borderIndex] ; var leftPosition = FCKTools.GetWindowPosition( FCK.EditorWindow, leftCell ) ; var rightPosition = FCKTools.GetWindowPosition( FCK.EditorWindow, rightCell ) ; var leftPadding = FCKDragTableHandler._GetCellPadding( table, leftCell ) ; var rightPadding = FCKDragTableHandler._GetCellPadding( table, rightCell ) ; if ( minX == null || leftPosition.x + leftPadding > minX ) minX = leftPosition.x + leftPadding ; if ( maxX == null || rightPosition.x + rightCell.clientWidth - rightPadding < maxX ) maxX = rightPosition.x + rightCell.clientWidth - rightPadding ; } FCKDragTableHandler._MinimumX = minX + offset.x ; FCKDragTableHandler._MaximumX = maxX + offset.x ; FCKDragTableHandler._LastX = null ; if (evt.preventDefault) evt.preventDefault(); else evt.returnValue = false; }, "_ResizeBarMouseUpListener" : function( evt ) { FCKDragTableHandler._MouseMoveMode = 0 ; FCKDragTableHandler._HideResizeBar() ; if ( FCKDragTableHandler._LastX == null ) return ; // Calculate the delta value. var deltaX = FCKDragTableHandler._LastX - FCKDragTableHandler._OriginalX ; // Then, build an array of current column width values. // This algorithm can be very slow if the cells have insane colSpan values. (e.g. colSpan=1000). var table = FCKTools.GetElementAscensor( FCKDragTableHandler._LeftCell, "table" ) ; var colArray = [] ; var tableMap = FCKDragTableHandler._TableMap ; for ( var i = 0 ; i < tableMap.length ; i++ ) { for ( var j = 0 ; j < tableMap[i].length ; j++ ) { var cell = tableMap[i][j] ; var width = FCKDragTableHandler._GetCellWidth( table, cell ) ; var colSpan = isNaN( cell.colSpan) ? 1 : cell.colSpan ; if ( colArray.length <= j ) colArray.push( { width : width / colSpan, colSpan : colSpan } ) ; else { var guessItem = colArray[j] ; if ( guessItem.colSpan > colSpan ) { guessItem.width = width / colSpan ; guessItem.colSpan = colSpan ; } } } } // Find out the equivalent column index of the two cells selected for resizing. colIndex = FCKDragTableHandler._GetResizeBarPosition() ; // Note that colIndex must be at least 1 here, so it's safe to subtract 1 from it. colIndex-- ; // Modify the widths in the colArray according to the mouse coordinate delta value. colArray[colIndex].width += deltaX ; colArray[colIndex + 1].width -= deltaX ; // Clear all cell widths, delete all <col> elements from the table. for ( var r = 0 ; r < table.rows.length ; r++ ) { var row = table.rows.item( r ) ; for ( var c = 0 ; c < row.cells.length ; c++ ) { var cell = row.cells.item( c ) ; cell.width = "" ; cell.style.width = "" ; } } var colElements = table.getElementsByTagName( "col" ) ; for ( var i = colElements.length - 1 ; i >= 0 ; i-- ) colElements[i].parentNode.removeChild( colElements[i] ) ; // Set new cell widths. var processedCells = [] ; for ( var i = 0 ; i < tableMap.length ; i++ ) { for ( var j = 0 ; j < tableMap[i].length ; j++ ) { var cell = tableMap[i][j] ; if ( cell._Processed ) continue ; if ( tableMap[i][j-1] != cell ) cell.width = colArray[j].width ; else cell.width = parseInt( cell.width, 10 ) + parseInt( colArray[j].width, 10 ) ; if ( tableMap[i][j+1] != cell ) { processedCells.push( cell ) ; cell._Processed = true ; } } } for ( var i = 0 ; i < processedCells.length ; i++ ) { if ( FCKBrowserInfo.IsIE ) processedCells[i].removeAttribute( '_Processed' ) ; else delete processedCells[i]._Processed ; } FCKDragTableHandler._LastX = null ; }, "_ResizeBarMouseMoveListener" : function( evt ) { if ( FCKDragTableHandler._MouseMoveMode == 0 ) return FCKDragTableHandler._MouseFindHandler( FCK, evt ) ; else return FCKDragTableHandler._MouseDragHandler( FCK, evt ) ; }, // Calculate the padding of a table cell. // It returns the value of paddingLeft + paddingRight of a table cell. // This function is used, in part, to calculate the width parameter that should be used for setting cell widths. // The equation in question is clientWidth = paddingLeft + paddingRight + width. // So that width = clientWidth - paddingLeft - paddingRight. // The return value of this function must be pixel accurate acorss all supported browsers, so be careful if you need to modify it. "_GetCellPadding" : function( table, cell ) { var attrGuess = parseInt( table.cellPadding, 10 ) * 2 ; var cssGuess = null ; if ( typeof( window.getComputedStyle ) == "function" ) { var styleObj = window.getComputedStyle( cell, null ) ; cssGuess = parseInt( styleObj.getPropertyValue( "padding-left" ), 10 ) + parseInt( styleObj.getPropertyValue( "padding-right" ), 10 ) ; } else cssGuess = parseInt( cell.currentStyle.paddingLeft, 10 ) + parseInt (cell.currentStyle.paddingRight, 10 ) ; var cssRuntime = cell.style.padding ; if ( isFinite( cssRuntime ) ) cssGuess = parseInt( cssRuntime, 10 ) * 2 ; else { cssRuntime = cell.style.paddingLeft ; if ( isFinite( cssRuntime ) ) cssGuess = parseInt( cssRuntime, 10 ) ; cssRuntime = cell.style.paddingRight ; if ( isFinite( cssRuntime ) ) cssGuess += parseInt( cssRuntime, 10 ) ; } attrGuess = parseInt( attrGuess, 10 ) ; cssGuess = parseInt( cssGuess, 10 ) ; if ( isNaN( attrGuess ) ) attrGuess = 0 ; if ( isNaN( cssGuess ) ) cssGuess = 0 ; return Math.max( attrGuess, cssGuess ) ; }, // Calculate the real width of the table cell. // The real width of the table cell is the pixel width that you can set to the width attribute of the table cell and after // that, the table cell should be of exactly the same width as before. // The real width of a table cell can be calculated as: // width = clientWidth - paddingLeft - paddingRight. "_GetCellWidth" : function( table, cell ) { var clientWidth = cell.clientWidth ; if ( isNaN( clientWidth ) ) clientWidth = 0 ; return clientWidth - this._GetCellPadding( table, cell ) ; }, "MouseMoveListener" : function( FCK, evt ) { if ( FCKDragTableHandler._MouseMoveMode == 0 ) return FCKDragTableHandler._MouseFindHandler( FCK, evt ) ; else return FCKDragTableHandler._MouseDragHandler( FCK, evt ) ; }, "_MouseFindHandler" : function( FCK, evt ) { if ( FCK.MouseDownFlag ) return ; var node = evt.srcElement || evt.target ; try { if ( ! node || node.nodeType != 1 ) { this._HideResizeBar() ; return ; } } catch ( e ) { this._HideResizeBar() ; return ; } // Since this function might be called from the editing area iframe or the outer fckeditor iframe, // the mouse point coordinates from evt.clientX/Y can have different reference points. // We need to resolve the mouse pointer position relative to the editing area iframe. var mouseX = evt.clientX ; var mouseY = evt.clientY ; if ( FCKTools.GetElementDocument( node ) == document ) { var offset = this._GetIframeOffset() ; mouseX -= offset.x ; mouseY -= offset.y ; } if ( this._ResizeBar && this._LeftCell ) { var leftPos = FCKTools.GetWindowPosition( FCK.EditorWindow, this._LeftCell ) ; var rightPos = FCKTools.GetWindowPosition( FCK.EditorWindow, this._RightCell ) ; var rxDist = mouseX - ( leftPos.x + this._LeftCell.clientWidth ) ; var lxDist = mouseX - rightPos.x ; var inRangeFlag = false ; if ( lxDist >= 0 && rxDist <= 0 ) inRangeFlag = true ; else if ( rxDist > 0 && lxDist <= 3 ) inRangeFlag = true ; else if ( lxDist < 0 && rxDist >= -2 ) inRangeFlag = true ; if ( inRangeFlag ) { this._ShowResizeBar( FCK.EditorWindow, FCKTools.GetElementAscensor( this._LeftCell, "table" ), { "x" : mouseX, "y" : mouseY } ) ; return ; } } var tagName = node.tagName.toLowerCase() ; if ( tagName != "table" && tagName != "td" && tagName != "th" ) { if ( this._LeftCell ) this._LeftCell = this._RightCell = this._TableMap = null ; this._HideResizeBar() ; return ; } node = FCKTools.GetElementAscensor( node, "table" ) ; var tableMap = FCKTableHandler._CreateTableMap( node ) ; var cellTuple = this._GetBorderCells( FCK.EditorWindow, node, tableMap, { "x" : mouseX, "y" : mouseY } ) ; if ( cellTuple == null ) { if ( this._LeftCell ) this._LeftCell = this._RightCell = this._TableMap = null ; this._HideResizeBar() ; } else { this._LeftCell = cellTuple["leftCell"] ; this._RightCell = cellTuple["rightCell"] ; this._TableMap = tableMap ; this._ShowResizeBar( FCK.EditorWindow, FCKTools.GetElementAscensor( this._LeftCell, "table" ), { "x" : mouseX, "y" : mouseY } ) ; } }, "_MouseDragHandler" : function( FCK, evt ) { var mouse = { "x" : evt.clientX, "y" : evt.clientY } ; // Convert mouse coordinates in reference to the outer iframe. var node = evt.srcElement || evt.target ; if ( FCKTools.GetElementDocument( node ) == FCK.EditorDocument ) { var offset = this._GetIframeOffset() ; mouse.x += offset.x ; mouse.y += offset.y ; } // Calculate the mouse position delta and see if we've gone out of range. if ( mouse.x >= this._MaximumX - 5 ) mouse.x = this._MaximumX - 5 ; if ( mouse.x <= this._MinimumX + 5 ) mouse.x = this._MinimumX + 5 ; var docX = mouse.x + FCKTools.GetScrollPosition( window ).X ; this._ResizeBar.style.left = ( docX - this._ResizeBar.offsetWidth / 2 ) + "px" ; this._LastX = mouse.x ; }, "_ShowResizeBar" : function( w, table, mouse ) { if ( this._ResizeBar == null ) { this._ResizeBar = this._doc.createElement( "div" ) ; var paddingBar = this._ResizeBar ; var paddingStyles = { 'position' : 'absolute', 'cursor' : 'e-resize' } ; if ( FCKBrowserInfo.IsIE ) paddingStyles.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=10,enabled=true)" ; else paddingStyles.opacity = 0.10 ; FCKDomTools.SetElementStyles( paddingBar, paddingStyles ) ; this._avoidStyles( paddingBar ); paddingBar.setAttribute('_fcktemp', true); this._doc.body.appendChild( paddingBar ) ; FCKTools.AddEventListener( paddingBar, "mousemove", this._ResizeBarMouseMoveListener ) ; FCKTools.AddEventListener( paddingBar, "mousedown", this._ResizeBarMouseDownListener ) ; FCKTools.AddEventListener( document, "mouseup", this._ResizeBarMouseUpListener ) ; FCKTools.AddEventListener( FCK.EditorDocument, "mouseup", this._ResizeBarMouseUpListener ) ; // IE doesn't let the tranparent part of the padding block to receive mouse events unless there's something inside. // So we need to create a spacer image to fill the block up. var filler = this._doc.createElement( "img" ) ; filler.setAttribute('_fcktemp', true); filler.border = 0 ; filler.src = FCKConfig.BasePath + "images/spacer.gif" ; filler.style.position = "absolute" ; paddingBar.appendChild( filler ) ; // Disable drag and drop, and selection for the filler image. var disabledListener = function( evt ) { if ( evt.preventDefault ) evt.preventDefault() ; else evt.returnValue = false ; } FCKTools.AddEventListener( filler, "dragstart", disabledListener ) ; FCKTools.AddEventListener( filler, "selectstart", disabledListener ) ; } var paddingBar = this._ResizeBar ; var offset = this._GetIframeOffset() ; var tablePos = this._GetTablePosition( w, table ) ; var barHeight = table.offsetHeight ; var barTop = offset.y + tablePos.y ; // Do not let the resize bar intrude into the toolbar area. if ( tablePos.y < 0 ) { barHeight += tablePos.y ; barTop -= tablePos.y ; } var bw = parseInt( table.border, 10 ) ; if ( isNaN( bw ) ) bw = 0 ; var cs = parseInt( table.cellSpacing, 10 ) ; if ( isNaN( cs ) ) cs = 0 ; var barWidth = Math.max( bw+100, cs+100 ) ; var paddingStyles = { 'top' : barTop + 'px', 'height' : barHeight + 'px', 'width' : barWidth + 'px', 'left' : ( offset.x + mouse.x + FCKTools.GetScrollPosition( w ).X - barWidth / 2 ) + 'px' } ; if ( FCKBrowserInfo.IsIE ) paddingBar.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 10 ; else paddingStyles.opacity = 0.1 ; FCKDomTools.SetElementStyles( paddingBar, paddingStyles ) ; var filler = paddingBar.getElementsByTagName( "img" )[0] ; FCKDomTools.SetElementStyles( filler, { width : paddingBar.offsetWidth + 'px', height : barHeight + 'px' } ) ; barWidth = Math.max( bw, cs, 3 ) ; var visibleBar = null ; if ( paddingBar.getElementsByTagName( "div" ).length < 1 ) { visibleBar = this._doc.createElement( "div" ) ; this._avoidStyles( visibleBar ); visibleBar.setAttribute('_fcktemp', true); paddingBar.appendChild( visibleBar ) ; } else visibleBar = paddingBar.getElementsByTagName( "div" )[0] ; FCKDomTools.SetElementStyles( visibleBar, { position : 'absolute', backgroundColor : 'blue', width : barWidth + 'px', height : barHeight + 'px', left : '50px', top : '0px' } ) ; }, "_HideResizeBar" : function() { if ( this._ResizeBar ) // IE bug: display : none does not hide the resize bar for some reason. // so set the position to somewhere invisible. FCKDomTools.SetElementStyles( this._ResizeBar, { top : '-100000px', left : '-100000px' } ) ; }, "_GetIframeOffset" : function () { return FCKTools.GetDocumentPosition( window, FCK.EditingArea.IFrame ) ; }, "_GetTablePosition" : function ( w, table ) { return FCKTools.GetWindowPosition( w, table ) ; }, "_avoidStyles" : function( element ) { FCKDomTools.SetElementStyles( element, { padding : '0', backgroundImage : 'none', border : '0' } ) ; }, "Reset" : function() { FCKDragTableHandler._LeftCell = FCKDragTableHandler._RightCell = FCKDragTableHandler._TableMap = null ; } }; FCK.Events.AttachEvent( "OnMouseMove", FCKDragTableHandler.MouseMoveListener ) ; FCK.Events.AttachEvent( "OnAfterSetHTML", FCKDragTableHandler.Reset ) ;
10npsite
trunk/guanli/system/fckeditor/editor/plugins/dragresizetable/fckplugin.js
JavaScript
asf20
18,298
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML lang="UTF-8"> <HEAD> <META http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <META http-equiv="Content-Language" content="UTF-8" /> <TITLE fcklang="DlgSyntaxHighLighterProperty">语法高亮代码属性</TITLE> <SCRIPT language="javascript" src="./dp.SyntaxHighlighter/Scripts/shCore.js"></SCRIPT> <SCRIPT language="javascript"> var oEditor = window.parent.InnerDialogLoaded() ; var FCKBrowserInfo = oEditor.FCKBrowserInfo; var FCKLang = oEditor.FCKLang ; var FCKHighLighter = oEditor.FCKHighLighter ; var usingTag = "DIV"; var usingFlag = "HighLighter"; //var SCRIPT_PATH = FCKConfig.PluginsPath + "highlighter/dp.SyntaxHighlighter/Scripts/"; var SCRIPT_PATH = "./dp.SyntaxHighlighter/Scripts/"; var PREFIX = "shBrush"; var POSTFIX = ".js"; var TypeMapper = { "php" : PREFIX + "Php" + POSTFIX , "javascript" : PREFIX + "JScript" + POSTFIX , "java" : PREFIX + "Java" + POSTFIX , "xml" : PREFIX + "Xml" + POSTFIX , "html" : PREFIX + "Xml" + POSTFIX , "c++" : PREFIX + "Cpp" + POSTFIX , "c#" : PREFIX + "CSharp" + POSTFIX , "css" : PREFIX + "Css" + POSTFIX , "delphi" : PREFIX + "Delphi" + POSTFIX , "python" : PREFIX + "Python" + POSTFIX , "ruby" : PREFIX + "Ruby" + POSTFIX , "sql" : PREFIX + "Sql" + POSTFIX , "vb" : PREFIX + "Vb" + POSTFIX }; window.onload = function () { // First of all, translate the dialog box texts oEditor.FCKLanguageManager.TranslatePage( document ) ; LoadSelected(); // Show the "Ok" button. window.parent.SetOkButton( true ) ; document.getElementById("code").focus(); } function Ok() { if(document.getElementById("codeType").value.length == 0) { alert("请选择一种语言"); return false; } if(document.getElementById("code").value.length==0) { alert("代码不能为空"); return false; } document.getElementById("code").value = document.getElementById("code").value .replace(/&/g, "&amp;") .replace(/</g, "&lt;") .replace(/>/g,'&gt;'); oEditor.FCKUndo.SaveUndoStep() ; //dp.SyntaxHighlighter.ClipboardSwf = SCRIPT_PATH + 'clipboard.swf'; var result = dp.SyntaxHighlighter.HighlightAll('code',1,0,0,1,0); var str = ""; for(key in result) { str += "<" + usingTag + " contentEditable='false' class='dp-highlighter'>"; str += result[key][0]; str += "</" + usingTag + ">"; str += "<" + usingTag + " contentEditable='false' class='"; str += result[key][2]; str += "' style='display:none'><pre>"; str += result[key][1]; str += "</pre></" + usingTag + ">"; } FCKHighLighter.Add( str ) ; return true ; } function createScript( type ) { var oScript = document.createElement("script"); var src = TypeMapper[type]; oScript.LANGUAGE = "javascript"; oScript.TYPE = "text/javascript"; oScript.src = SCRIPT_PATH + src; document.body.appendChild( oScript ); } function setCodeType( codeType ) { document.getElementById("code").className = codeType; createScript(codeType); } var eSelected = oEditor.FCKSelection.GetSelectedElement() ; function LoadSelected() { if ( !eSelected ) return ; if ( eSelected.tagName == usingTag && eSelected.className == usingFlag ) { var srcNode = null; if (FCKBrowserInfo.IsIE) { srcNode = eSelected.firstChild.nextSibling; } else { srcNode = eSelected.getElementsByTagName('div').item(2); } var language = srcNode.className; var codeTypeNum = document.getElementById("codeType").options.length; document.getElementById("code").className = language; createScript(language); for(var i=0;i<codeTypeNum;i++) { if(document.getElementById("codeType").options[i].value == language) { document.getElementById("codeType").options[i].selected = true; } } var codeContent = srcNode.innerHTML; var startInt, endInt; if (FCKBrowserInfo.IsIE) { startInt = 5; endInt = 6; } else { startInt = 6; endInt = 7; } document.getElementById('code').value = codeContent .substring( startInt, codeContent.length - endInt ) .replace(/&gt;/g,'>') .replace(/&lt;/g, "<") .replace(/&amp;/g, "&"); } else eSelected == null ; } function codingKeyDown( event, obj ) { // Process Tab key var tabKeyCode = 9; var keycode = event.keyCode; if (keycode == tabKeyCode) { if (obj.setSelectionRange) { // mozilla var s = obj.selectionStart; var e = obj.selectionEnd; obj.value = obj.value.substring(0, s) + "\t" + obj.value.substr(e); obj.setSelectionRange(s + 1, s + 1); obj.focus(); } else if (obj.createTextRange) { // ie document.selection.createRange().text="\t" event.returnValue = false; } else { // unsupported browsers } if (event.preventDefault) // dom event.preventDefault(); return false; // should work in all browsers } // Process Ctrl+A key for select all code if ( event.ctrlKey && event.keyCode == 65 || event.keyCode == 97 ) { document.getElementById("code").select(); return; } } </SCRIPT> </HEAD> <BODY SCROLL="no" style="OVERFLOW: hidden"> <TABLE width="100%" height="100%" border="0" cellpadding="0" cellspacing="0"> <TR><TD> <TABLE align="center" border="0" cellpadding="0" cellspacing="5"> <form> <TR> <TD width="30"><SPAN FCKLANG="DlgSyntaxHighLighterSelectLang">语言</SPAN></TD> <TD><SELECT name="codeType" id="codeType" onChange="setCodeType(this.value);"> <OPTION value="" fcklang="DlgSyntaxHighLighterSelectLang">语言</OPTION> <OPTION value="cpp">C++</OPTION> <OPTION value="c#">C#</OPTION> <OPTION value="css">CSS</OPTION> <OPTION value="delphi">Delphi</OPTION> <OPTION value="java">Java</OPTION> <OPTION value="javascript">JavaScript</OPTION> <OPTION value="php" selected>PHP</OPTION> <OPTION value="python">Python</OPTION> <OPTION value="ruby">Ruby</OPTION> <OPTION value="sql">SQL</OPTION> <OPTION value="xml">XML</OPTION> <OPTION value="vb">VB</OPTION> </SELECT></TD> </TR> <TR> <TD><SPAN fcklang="DlgSyntaxHighLighterCoding">代码</SPAN></TD> <TD><TEXTAREA name="code" cols="" rows="" wrap="off" class="" id="code" style="width:530; height:370;" onKeyDown="codingKeyDown(event, this);"></TEXTAREA></TD> </TR> </form> </TABLE> </TD></TR></TABLE> </BODY> </HTML>
10npsite
trunk/guanli/system/fckeditor/editor/plugins/highlighter/highlighter.html
HTML
asf20
6,691
FCKLang['DlgSyntaxHighLighterTitle'] = '插入语法高亮代码'; FCKLang['DlgSyntaxHighLighterProperty'] = '语法高亮代码属性'; FCKLang['DlgSyntaxHighLighterSelectLang'] = '语言'; FCKLang['DlgSyntaxHighLighterCoding'] = '代码'; FCKLang['DlgSyntaxHighLighterErrLang'] = '请选择一种语言'; FCKLang['DlgSyntaxHighLighterErrEmpty'] = '代码不能为空';
10npsite
trunk/guanli/system/fckeditor/editor/plugins/highlighter/lang/zh-cn.js
JavaScript
asf20
380
FCKLang['DlgSyntaxHighLighterTitle'] = 'Insert highLight code'; FCKLang['DlgSyntaxHighLighterProperty'] = 'HighLight Properties'; FCKLang['DlgSyntaxHighLighterSelectLang'] = 'Lang'; FCKLang['DlgSyntaxHighLighterCoding'] = 'Code'; FCKLang['DlgSyntaxHighLighterErrLang'] = 'Please select a language'; FCKLang['DlgSyntaxHighLighterErrEmpty'] = 'Coding can\'t empty';
10npsite
trunk/guanli/system/fckeditor/editor/plugins/highlighter/lang/en.js
JavaScript
asf20
371
window.onload = function () { dp.SyntaxHighlighter.ClipboardSwf = 'Scripts/clipboard.swf'; dp.SyntaxHighlighter.HighlightAll('code'); }
10npsite
trunk/guanli/system/fckeditor/editor/plugins/highlighter/dp.SyntaxHighlighter/Scripts/run.js
JavaScript
asf20
142
.dp-highlighter { font-family: "Consolas", "Courier New", Courier, mono, serif; font-size: 12px; background-color: #E7E5DC; width: 99%; overflow: auto; margin: 18px 0 18px 0 !important; padding-top: 1px; /* adds a little border on top when controls are hidden */ } /* clear styles */ .dp-highlighter ol, .dp-highlighter ol li, .dp-highlighter ol li span { margin: 0; padding: 0; border: none; } .dp-highlighter a, .dp-highlighter a:hover { background: none; border: none; padding: 0; margin: 0; } .dp-highlighter .bar { padding-left: 45px; } .dp-highlighter.collapsed .bar, .dp-highlighter.nogutter .bar { padding-left: 0px; } .dp-highlighter ol { list-style: decimal; /* for ie */ background-color: #fff; margin: 0px 0px 1px 45px !important; /* 1px bottom margin seems to fix occasional Firefox scrolling */ padding: 0px; color: #5C5C5C; } .dp-highlighter.nogutter ol, .dp-highlighter.nogutter ol li { list-style: none !important; margin-left: 0px !important; } .dp-highlighter ol li, .dp-highlighter .columns div { list-style: decimal-leading-zero; /* better look for others, override cascade from OL */ list-style-position: outside !important; border-left: 3px solid #6CE26C; background-color: #F8F8F8; color: #5C5C5C; padding: 0 3px 0 10px !important; margin: 0 !important; line-height: 14px; } .dp-highlighter.nogutter ol li, .dp-highlighter.nogutter .columns div { border: 0; } .dp-highlighter .columns { background-color: #F8F8F8; color: gray; overflow: hidden; width: 100%; } .dp-highlighter .columns div { padding-bottom: 5px; } .dp-highlighter ol li.alt { background-color: #FFF; color: inherit; } .dp-highlighter ol li span { color: black; background-color: inherit; } /* Adjust some properties when collapsed */ .dp-highlighter.collapsed ol { margin: 0px; } .dp-highlighter.collapsed ol li { display: none; } /* Additional modifications when in print-view */ .dp-highlighter.printing { border: none; } .dp-highlighter.printing .tools { display: none !important; } .dp-highlighter.printing li { display: list-item !important; } /* Styles for the tools */ .dp-highlighter .tools { padding: 3px 8px 3px 10px; font: 9px Verdana, Geneva, Arial, Helvetica, sans-serif; color: silver; background-color: #f8f8f8; padding-bottom: 10px; border-left: 3px solid #6CE26C; } .dp-highlighter.nogutter .tools { border-left: 0; } .dp-highlighter.collapsed .tools { border-bottom: 0; } .dp-highlighter .tools a { font-size: 9px; color: #a0a0a0; background-color: inherit; text-decoration: none; margin-right: 10px; } .dp-highlighter .tools a:hover { color: red; background-color: inherit; text-decoration: underline; } /* About dialog styles */ .dp-about { background-color: #fff; color: #333; margin: 0px; padding: 0px; } .dp-about table { width: 100%; height: 100%; font-size: 11px; font-family: Tahoma, Verdana, Arial, sans-serif !important; } .dp-about td { padding: 10px; vertical-align: top; } .dp-about .copy { border-bottom: 1px solid #ACA899; height: 95%; } .dp-about .title { color: red; background-color: inherit; font-weight: bold; } .dp-about .para { margin: 0 0 4px 0; } .dp-about .footer { background-color: #ECEADB; color: #333; border-top: 1px solid #fff; text-align: right; } .dp-about .close { font-size: 11px; font-family: Tahoma, Verdana, Arial, sans-serif !important; background-color: #ECEADB; color: #333; width: 60px; height: 22px; } /* Language specific styles */ .dp-highlighter .comment, .dp-highlighter .comments { color: #008200; background-color: inherit; } .dp-highlighter .string { color: blue; background-color: inherit; } .dp-highlighter .keyword { color: #069; font-weight: bold; background-color: inherit; } .dp-highlighter .preprocessor { color: gray; background-color: inherit; }
10npsite
trunk/guanli/system/fckeditor/editor/plugins/highlighter/dp.SyntaxHighlighter/Styles/SyntaxHighlighter.css
CSS
asf20
3,993
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Plugin: automatically resizes the editor until a configurable maximun * height (FCKConfig.AutoGrowMax), based on its contents. */ var FCKAutoGrow = { MIN_HEIGHT : window.frameElement.offsetHeight, Check : function() { var delta = FCKAutoGrow.GetHeightDelta() ; if ( delta != 0 ) { var newHeight = window.frameElement.offsetHeight + delta ; newHeight = FCKAutoGrow.GetEffectiveHeight( newHeight ) ; if ( newHeight != window.frameElement.height ) { window.frameElement.style.height = newHeight + "px" ; // Gecko browsers use an onresize handler to update the innermost // IFRAME's height. If the document is modified before the onresize // is triggered, the plugin will miscalculate the new height. Thus, // forcibly trigger onresize. #1336 if ( typeof window.onresize == 'function' ) { window.onresize() ; } } } }, CheckEditorStatus : function( sender, status ) { if ( status == FCK_STATUS_COMPLETE ) FCKAutoGrow.Check() ; }, GetEffectiveHeight : function( height ) { if ( height < FCKAutoGrow.MIN_HEIGHT ) height = FCKAutoGrow.MIN_HEIGHT; else { var max = FCKConfig.AutoGrowMax; if ( max && max > 0 && height > max ) height = max; } return height; }, GetHeightDelta : function() { var oInnerDoc = FCK.EditorDocument ; var iFrameHeight ; var iInnerHeight ; if ( FCKBrowserInfo.IsIE ) { iFrameHeight = FCK.EditorWindow.frameElement.offsetHeight ; iInnerHeight = oInnerDoc.body.scrollHeight ; } else { iFrameHeight = FCK.EditorWindow.innerHeight ; iInnerHeight = oInnerDoc.body.offsetHeight + ( parseInt( FCKDomTools.GetCurrentElementStyle( oInnerDoc.body, 'margin-top' ), 10 ) || 0 ) + ( parseInt( FCKDomTools.GetCurrentElementStyle( oInnerDoc.body, 'margin-bottom' ), 10 ) || 0 ) ; } return iInnerHeight - iFrameHeight ; }, SetListeners : function() { if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG ) return ; FCK.EditorWindow.attachEvent( 'onscroll', FCKAutoGrow.Check ) ; FCK.EditorDocument.attachEvent( 'onkeyup', FCKAutoGrow.Check ) ; } }; FCK.AttachToOnSelectionChange( FCKAutoGrow.Check ) ; if ( FCKBrowserInfo.IsIE ) FCK.Events.AttachEvent( 'OnAfterSetHTML', FCKAutoGrow.SetListeners ) ; FCK.Events.AttachEvent( 'OnStatusChange', FCKAutoGrow.CheckEditorStatus ) ;
10npsite
trunk/guanli/system/fckeditor/editor/plugins/autogrow/fckplugin.js
JavaScript
asf20
3,061
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 a sample implementation for a custom Data Processor for basic BBCode. */ FCK.DataProcessor = { /* * Returns a string representing the HTML format of "data". The returned * value will be loaded in the editor. * The HTML must be from <html> to </html>, eventually including * the DOCTYPE. * @param {String} data The data to be converted in the * DataProcessor specific format. */ ConvertToHtml : function( data ) { // Convert < and > to their HTML entities. data = data.replace( /</g, '&lt;' ) ; data = data.replace( />/g, '&gt;' ) ; // Convert line breaks to <br>. data = data.replace( /(?:\r\n|\n|\r)/g, '<br>' ) ; // [url] data = data.replace( /\[url\](.+?)\[\/url]/gi, '<a href="$1">$1</a>' ) ; data = data.replace( /\[url\=([^\]]+)](.+?)\[\/url]/gi, '<a href="$1">$2</a>' ) ; // [b] data = data.replace( /\[b\](.+?)\[\/b]/gi, '<b>$1</b>' ) ; // [i] data = data.replace( /\[i\](.+?)\[\/i]/gi, '<i>$1</i>' ) ; // [u] data = data.replace( /\[u\](.+?)\[\/u]/gi, '<u>$1</u>' ) ; return '<html><head><title></title></head><body>' + data + '</body></html>' ; }, /* * Converts a DOM (sub-)tree to a string in the data format. * @param {Object} rootNode The node that contains the DOM tree to be * converted to the data format. * @param {Boolean} excludeRoot Indicates that the root node must not * be included in the conversion, only its children. * @param {Boolean} format Indicates that the data must be formatted * for human reading. Not all Data Processors may provide it. */ ConvertToDataFormat : function( rootNode, excludeRoot, ignoreIfEmptyParagraph, format ) { var data = rootNode.innerHTML ; // Convert <br> to line breaks. data = data.replace( /<br(?=[ \/>]).*?>/gi, '\r\n') ; // [url] data = data.replace( /<a .*?href=(["'])(.+?)\1.*?>(.+?)<\/a>/gi, '[url=$2]$3[/url]') ; // [b] data = data.replace( /<(?:b|strong)>/gi, '[b]') ; data = data.replace( /<\/(?:b|strong)>/gi, '[/b]') ; // [i] data = data.replace( /<(?:i|em)>/gi, '[i]') ; data = data.replace( /<\/(?:i|em)>/gi, '[/i]') ; // [u] data = data.replace( /<u>/gi, '[u]') ; data = data.replace( /<\/u>/gi, '[/u]') ; // Remove remaining tags. data = data.replace( /<[^>]+>/g, '') ; return data ; }, /* * Makes any necessary changes to a piece of HTML for insertion in the * editor selection position. * @param {String} html The HTML to be fixed. */ FixHtml : function( html ) { return html ; } } ; // This Data Processor doesn't support <p>, so let's use <br>. FCKConfig.EnterMode = 'br' ; // To avoid pasting invalid markup (which is discarded in any case), let's // force pasting to plain text. FCKConfig.ForcePasteAsPlainText = true ; // Rename the "Source" buttom to "BBCode". FCKToolbarItems.RegisterItem( 'Source', new FCKToolbarButton( 'Source', 'BBCode', null, FCK_TOOLBARITEM_ICONTEXT, true, true, 1 ) ) ; // Let's enforce the toolbar to the limits of this Data Processor. A custom // toolbar set may be defined in the configuration file with more or less entries. FCKConfig.ToolbarSets["Default"] = [ ['Source'], ['Bold','Italic','Underline','-','Link'], ['About'] ] ;
10npsite
trunk/guanli/system/fckeditor/editor/plugins/bbcode/fckplugin.js
JavaScript
asf20
4,066
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Sample page. --> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>FCKeditor - BBCode Sample</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="robots" content="noindex, nofollow" /> <link href="../../../../_samples/sample.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="../../../../fckeditor.js"></script> </head> <body> <h1> FCKeditor - BBCode Sample</h1> <p> This is a sample of custom Data Processor implementation for (very) basic BBCode syntax. Only <strong>[b]</strong>, <strong>[i]</strong>, <strong>[u]</strong> and <strong>[url]</strong> may be used. It may be extended, but this is out of this sample purpose. </p> <p> Note that the input and output of the editor is not HTML, but BBCode </p> <hr /> <form action="../../../../_samples/html/sampleposteddata.asp" method="post" target="_blank"> <script type="text/javascript"> <!-- // Automatically calculates the editor base path based on the _samples directory. // This is usefull only for these samples. A real application should use something like this: // oFCKeditor.BasePath = '/fckeditor/' ; // '/fckeditor/' is the default value. var sBasePath = document.location.pathname.substring(0,document.location.pathname.lastIndexOf('editor')) ; var oFCKeditor = new FCKeditor( 'FCKeditor1' ) ; oFCKeditor.BasePath = sBasePath ; // Set the custom configurations file path (in this way the original file is mantained). oFCKeditor.Config['CustomConfigurationsPath'] = sBasePath + 'editor/plugins/bbcode/_sample/sample.config.js' ; oFCKeditor.Value = 'This is some [b]sample text[/b]. You are using [url=http://www.fckeditor.net/]FCKeditor[/url].' ; oFCKeditor.Create() ; //--> </script> <br /> <input type="submit" value="Submit" /> </form> </body> </html>
10npsite
trunk/guanli/system/fckeditor/editor/plugins/bbcode/_sample/sample.html
HTML
asf20
2,625
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Sample custom configuration settings used by the BBCode plugin. It simply * loads the plugin. All the rest is done by the plugin itself. */ // Add the BBCode plugin. FCKConfig.Plugins.Add( 'bbcode' ) ;
10npsite
trunk/guanli/system/fckeditor/editor/plugins/bbcode/_sample/sample.config.js
JavaScript
asf20
843
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 plugin register the required Toolbar items to be able to insert the * table commands in the toolbar. */ FCKToolbarItems.RegisterItem( 'TableInsertRowAfter' , new FCKToolbarButton( 'TableInsertRowAfter' , FCKLang.InsertRowAfter, null, null, null, true, 62 ) ) ; FCKToolbarItems.RegisterItem( 'TableDeleteRows' , new FCKToolbarButton( 'TableDeleteRows' , FCKLang.DeleteRows, null, null, null, true, 63 ) ) ; FCKToolbarItems.RegisterItem( 'TableInsertColumnAfter' , new FCKToolbarButton( 'TableInsertColumnAfter' , FCKLang.InsertColumnAfter, null, null, null, true, 64 ) ) ; FCKToolbarItems.RegisterItem( 'TableDeleteColumns' , new FCKToolbarButton( 'TableDeleteColumns', FCKLang.DeleteColumns, null, null, null, true, 65 ) ) ; FCKToolbarItems.RegisterItem( 'TableInsertCellAfter' , new FCKToolbarButton( 'TableInsertCellAfter' , FCKLang.InsertCellAfter, null, null, null, true, 58 ) ) ; FCKToolbarItems.RegisterItem( 'TableDeleteCells' , new FCKToolbarButton( 'TableDeleteCells' , FCKLang.DeleteCells, null, null, null, true, 59 ) ) ; FCKToolbarItems.RegisterItem( 'TableMergeCells' , new FCKToolbarButton( 'TableMergeCells' , FCKLang.MergeCells, null, null, null, true, 60 ) ) ; FCKToolbarItems.RegisterItem( 'TableHorizontalSplitCell' , new FCKToolbarButton( 'TableHorizontalSplitCell' , FCKLang.SplitCell, null, null, null, true, 61 ) ) ; FCKToolbarItems.RegisterItem( 'TableCellProp' , new FCKToolbarButton( 'TableCellProp' , FCKLang.CellProperties, null, null, null, true, 57 ) ) ;
10npsite
trunk/guanli/system/fckeditor/editor/plugins/tablecommands/fckplugin.js
JavaScript
asf20
2,144
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 plugin register Toolbar items for the combos modifying the style to * not show the box. */ FCKToolbarItems.RegisterItem( 'SourceSimple' , new FCKToolbarButton( 'Source', FCKLang.Source, null, FCK_TOOLBARITEM_ONLYICON, true, true, 1 ) ) ; FCKToolbarItems.RegisterItem( 'StyleSimple' , new FCKToolbarStyleCombo( null, FCK_TOOLBARITEM_ONLYTEXT ) ) ; FCKToolbarItems.RegisterItem( 'FontNameSimple' , new FCKToolbarFontsCombo( null, FCK_TOOLBARITEM_ONLYTEXT ) ) ; FCKToolbarItems.RegisterItem( 'FontSizeSimple' , new FCKToolbarFontSizeCombo( null, FCK_TOOLBARITEM_ONLYTEXT ) ) ; FCKToolbarItems.RegisterItem( 'FontFormatSimple', new FCKToolbarFontFormatCombo( null, FCK_TOOLBARITEM_ONLYTEXT ) ) ;
10npsite
trunk/guanli/system/fckeditor/editor/plugins/simplecommands/fckplugin.js
JavaScript
asf20
1,342
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <!-- * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 == * * Main page that holds the editor. --> <html> <head> <title>FCKeditor</title> <meta name="robots" content="noindex, nofollow"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <!-- @Packager.RemoveLine <meta http-equiv="Cache-Control" content="public"> @Packager.RemoveLine --> <script type="text/javascript"> // #1645: Alert the user if opening FCKeditor in FF3 from local filesystem // without security.fileuri.strict_origin_policy disabled. if ( document.location.protocol == 'file:' ) { try { window.parent.document.domain ; } catch ( e ) { window.addEventListener( 'load', function() { document.body.innerHTML = '\ <div style="border: 1px red solid; font-family: arial; font-size: 12px; color: red; padding:10px;">\ <p>\ <b>Your browser security settings don\'t allow FCKeditor to be opened from\ the local filesystem.<\/b>\ <\/p>\ <p>\ Please open the <b>about:config<\/b> page and disable the\ &quot;security.fileuri.strict_origin_policy&quot; option; then load this page again.\ <\/p>\ <p>\ Check our <a href="http://docs.fckeditor.net/FCKeditor_2.x/Developers_Guide/FAQ#ff3perms">FAQ<\/a>\ for more information.\ <\/p>\ <\/div>' ; }, false ) ; } } // Save a reference to the default domain. var FCK_ORIGINAL_DOMAIN ; // Automatically detect the correct document.domain (#123). (function() { var d = FCK_ORIGINAL_DOMAIN = document.domain ; while ( true ) { // Test if we can access a parent property. try { var test = window.parent.document.domain ; break ; } catch( e ) {} // Remove a domain part: www.mytest.example.com => mytest.example.com => example.com ... d = d.replace( /.*?(?:\.|$)/, '' ) ; if ( d.length == 0 ) break ; // It was not able to detect the domain. try { document.domain = d ; } catch (e) { break ; } } })() ; // Save a reference to the detected runtime domain. var FCK_RUNTIME_DOMAIN = document.domain ; var FCK_IS_CUSTOM_DOMAIN = ( FCK_ORIGINAL_DOMAIN != FCK_RUNTIME_DOMAIN ) ; // Instead of loading scripts and CSSs using inline tags, all scripts are // loaded by code. In this way we can guarantee the correct processing order, // otherwise external scripts and inline scripts could be executed in an // unwanted order (IE). function LoadScript( url ) { document.write( '<scr' + 'ipt type="text/javascript" src="' + url + '"><\/scr' + 'ipt>' ) ; } // Main editor scripts. var sSuffix = ( /*@cc_on!@*/false ) ? 'ie' : 'gecko' ; /* @Packager.RemoveLine LoadScript( 'js/fckeditorcode_' + sSuffix + '.js' ) ; @Packager.RemoveLine */ // @Packager.Remove.Start LoadScript( '_source/fckconstants.js' ) ; LoadScript( '_source/fckjscoreextensions.js' ) ; if ( sSuffix == 'ie' ) LoadScript( '_source/classes/fckiecleanup.js' ) ; LoadScript( '_source/internals/fckbrowserinfo.js' ) ; LoadScript( '_source/internals/fckurlparams.js' ) ; LoadScript( '_source/classes/fckevents.js' ) ; LoadScript( '_source/classes/fckdataprocessor.js' ) ; LoadScript( '_source/internals/fck.js' ) ; LoadScript( '_source/internals/fck_' + sSuffix + '.js' ) ; LoadScript( '_source/internals/fckconfig.js' ) ; LoadScript( '_source/internals/fckdebug_empty.js' ) ; LoadScript( '_source/internals/fckdomtools.js' ) ; LoadScript( '_source/internals/fcktools.js' ) ; LoadScript( '_source/internals/fcktools_' + sSuffix + '.js' ) ; LoadScript( '_source/fckeditorapi.js' ) ; LoadScript( '_source/classes/fckimagepreloader.js' ) ; LoadScript( '_source/internals/fckregexlib.js' ) ; LoadScript( '_source/internals/fcklistslib.js' ) ; LoadScript( '_source/internals/fcklanguagemanager.js' ) ; LoadScript( '_source/internals/fckxhtmlentities.js' ) ; LoadScript( '_source/internals/fckxhtml.js' ) ; LoadScript( '_source/internals/fckxhtml_' + sSuffix + '.js' ) ; LoadScript( '_source/internals/fckcodeformatter.js' ) ; LoadScript( '_source/internals/fckundo.js' ) ; LoadScript( '_source/classes/fckeditingarea.js' ) ; LoadScript( '_source/classes/fckkeystrokehandler.js' ) ; LoadScript( 'dtd/fck_xhtml10transitional.js' ) ; LoadScript( '_source/classes/fckstyle.js' ) ; LoadScript( '_source/internals/fckstyles.js' ) ; LoadScript( '_source/internals/fcklisthandler.js' ) ; LoadScript( '_source/classes/fckelementpath.js' ) ; LoadScript( '_source/classes/fckdomrange.js' ) ; LoadScript( '_source/classes/fckdocumentfragment_' + sSuffix + '.js' ) ; LoadScript( '_source/classes/fckw3crange.js' ) ; LoadScript( '_source/classes/fckdomrange_' + sSuffix + '.js' ) ; LoadScript( '_source/classes/fckdomrangeiterator.js' ) ; LoadScript( '_source/classes/fckenterkey.js' ) ; LoadScript( '_source/internals/fckdocumentprocessor.js' ) ; LoadScript( '_source/internals/fckselection.js' ) ; LoadScript( '_source/internals/fckselection_' + sSuffix + '.js' ) ; LoadScript( '_source/internals/fcktablehandler.js' ) ; LoadScript( '_source/internals/fcktablehandler_' + sSuffix + '.js' ) ; LoadScript( '_source/classes/fckxml.js' ) ; LoadScript( '_source/classes/fckxml_' + sSuffix + '.js' ) ; LoadScript( '_source/commandclasses/fcknamedcommand.js' ) ; LoadScript( '_source/commandclasses/fckstylecommand.js' ) ; LoadScript( '_source/commandclasses/fck_othercommands.js' ) ; LoadScript( '_source/commandclasses/fckshowblocks.js' ) ; LoadScript( '_source/commandclasses/fckspellcheckcommand_' + sSuffix + '.js' ) ; LoadScript( '_source/commandclasses/fcktextcolorcommand.js' ) ; LoadScript( '_source/commandclasses/fckpasteplaintextcommand.js' ) ; LoadScript( '_source/commandclasses/fckpastewordcommand.js' ) ; LoadScript( '_source/commandclasses/fcktablecommand.js' ) ; LoadScript( '_source/commandclasses/fckfitwindow.js' ) ; LoadScript( '_source/commandclasses/fcklistcommands.js' ) ; LoadScript( '_source/commandclasses/fckjustifycommands.js' ) ; LoadScript( '_source/commandclasses/fckindentcommands.js' ) ; LoadScript( '_source/commandclasses/fckblockquotecommand.js' ) ; LoadScript( '_source/commandclasses/fckcorestylecommand.js' ) ; LoadScript( '_source/commandclasses/fckremoveformatcommand.js' ) ; LoadScript( '_source/internals/fckcommands.js' ) ; LoadScript( '_source/classes/fckpanel.js' ) ; LoadScript( '_source/classes/fckicon.js' ) ; LoadScript( '_source/classes/fcktoolbarbuttonui.js' ) ; LoadScript( '_source/classes/fcktoolbarbutton.js' ) ; LoadScript( '_source/classes/fckspecialcombo.js' ) ; LoadScript( '_source/classes/fcktoolbarspecialcombo.js' ) ; LoadScript( '_source/classes/fcktoolbarstylecombo.js' ) ; LoadScript( '_source/classes/fcktoolbarfontformatcombo.js' ) ; LoadScript( '_source/classes/fcktoolbarfontscombo.js' ) ; LoadScript( '_source/classes/fcktoolbarfontsizecombo.js' ) ; LoadScript( '_source/classes/fcktoolbarpanelbutton.js' ) ; LoadScript( '_source/internals/fckscayt.js' ) ; LoadScript( '_source/internals/fcktoolbaritems.js' ) ; LoadScript( '_source/classes/fcktoolbar.js' ) ; LoadScript( '_source/classes/fcktoolbarbreak_' + sSuffix + '.js' ) ; LoadScript( '_source/internals/fcktoolbarset.js' ) ; LoadScript( '_source/internals/fckdialog.js' ) ; LoadScript( '_source/classes/fckmenuitem.js' ) ; LoadScript( '_source/classes/fckmenublock.js' ) ; LoadScript( '_source/classes/fckmenublockpanel.js' ) ; LoadScript( '_source/classes/fckcontextmenu.js' ) ; LoadScript( '_source/internals/fck_contextmenu.js' ) ; LoadScript( '_source/classes/fckhtmliterator.js' ) ; LoadScript( '_source/classes/fckplugin.js' ) ; LoadScript( '_source/internals/fckplugins.js' ) ; // @Packager.Remove.End // Base configuration file. LoadScript( '../fckconfig.js' ) ; </script> <script type="text/javascript"> // Adobe AIR compatibility file. if ( FCKBrowserInfo.IsAIR ) LoadScript( 'js/fckadobeair.js' ) ; if ( FCKBrowserInfo.IsIE ) { // Remove IE mouse flickering. try { document.execCommand( 'BackgroundImageCache', false, true ) ; } catch (e) { // We have been reported about loading problems caused by the above // line. For safety, let's just ignore errors. } // Create the default cleanup object used by the editor. FCK.IECleanup = new FCKIECleanup( window ) ; FCK.IECleanup.AddItem( FCKTempBin, FCKTempBin.Reset ) ; FCK.IECleanup.AddItem( FCK, FCK_Cleanup ) ; } // The first function to be called on selection change must the the styles // change checker, because the result of its processing may be used by another // functions listening to the same event. FCK.Events.AttachEvent( 'OnSelectionChange', function() { FCKStyles.CheckSelectionChanges() ; } ) ; // The config hidden field is processed immediately, because // CustomConfigurationsPath may be set in the page. FCKConfig.ProcessHiddenField() ; // Load the custom configurations file (if defined). if ( FCKConfig.CustomConfigurationsPath.length > 0 ) LoadScript( FCKConfig.CustomConfigurationsPath ) ; </script> <script type="text/javascript"> // Load configurations defined at page level. FCKConfig_LoadPageConfig() ; FCKConfig_PreProcess() ; // Load the full debug script. if ( FCKConfig.Debug ) LoadScript( '_source/internals/fckdebug.js' ) ; </script> <script type="text/javascript"> var FCK_InternalCSS = FCKConfig.BasePath + 'css/fck_internal.css' ; // @Packager.RemoveLine var FCK_ShowTableBordersCSS = FCKConfig.BasePath + 'css/fck_showtableborders_gecko.css' ; // @Packager.RemoveLine /* @Packager.RemoveLine // CSS minified by http://iceyboard.no-ip.org/projects/css_compressor (see _dev/css_compression.txt). var FCK_InternalCSS = FCKTools.FixCssUrls( FCKConfig.BasePath + 'css/', 'html{min-height:100%}table.FCK__ShowTableBorders,table.FCK__ShowTableBorders td,table.FCK__ShowTableBorders th{border:#d3d3d3 1px solid}form{border:1px dotted #F00;padding:2px}.FCK__Flash{border:#a9a9a9 1px solid;background-position:center center;background-image:url(images/fck_flashlogo.gif);background-repeat:no-repeat;width:80px;height:80px}.FCK__UnknownObject{border:#a9a9a9 1px solid;background-position:center center;background-image:url(images/fck_plugin.gif);background-repeat:no-repeat;width:80px;height:80px}.FCK__Anchor{border:1px dotted #00F;background-position:center center;background-image:url(images/fck_anchor.gif);background-repeat:no-repeat;width:16px;height:15px;vertical-align:middle}.FCK__AnchorC{border:1px dotted #00F;background-position:1px center;background-image:url(images/fck_anchor.gif);background-repeat:no-repeat;padding-left:18px}a[name]{border:1px dotted #00F;background-position:0 center;background-image:url(images/fck_anchor.gif);background-repeat:no-repeat;padding-left:18px}.FCK__PageBreak{background-position:center center;background-image:url(images/fck_pagebreak.gif);background-repeat:no-repeat;clear:both;display:block;float:none;width:100%;border-top:#999 1px dotted;border-bottom:#999 1px dotted;border-right:0;border-left:0;height:5px}.FCK__InputHidden{width:19px;height:18px;background-image:url(images/fck_hiddenfield.gif);background-repeat:no-repeat;vertical-align:text-bottom;background-position:center center}.FCK__ShowBlocks p,.FCK__ShowBlocks div,.FCK__ShowBlocks pre,.FCK__ShowBlocks address,.FCK__ShowBlocks blockquote,.FCK__ShowBlocks h1,.FCK__ShowBlocks h2,.FCK__ShowBlocks h3,.FCK__ShowBlocks h4,.FCK__ShowBlocks h5,.FCK__ShowBlocks h6{background-repeat:no-repeat;border:1px dotted gray;padding-top:8px;padding-left:8px}.FCK__ShowBlocks p{background-image:url(images/block_p.png)}.FCK__ShowBlocks div{background-image:url(images/block_div.png)}.FCK__ShowBlocks pre{background-image:url(images/block_pre.png)}.FCK__ShowBlocks address{background-image:url(images/block_address.png)}.FCK__ShowBlocks blockquote{background-image:url(images/block_blockquote.png)}.FCK__ShowBlocks h1{background-image:url(images/block_h1.png)}.FCK__ShowBlocks h2{background-image:url(images/block_h2.png)}.FCK__ShowBlocks h3{background-image:url(images/block_h3.png)}.FCK__ShowBlocks h4{background-image:url(images/block_h4.png)}.FCK__ShowBlocks h5{background-image:url(images/block_h5.png)}.FCK__ShowBlocks h6{background-image:url(images/block_h6.png)}' ) ; var FCK_ShowTableBordersCSS = FCKTools.FixCssUrls( FCKConfig.BasePath + 'css/', 'table:not([border]),table:not([border]) > tr > td,table:not([border]) > tr > th,table:not([border]) > tbody > tr > td,table:not([border]) > tbody > tr > th,table:not([border]) > thead > tr > td,table:not([border]) > thead > tr > th,table:not([border]) > tfoot > tr > td,table:not([border]) > tfoot > tr > th,table[border=\"0\"],table[border=\"0\"] > tr > td,table[border=\"0\"] > tr > th,table[border=\"0\"] > tbody > tr > td,table[border=\"0\"] > tbody > tr > th,table[border=\"0\"] > thead > tr > td,table[border=\"0\"] > thead > tr > th,table[border=\"0\"] > tfoot > tr > td,table[border=\"0\"] > tfoot > tr > th{border:#d3d3d3 1px dotted}' ) ; @Packager.RemoveLine */ // Popup the debug window if debug mode is set to true. It guarantees that the // first debug message will not be lost. if ( FCKConfig.Debug ) FCKDebug._GetWindow() ; // Load the active skin CSS. document.write( FCKTools.GetStyleHtml( FCKConfig.SkinEditorCSS ) ) ; // Load the language file. FCKLanguageManager.Initialize() ; LoadScript( 'lang/' + FCKLanguageManager.ActiveLanguage.Code + '.js' ) ; </script> <script type="text/javascript"> // Initialize the editing area context menu. FCK_ContextMenu_Init() ; FCKPlugins.Load() ; </script> <script type="text/javascript"> // Set the editor interface direction. window.document.dir = FCKLang.Dir ; </script> <script type="text/javascript"> window.onload = function() { InitializeAPI() ; if ( FCKBrowserInfo.IsIE ) FCK_PreloadImages() ; else LoadToolbarSetup() ; } function LoadToolbarSetup() { FCKeditorAPI._FunctionQueue.Add( LoadToolbar ) ; } function LoadToolbar() { var oToolbarSet = FCK.ToolbarSet = FCKToolbarSet_Create() ; if ( oToolbarSet.IsLoaded ) StartEditor() ; else { oToolbarSet.OnLoad = StartEditor ; oToolbarSet.Load( FCKURLParams['Toolbar'] || 'Default' ) ; } } function StartEditor() { // Remove the onload listener. FCK.ToolbarSet.OnLoad = null ; FCKeditorAPI._FunctionQueue.Remove( LoadToolbar ) ; FCK.Events.AttachEvent( 'OnStatusChange', WaitForActive ) ; // Start the editor. FCK.StartEditor() ; } function WaitForActive( editorInstance, newStatus ) { if ( newStatus == FCK_STATUS_ACTIVE ) { if ( FCKBrowserInfo.IsGecko ) FCKTools.RunFunction( window.onresize ) ; if ( !FCKConfig.PreventSubmitHandler ) _AttachFormSubmitToAPI() ; FCK.SetStatus( FCK_STATUS_COMPLETE ) ; // Call the special "FCKeditor_OnComplete" function that should be present in // the HTML page where the editor is located. if ( typeof( window.parent.FCKeditor_OnComplete ) == 'function' ) window.parent.FCKeditor_OnComplete( FCK ) ; } } // Gecko and Webkit browsers don't calculate well the IFRAME size so we must // recalculate it every time the window size changes. if ( FCKBrowserInfo.IsGecko || FCKBrowserInfo.IsSafari ) { window.onresize = function( e ) { // Running in Firefox's chrome makes the window receive the event including subframes. // we care only about this window. Ticket #1642. // #2002: The originalTarget from the event can be the current document, the window, or the editing area. if ( e && e.originalTarget && e.originalTarget !== document && e.originalTarget !== window && (!e.originalTarget.ownerDocument || e.originalTarget.ownerDocument != document )) return ; var oCell = document.getElementById( 'xEditingArea' ) ; var eInnerElement = oCell.firstChild ; if ( eInnerElement ) { eInnerElement.style.height = '0px' ; eInnerElement.style.height = ( oCell.scrollHeight - 2 ) + 'px' ; } } } </script> </head> <body> <table width="100%" cellpadding="0" cellspacing="0" style="height: 100%; table-layout: fixed"> <tr id="xToolbarRow" style="display: none"> <td id="xToolbarSpace" style="overflow: hidden"> <table width="100%" cellpadding="0" cellspacing="0"> <tr id="xCollapsed" style="display: none"> <td id="xExpandHandle" class="TB_Expand" colspan="3"> <img class="TB_ExpandImg" alt="" src="images/spacer.gif" width="8" height="4" /></td> </tr> <tr id="xExpanded" style="display: none"> <td id="xTBLeftBorder" class="TB_SideBorder" style="width: 1px; display: none;"></td> <td id="xCollapseHandle" style="display: none" class="TB_Collapse" valign="bottom"> <img class="TB_CollapseImg" alt="" src="images/spacer.gif" width="8" height="4" /></td> <td id="xToolbar" class="TB_ToolbarSet"></td> <td class="TB_SideBorder" style="width: 1px"></td> </tr> </table> </td> </tr> <tr> <td id="xEditingArea" valign="top" style="height: 100%"></td> </tr> </table> </body> </html>
10npsite
trunk/guanli/system/fckeditor/editor/fckeditor.original.html
HTML
asf20
17,800
<!--- image.cfc v2.19, written by Rick Root (rick@webworksllc.com) Derivative of work originally done originally by James Dew. Related Web Sites: - http://www.opensourcecf.com/imagecfc (home page) - http://www.cfopen.org/projects/imagecfc (project page) LICENSE ------- Copyright (c) 2007, 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. ============================================================ This is a derivative work. Following is the original Copyright notice. ============================================================ Copyright (c) 2004 James F. Dew <jdew@yggdrasil.ca> Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ---> <!--- SPECIAL NOTE FOR HEADLESS SYSTEMS --------------------------------- If you get a "cannot connect to X11 server" when running certain parts of this component under Bluedragon (Linux), you must add "-Djava.awt.headless=true" to the java startup line in <bluedragon>/bin/StartBluedragon.sh. This isssue is discussed in the Bluedragon Installation Guide section 3.8.1 for Bluedragon 6.2.1. Bluedragon may also report a ClassNotFound exception when trying to instantiate the java.awt.image.BufferedImage class. This is most likely the same issue. If you get "This graphics environment can be used only in the software emulation mode" when calling certain parts of this component under Coldfusion MX, you should refer to Technote ID #18747: http://www.macromedia.com/go/tn_18747 ---> <cfcomponent displayname="Image"> <cfset variables.throwOnError = "Yes"> <cfset variables.defaultJpegCompression = "90"> <cfset variables.interpolation = "bicubic"> <cfset variables.textAntiAliasing = "Yes"> <cfset variables.tempDirectory = "#expandPath(".")#"> <cfset variables.javanulls = "no"> <cftry> <cfset nullvalue = javacast("null","")> <cfset variables.javanulls = "yes"> <cfcatch type="any"> <cfset variables.javanulls = "no"> <!--- javacast null not supported, so filters won't work ---> </cfcatch> </cftry> <!--- <cfif javanulls> <cfset variables.blurFilter = createObject("component","blurFilter")> <cfset variables.sharpenFilter = createObject("component","sharpenFilter")> <cfset variables.posterizeFilter = createObject("component","posterizeFilter")> </cfif> ---> <cfset variables.Math = createobject("java", "java.lang.Math")> <cfset variables.arrObj = createobject("java", "java.lang.reflect.Array")> <cfset variables.floatClass = createobject("java", "java.lang.Float").TYPE> <cfset variables.intClass = createobject("java", "java.lang.Integer").TYPE> <cfset variables.shortClass = createobject("java", "java.lang.Short").TYPE> <cffunction name="getImageInfo" access="public" output="true" returntype="struct" hint="Rotate an image (+/-)90, (+/-)180, or (+/-)270 degrees."> <cfargument name="objImage" required="yes" type="Any"> <cfargument name="inputFile" required="yes" type="string"> <cfset var retVal = StructNew()> <cfset var loadImage = StructNew()> <cfset var img = ""> <cfset retVal.errorCode = 0> <cfset retVal.errorMessage = ""> <cfif inputFile neq ""> <cfset loadImage = readImage(inputFile, "NO")> <cfif loadImage.errorCode is 0> <cfset img = loadImage.img> <cfelse> <cfset retVal = throw(loadImage.errorMessage)> <cfreturn retVal> </cfif> <cfset retVal.metaData = getImageMetadata(loadImage.inFile)> <cfelse> <cfset img = objImage> <cfset retVal.metadata = getImageMetadata("")> </cfif> <cftry> <cfset retVal.width = img.getWidth()> <cfset retVal.height = img.getHeight()> <cfset retVal.colorModel = img.getColorModel().toString()> <cfset retVal.colorspace = img.getColorModel().getColorSpace().toString()> <cfset retVal.objColorModel = img.getColorModel()> <cfset retVal.objColorspace = img.getColorModel().getColorSpace()> <cfset retVal.sampleModel = img.getSampleModel().toString()> <cfset retVal.imageType = img.getType()> <cfset retVal.misc = img.toString()> <cfset retVal.canModify = true> <cfreturn retVal> <cfcatch type="any"> <cfset retVal = throw( "#cfcatch.message#: #cfcatch.detail#")> <cfreturn retVal> </cfcatch> </cftry> </cffunction> <cffunction name="getImageMetadata" access="private" output="false" returntype="query"> <cfargument name="inFile" required="yes" type="Any"><!--- java.io.File ---> <cfset var retQry = queryNew("dirName,tagName,tagValue")> <cfset var paths = arrayNew(1)> <cfset var loader = ""> <cfset var JpegMetadatareader = ""> <cfset var myMetadata = ""> <cfset var directories = ""> <cfset var currentDirectory = ""> <cfset var tags = ""> <cfset var currentTag = ""> <cfset var tagName = ""> <cftry> <cfscript> paths = arrayNew(1); paths[1] = expandPath("metadata-extractor-2.3.1.jar"); loader = createObject("component", "javaloader.JavaLoader").init(paths); //at this stage we only have access to the class, but we don't have an instance JpegMetadataReader = loader.create("com.drew.imaging.jpeg.JpegMetadataReader"); myMetaData = JpegMetadataReader.readMetadata(inFile); directories = myMetaData.getDirectoryIterator(); while (directories.hasNext()) { currentDirectory = directories.next(); tags = currentDirectory.getTagIterator(); while (tags.hasNext()) { currentTag = tags.next(); if (currentTag.getTagName() DOES NOT CONTAIN "Unknown") { //leave out the junk data queryAddRow(retQry); querySetCell(retQry,"dirName",replace(currentTag.getDirectoryName(),' ','_','ALL')); tagName = replace(currentTag.getTagName(),' ','','ALL'); tagName = replace(tagName,'/','','ALL'); querySetCell(retQry,"tagName",tagName); querySetCell(retQry,"tagValue",currentTag.getDescription()); } } } return retQry; </cfscript> <cfcatch type="any"> <cfreturn retQry /> </cfcatch> </cftry> </cffunction> <cffunction name="flipHorizontal" access="public" output="true" returntype="struct" hint="Flip an image horizontally."> <cfargument name="objImage" required="yes" type="Any"> <cfargument name="inputFile" required="yes" type="string"> <cfargument name="outputFile" required="yes" type="string"> <cfargument name="jpegCompression" required="no" type="numeric" default="#variables.defaultJpegCompression#"> <cfreturn flipflop(objImage, inputFile, outputFile, "horizontal", jpegCompression)> </cffunction> <cffunction name="flipVertical" access="public" output="true" returntype="struct" hint="Flop an image vertically."> <cfargument name="objImage" required="yes" type="Any"> <cfargument name="inputFile" required="yes" type="string"> <cfargument name="outputFile" required="yes" type="string"> <cfargument name="jpegCompression" required="no" type="numeric" default="#variables.defaultJpegCompression#"> <cfreturn flipflop(objImage, inputFile, outputFile, "vertical", jpegCompression)> </cffunction> <cffunction name="scaleWidth" access="public" output="true" returntype="struct" hint="Scale an image to a specific width."> <cfargument name="objImage" required="yes" type="Any"> <cfargument name="inputFile" required="yes" type="string"> <cfargument name="outputFile" required="yes" type="string"> <cfargument name="newWidth" required="yes" type="numeric"> <cfargument name="jpegCompression" required="no" type="numeric" default="#variables.defaultJpegCompression#"> <cfreturn resize(objImage, inputFile, outputFile, newWidth, 0, "false", "false", jpegCompression)> </cffunction> <cffunction name="scaleHeight" access="public" output="true" returntype="struct" hint="Scale an image to a specific height."> <cfargument name="objImage" required="yes" type="Any"> <cfargument name="inputFile" required="yes" type="string"> <cfargument name="outputFile" required="yes" type="string"> <cfargument name="newHeight" required="yes" type="numeric"> <cfargument name="jpegCompression" required="no" type="numeric" default="#variables.defaultJpegCompression#"> <cfreturn resize(objImage, inputFile, outputFile, 0, newHeight, "false", "false", jpegCompression)> </cffunction> <cffunction name="resize" access="public" output="true" returntype="struct" hint="Resize an image to a specific width and height."> <cfargument name="objImage" required="yes" type="Any"> <cfargument name="inputFile" required="yes" type="string"> <cfargument name="outputFile" required="yes" type="string"> <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"> <cfargument name="jpegCompression" required="no" type="numeric" default="#variables.defaultJpegCompression#"> <cfset var retVal = StructNew()> <cfset var loadImage = StructNew()> <cfset var saveImage = StructNew()> <cfset var at = ""> <cfset var op = ""> <cfset var w = ""> <cfset var h = ""> <cfset var scale = 1> <cfset var scaleX = 1> <cfset var scaleY = 1> <cfset var resizedImage = ""> <cfset var rh = getRenderingHints()> <cfset var specifiedWidth = arguments.newWidth> <cfset var specifiedHeight = arguments.newHeight> <cfset var imgInfo = ""> <cfset var img = ""> <cfset var cropImageResult = ""> <cfset var cropOffsetX = ""> <cfset var cropOffsetY = ""> <cfset retVal.errorCode = 0> <cfset retVal.errorMessage = ""> <cfif inputFile neq ""> <cfset loadImage = readImage(inputFile, "NO")> <cfif loadImage.errorCode is 0> <cfset img = loadImage.img> <cfelse> <cfset retVal = throw(loadImage.errorMessage)> <cfreturn retVal> </cfif> <cfelse> <cfset img = objImage> </cfif> <cfif img.getType() eq 0> <cfset img = convertImageObject(img,img.TYPE_3BYTE_BGR)> </cfif> <cfscript> resizedImage = CreateObject("java", "java.awt.image.BufferedImage"); at = CreateObject("java", "java.awt.geom.AffineTransform"); op = CreateObject("java", "java.awt.image.AffineTransformOp"); w = img.getWidth(); h = img.getHeight(); if (preserveAspect and cropToExact and newHeight gt 0 and newWidth gt 0) { if (w / h gt newWidth / newHeight){ newWidth = 0; } else if (w / h lt newWidth / newHeight){ newHeight = 0; } } else if (preserveAspect and newHeight gt 0 and newWidth gt 0) { if (w / h gt newWidth / newHeight){ newHeight = 0; } else if (w / h lt newWidth / newHeight){ newWidth = 0; } } if (newWidth gt 0 and newHeight eq 0) { scale = newWidth / w; w = newWidth; h = round(h*scale); } else if (newHeight gt 0 and newWidth eq 0) { scale = newHeight / h; h = newHeight; w = round(w*scale); } else if (newHeight gt 0 and newWidth gt 0) { w = newWidth; h = newHeight; } else { retVal = throw( retVal.errorMessage); return retVal; } resizedImage.init(javacast("int",w),javacast("int",h),img.getType()); w = w / img.getWidth(); h = h / img.getHeight(); op.init(at.getScaleInstance(javacast("double",w),javacast("double",h)), rh); // resizedImage = op.createCompatibleDestImage(img, img.getColorModel()); op.filter(img, resizedImage); imgInfo = getimageinfo(resizedImage, ""); if (imgInfo.errorCode gt 0) { return imgInfo; } cropOffsetX = max( Int( (imgInfo.width/2) - (newWidth/2) ), 0 ); cropOffsetY = max( Int( (imgInfo.height/2) - (newHeight/2) ), 0 ); // There is a chance that the image is exactly the correct // width and height and don't need to be cropped if ( preserveAspect and cropToExact and (imgInfo.width IS NOT specifiedWidth OR imgInfo.height IS NOT specifiedHeight) ) { // Get the correct offset to get the center of the image cropOffsetX = max( Int( (imgInfo.width/2) - (specifiedWidth/2) ), 0 ); cropOffsetY = max( Int( (imgInfo.height/2) - (specifiedHeight/2) ), 0 ); cropImageResult = crop( resizedImage, "", "", cropOffsetX, cropOffsetY, specifiedWidth, specifiedHeight ); if ( cropImageResult.errorCode GT 0) { return cropImageResult; } else { resizedImage = cropImageResult.img; } } if (outputFile eq "") { retVal.img = resizedImage; return retVal; } else { saveImage = writeImage(outputFile, resizedImage, jpegCompression); if (saveImage.errorCode gt 0) { return saveImage; } else { return retVal; } } </cfscript> </cffunction> <cffunction name="crop" access="public" output="true" returntype="struct" hint="Crop an image."> <cfargument name="objImage" required="yes" type="Any"> <cfargument name="inputFile" required="yes" type="string"> <cfargument name="outputFile" required="yes" type="string"> <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"> <cfargument name="jpegCompression" required="no" type="numeric" default="#variables.defaultJpegCompression#"> <cfset var retVal = StructNew()> <cfset var loadImage = StructNew()> <cfset var saveImage = StructNew()> <cfset var croppedImage = ""> <cfset var rh = getRenderingHints()> <cfset var img = ""> <cfset retVal.errorCode = 0> <cfset retVal.errorMessage = ""> <cfif inputFile neq ""> <cfset loadImage = readImage(inputFile, "NO")> <cfif loadImage.errorCode is 0> <cfset img = loadImage.img> <cfelse> <cfset retVal = throw(loadImage.errorMessage)> <cfreturn retVal> </cfif> <cfelse> <cfset img = objImage> </cfif> <cfif img.getType() eq 0> <cfset img = convertImageObject(img,img.TYPE_3BYTE_BGR)> </cfif> <cfscript> if (fromX + newWidth gt img.getWidth() OR fromY + newHeight gt img.getHeight() ) { retval = throw( "The cropped image dimensions go beyond the original image dimensions."); return retVal; } croppedImage = img.getSubimage(javaCast("int", fromX), javaCast("int", fromY), javaCast("int", newWidth), javaCast("int", newHeight) ); if (outputFile eq "") { retVal.img = croppedImage; return retVal; } else { saveImage = writeImage(outputFile, croppedImage, jpegCompression); if (saveImage.errorCode gt 0) { return saveImage; } else { return retVal; } } </cfscript> </cffunction> <cffunction name="rotate" access="public" output="true" returntype="struct" hint="Rotate an image (+/-)90, (+/-)180, or (+/-)270 degrees."> <cfargument name="objImage" required="yes" type="Any"> <cfargument name="inputFile" required="yes" type="string"> <cfargument name="outputFile" required="yes" type="string"> <cfargument name="degrees" required="yes" type="numeric"> <cfargument name="jpegCompression" required="no" type="numeric" default="#variables.defaultJpegCompression#"> <cfset var retVal = StructNew()> <cfset var img = ""> <cfset var loadImage = StructNew()> <cfset var saveImage = StructNew()> <cfset var at = ""> <cfset var op = ""> <cfset var w = 0> <cfset var h = 0> <cfset var iw = 0> <cfset var ih = 0> <cfset var x = 0> <cfset var y = 0> <cfset var rotatedImage = ""> <cfset var rh = getRenderingHints()> <cfset retVal.errorCode = 0> <cfset retVal.errorMessage = ""> <cfif inputFile neq ""> <cfset loadImage = readImage(inputFile, "NO")> <cfif loadImage.errorCode is 0> <cfset img = loadImage.img> <cfelse> <cfset retVal = throw(loadImage.errorMessage)> <cfreturn retVal> </cfif> <cfelse> <cfset img = objImage> </cfif> <cfif img.getType() eq 0> <cfset img = convertImageObject(img,img.TYPE_3BYTE_BGR)> </cfif> <cfif ListFind("-270,-180,-90,90,180,270",degrees) is 0> <cfset retVal = throw( "At this time, image.cfc only supports rotating images in 90 degree increments.")> <cfreturn retVal> </cfif> <cfscript> rotatedImage = CreateObject("java", "java.awt.image.BufferedImage"); at = CreateObject("java", "java.awt.geom.AffineTransform"); op = CreateObject("java", "java.awt.image.AffineTransformOp"); iw = img.getWidth(); h = iw; ih = img.getHeight(); w = ih; if(arguments.degrees eq 180) { w = iw; h = ih; } x = (w/2)-(iw/2); y = (h/2)-(ih/2); rotatedImage.init(javacast("int",w),javacast("int",h),img.getType()); at.rotate(arguments.degrees * 0.0174532925,w/2,h/2); at.translate(x,y); op.init(at, rh); op.filter(img, rotatedImage); if (outputFile eq "") { retVal.img = rotatedImage; return retVal; } else { saveImage = writeImage(outputFile, rotatedImage, jpegCompression); if (saveImage.errorCode gt 0) { return saveImage; } else { return retVal; } } </cfscript> </cffunction> <cffunction name="convert" access="public" output="true" returntype="struct" hint="Convert an image from one format to another."> <cfargument name="objImage" required="yes" type="Any"> <cfargument name="inputFile" required="yes" type="string"> <cfargument name="outputFile" required="yes" type="string"> <cfargument name="jpegCompression" required="no" type="numeric" default="#variables.defaultJpegCompression#"> <cfset var retVal = StructNew()> <cfset var loadImage = StructNew()> <cfset var saveImage = StructNew()> <cfset var img = ""> <cfset retVal.errorCode = 0> <cfset retVal.errorMessage = ""> <cfif inputFile neq ""> <cfset loadImage = readImage(inputFile, "NO")> <cfif loadImage.errorCode is 0> <cfset img = loadImage.img> <cfelse> <cfset retVal = throw(loadImage.errorMessage)> <cfreturn retVal> </cfif> <cfelse> <cfset img = objImage> </cfif> <cfscript> if (outputFile eq "") { retVal = throw( "The convert method requires a valid output filename."); return retVal; } else { saveImage = writeImage(outputFile, img, jpegCompression); if (saveImage.errorCode gt 0) { return saveImage; } else { return retVal; } } </cfscript> </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"> <cfset var validKeys = "interpolation,textantialiasing,throwonerror,defaultJpegCompression"> <cfset arguments.key = lcase(trim(arguments.key))> <cfset arguments.val = lcase(trim(arguments.val))> <cfif listFind(validKeys, arguments.key) gt 0> <cfset variables[arguments.key] = arguments.val> </cfif> </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"> <cfset var validKeys = "interpolation,textantialiasing,throwonerror,defaultJpegCompression"> <cfset arguments.key = lcase(trim(arguments.key))> <cfif listFindNoCase(validKeys, arguments.key) gt 0> <cfreturn variables[arguments.key]> <cfelse> <cfreturn ""> </cfif> </cffunction> <cffunction name="getRenderingHints" access="private" output="true" returnType="any" hint="Internal method controls various aspects of rendering quality."> <cfset var rh = CreateObject("java","java.awt.RenderingHints")> <cfset var initMap = CreateObject("java","java.util.HashMap")> <cfset initMap.init()> <cfset rh.init(initMap)> <cfset rh.put(rh.KEY_ALPHA_INTERPOLATION, rh.VALUE_ALPHA_INTERPOLATION_QUALITY)> <!--- QUALITY, SPEED, DEFAULT ---> <cfset rh.put(rh.KEY_ANTIALIASING, rh.VALUE_ANTIALIAS_ON)> <!--- ON, OFF, DEFAULT ---> <cfset rh.put(rh.KEY_COLOR_RENDERING, rh.VALUE_COLOR_RENDER_QUALITY)> <!--- QUALITY, SPEED, DEFAULT ---> <cfset rh.put(rh.KEY_DITHERING, rh.VALUE_DITHER_DEFAULT)> <!--- DISABLE, ENABLE, DEFAULT ---> <cfset rh.put(rh.KEY_RENDERING, rh.VALUE_RENDER_QUALITY)> <!--- QUALITY, SPEED, DEFAULT ---> <cfset rh.put(rh.KEY_FRACTIONALMETRICS, rh.VALUE_FRACTIONALMETRICS_DEFAULT)> <!--- DISABLE, ENABLE, DEFAULT ---> <cfset rh.put(rh.KEY_STROKE_CONTROL, rh.VALUE_STROKE_DEFAULT)> <cfif variables.textAntiAliasing> <cfset rh.put(rh.KEY_TEXT_ANTIALIASING, rh.VALUE_TEXT_ANTIALIAS_ON)> <cfelse> <cfset rh.put(rh.KEY_TEXT_ANTIALIASING, rh.VALUE_TEXT_ANTIALIAS_OFF)> </cfif> <cfif variables.interpolation eq "nearest_neighbor"> <cfset rh.put(rh.KEY_INTERPOLATION, rh.VALUE_INTERPOLATION_NEAREST_NEIGHBOR)> <cfelseif variables.interpolation eq "bilinear"> <cfset rh.put(rh.KEY_INTERPOLATION, rh.VALUE_INTERPOLATION_BILINEAR)> <cfelse> <cfset rh.put(rh.KEY_INTERPOLATION, rh.VALUE_INTERPOLATION_BICUBIC)> </cfif> <cfreturn rh> </cffunction> <cffunction name="readImage" access="public" output="true" returntype="struct" hint="Reads an image from a local file. Requires an absolute path."> <cfargument name="source" required="yes" type="string"> <cfargument name="forModification" required="no" type="boolean" default="yes"> <cfif isURL(source)> <cfreturn readImageFromURL(source, forModification)> <cfelse> <cfreturn readImageFromFile(source, forModification)> </cfif> </cffunction> <cffunction name="readImageFromFile" access="private" output="true" returntype="struct" hint="Reads an image from a local file. Requires an absolute path."> <cfargument name="inputFile" required="yes" type="string"> <cfargument name="forModification" required="no" type="boolean" default="yes"> <cfset var retVal = StructNew()> <cfset var img = ""> <cfset var inFile = ""> <cfset var filename = getFileFromPath(inputFile)> <cfset var extension = lcase(listLast(inputFile,"."))> <cfset var imageIO = CreateObject("java", "javax.imageio.ImageIO")> <cfset var validExtensionsToRead = ArrayToList(imageIO.getReaderFormatNames())> <cfset retVal.errorCode = 0> <cfset retVal.errorMessage = ""> <cfif not fileExists(arguments.inputFile)> <cfset retVal = throw("The specified file #Chr(34)##arguments.inputFile##Chr(34)# could not be found.")> <cfreturn retVal> <cfelseif listLen(filename,".") lt 2> <cfset retVal = throw("Sorry, image files without extensions cannot be manipulated.")> <cfreturn retVal> <cfelseif listFindNoCase(validExtensionsToRead, extension) is 0> <cfset retVal = throw("Java is unable to read #extension# files.")> <cfreturn retVal> <cfelseif NOT fileExists(arguments.inputFile)> <cfset retVal = throw("The specified input file does not exist.")> <cfreturn retVal> <cfelse> <cfset img = CreateObject("java", "java.awt.image.BufferedImage")> <cfset inFile = CreateObject("java", "java.io.File")> <cfset inFile.init(arguments.inputFile)> <cfif NOT inFile.canRead()> <cfset retVal = throw("Unable to open source file #Chr(34)##arguments.inputFile##Chr(34)#.")> <cfreturn retVal> <cfelse> <cftry> <cfset img = imageIO.read(inFile)> <cfcatch type="any"> <cfset retval = throw("An error occurred attempting to read the specified image. #cfcatch.message# - #cfcatch.detail#")> <cfreturn retVal> </cfcatch> </cftry> <cfset retVal.img = img> <cfset retVal.inFile = inFile> <cfreturn retVal> </cfif> </cfif> </cffunction> <cffunction name="readImageFromURL" access="private" output="true" returntype="struct" hint="Read an image from a URL. Requires an absolute URL."> <cfargument name="inputURL" required="yes" type="string"> <cfargument name="forModification" required="no" type="boolean" default="yes"> <cfset var retVal = StructNew()> <cfset var img = CreateObject("java", "java.awt.image.BufferedImage")> <cfset var inURL = CreateObject("java", "java.net.URL")> <cfset var imageIO = CreateObject("java", "javax.imageio.ImageIO")> <cfset retVal.errorCode = 0> <cfset retVal.errorMessage = ""> <cfset inURL.init(arguments.inputURL)> <cftry> <cfset img = imageIO.read(inURL)> <cfcatch type="any"> <cfset retval = throw("An error occurred attempting to read the specified image. #cfcatch.message# - #cfcatch.detail#")> <cfreturn retVal> </cfcatch> </cftry> <cfset retVal.img = img> <cfreturn retVal> </cffunction> <cffunction name="writeImage" access="public" output="true" returntype="struct" hint="Write an image to disk."> <cfargument name="outputFile" required="yes" type="string"> <cfargument name="img" required="yes" type="any"> <cfargument name="jpegCompression" required="no" type="numeric" default="#variables.defaultJpegCompression#"> <cfset var retVal = StructNew()> <cfset var outFile = ""> <cfset var filename = getFileFromPath(outputFile)> <cfset var extension = lcase(listLast(filename,"."))> <cfset var imageIO = CreateObject("java", "javax.imageio.ImageIO")> <cfset var validExtensionsToWrite = ArrayToList(imageIO.getWriterFormatNames())> <!--- used for jpeg output method ---> <cfset var out = ""> <cfset var fos = ""> <cfset var JPEGCodec = ""> <cfset var encoder = ""> <cfset var param = ""> <cfset var quality = javacast("float", jpegCompression/100)> <cfset var tempOutputFile = "#variables.tempDirectory#\#createUUID()#.#extension#"> <cfset retVal.errorCode = 0> <cfset retVal.errorMessage = ""> <cfif listFindNoCase(validExtensionsToWrite, extension) eq 0> <cfset throw("Java is unable to write #extension# files. Valid formats include: #validExtensionsToWrite#")> </cfif> <cfif extension neq "jpg" and extension neq "jpeg"> <!--- Simple output method for non jpeg images ---> <cfset outFile = CreateObject("java", "java.io.File")> <cfset outFile.init(tempOutputFile)> <cfset imageIO.write(img, extension, outFile)> <cfelse> <cfscript> /* JPEG output method handles compression */ out = createObject("java", "java.io.BufferedOutputStream"); fos = createObject("java", "java.io.FileOutputStream"); fos.init(tempOutputFile); out.init(fos); JPEGCodec = createObject("java", "com.sun.image.codec.jpeg.JPEGCodec"); encoder = JPEGCodec.createJPEGEncoder(out); param = encoder.getDefaultJPEGEncodeParam(img); param.setQuality(quality, false); encoder.setJPEGEncodeParam(param); encoder.encode(img); out.close(); </cfscript> </cfif> <!--- move file to its final destination ---> <cffile action="MOVE" source="#tempOutputFile#" destination="#arguments.outputFile#"> <cfreturn retVal> </cffunction> <cffunction name="flipflop" access="private" output="true" returntype="struct" hint="Internal method used for flipping and flopping images."> <cfargument name="objImage" required="yes" type="Any"> <cfargument name="inputFile" required="yes" type="string"> <cfargument name="outputFile" required="yes" type="string"> <cfargument name="direction" required="yes" type="string"><!--- horizontal or vertical ---> <cfargument name="jpegCompression" required="no" type="numeric" default="#variables.defaultJpegCompression#"> <cfset var retVal = StructNew()> <cfset var loadImage = StructNew()> <cfset var saveImage = StructNew()> <cfset var flippedImage = ""> <cfset var rh = getRenderingHints()> <cfset var img = ""> <cfset retVal.errorCode = 0> <cfset retVal.errorMessage = ""> <cfif inputFile neq ""> <cfset loadImage = readImage(inputFile, "NO")> <cfif loadImage.errorCode is 0> <cfset img = loadImage.img> <cfelse> <cfset retVal = throw(loadImage.errorMessage)> <cfreturn retVal> </cfif> <cfelse> <cfset img = objImage> </cfif> <cfif img.getType() eq 0> <cfset img = convertImageObject(img,img.TYPE_3BYTE_BGR)> </cfif> <cfscript> flippedImage = CreateObject("java", "java.awt.image.BufferedImage"); at = CreateObject("java", "java.awt.geom.AffineTransform"); op = CreateObject("java", "java.awt.image.AffineTransformOp"); flippedImage.init(img.getWidth(), img.getHeight(), img.getType()); if (direction eq "horizontal") { at = at.getScaleInstance(-1, 1); at.translate(-img.getWidth(), 0); } else { at = at.getScaleInstance(1,-1); at.translate(0, -img.getHeight()); } op.init(at, rh); op.filter(img, flippedImage); if (outputFile eq "") { retVal.img = flippedImage; return retVal; } else { saveImage = writeImage(outputFile, flippedImage, jpegCompression); if (saveImage.errorCode gt 0) { return saveImage; } else { return retVal; } } </cfscript> </cffunction> <cffunction name="filterFastBlur" access="public" output="true" returntype="struct" hint="Internal method used for flipping and flopping images."> <cfargument name="objImage" required="yes" type="Any"> <cfargument name="inputFile" required="yes" type="string"> <cfargument name="outputFile" required="yes" type="string"> <cfargument name="blurAmount" required="yes" type="numeric"> <cfargument name="iterations" required="yes" type="numeric"> <cfargument name="jpegCompression" required="no" type="numeric" default="#variables.defaultJpegCompression#"> <cfset var retVal = StructNew()> <cfset var loadImage = StructNew()> <cfset var saveImage = StructNew()> <cfset var srcImage = ""> <cfset var destImage = ""> <cfset var rh = getRenderingHints()> <cfset retVal.errorCode = 0> <cfset retVal.errorMessage = ""> <cfif NOT variables.javanulls> <cfset throw("Sorry, but the blur filter is not supported on this platform.")> </cfif> <cfif inputFile neq ""> <cfset loadImage = readImage(inputFile, "NO")> <cfif loadImage.errorCode is 0> <cfset srcImage = loadImage.img> <cfelse> <cfset retVal = throw(loadImage.errorMessage)> <cfreturn retVal> </cfif> <cfelse> <cfset srcImage = objImage> </cfif> <cfif srcImage.getType() eq 0> <cfset srcImage = convertImageObject(srcImage,srcImage.TYPE_3BYTE_BGR)> </cfif> <cfscript> // initialize the blur filter variables.blurFilter.init(arguments.blurAmount); // move the source image into the destination image // so we can repeatedly blur it. destImage = srcImage; for (i=1; i lte iterations; i=i+1) { // do the blur i times destImage = variables.blurFilter.filter(destImage); } if (outputFile eq "") { // return the image object retVal.img = destImage; return retVal; } else { // write the image object to the specified file. saveImage = writeImage(outputFile, destImage, jpegCompression); if (saveImage.errorCode gt 0) { return saveImage; } else { return retVal; } } </cfscript> </cffunction> <cffunction name="filterSharpen" access="public" output="true" returntype="struct" hint="Internal method used for flipping and flopping images."> <cfargument name="objImage" required="yes" type="Any"> <cfargument name="inputFile" required="yes" type="string"> <cfargument name="outputFile" required="yes" type="string"> <cfargument name="jpegCompression" required="no" type="numeric" default="#variables.defaultJpegCompression#"> <cfset var retVal = StructNew()> <cfset var loadImage = StructNew()> <cfset var saveImage = StructNew()> <cfset var srcImage = ""> <cfset var destImage = ""> <cfset var rh = getRenderingHints()> <cfset retVal.errorCode = 0> <cfset retVal.errorMessage = ""> <cfif NOT variables.javanulls> <cfset throw("Sorry, but the blur filter is not supported on this platform.")> </cfif> <cfif inputFile neq ""> <cfset loadImage = readImage(inputFile, "NO")> <cfif loadImage.errorCode is 0> <cfset srcImage = loadImage.img> <cfelse> <cfset retVal = throw(loadImage.errorMessage)> <cfreturn retVal> </cfif> <cfelse> <cfset srcImage = objImage> </cfif> <cfif srcImage.getType() eq 0> <cfset srcImage = convertImageObject(srcImage,srcImage.TYPE_3BYTE_BGR)> </cfif> <cfscript> // initialize the sharpen filter variables.sharpenFilter.init(); destImage = variables.sharpenFilter.filter(srcImage); if (outputFile eq "") { // return the image object retVal.img = destImage; return retVal; } else { // write the image object to the specified file. saveImage = writeImage(outputFile, destImage, jpegCompression); if (saveImage.errorCode gt 0) { return saveImage; } else { return retVal; } } </cfscript> </cffunction> <cffunction name="filterPosterize" access="public" output="true" returntype="struct" hint="Internal method used for flipping and flopping images."> <cfargument name="objImage" required="yes" type="Any"> <cfargument name="inputFile" required="yes" type="string"> <cfargument name="outputFile" required="yes" type="string"> <cfargument name="amount" required="yes" type="string"> <cfargument name="jpegCompression" required="no" type="numeric" default="#variables.defaultJpegCompression#"> <cfset var retVal = StructNew()> <cfset var loadImage = StructNew()> <cfset var saveImage = StructNew()> <cfset var srcImage = ""> <cfset var destImage = ""> <cfset var rh = getRenderingHints()> <cfset retVal.errorCode = 0> <cfset retVal.errorMessage = ""> <cfif NOT variables.javanulls> <cfset throw("Sorry, but the blur filter is not supported on this platform.")> </cfif> <cfif inputFile neq ""> <cfset loadImage = readImage(inputFile, "NO")> <cfif loadImage.errorCode is 0> <cfset srcImage = loadImage.img> <cfelse> <cfset retVal = throw(loadImage.errorMessage)> <cfreturn retVal> </cfif> <cfelse> <cfset srcImage = objImage> </cfif> <cfif srcImage.getType() eq 0> <cfset srcImage = convertImageObject(srcImage,srcImage.TYPE_3BYTE_BGR)> </cfif> <cfif srcImage.getType() neq 5> <cfset throw("ImageCFC cannot posterize this image type (#srcImage.getType()#)")> </cfif> <cfscript> // initialize the posterize filter variables.posterizeFilter.init(arguments.amount); destImage = variables.posterizeFilter.filter(srcImage); if (outputFile eq "") { // return the image object retVal.img = destImage; return retVal; } else { // write the image object to the specified file. saveImage = writeImage(outputFile, destImage, jpegCompression); if (saveImage.errorCode gt 0) { return saveImage; } else { return retVal; } } </cfscript> </cffunction> <cffunction name="addText" access="public" output="true" returntype="struct" hint="Add text to an image."> <cfargument name="objImage" required="yes" type="Any"> <cfargument name="inputFile" required="yes" type="string"> <cfargument name="outputFile" required="yes" type="string"> <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"> <cfargument name="jpegCompression" required="no" type="numeric" default="#variables.defaultJpegCompression#"> <cfset var retVal = StructNew()> <cfset var loadImage = StructNew()> <cfset var img = ""> <cfset var saveImage = StructNew()> <cfset var g2d = ""> <cfset var bgImage = ""> <cfset var fontImage = ""> <cfset var overlayImage = ""> <cfset var Color = ""> <cfset var font = ""> <cfset var font_stream = ""> <cfset var ac = ""> <cfset var rgb = ""> <cfset retVal.errorCode = 0> <cfset retVal.errorMessage = ""> <cfparam name="arguments.fontDetails.size" default="12"> <cfparam name="arguments.fontDetails.color" default="black"> <cfparam name="arguments.fontDetails.fontFile" default=""> <cfparam name="arguments.fontDetails.fontName" default="serif"> <cfif arguments.fontDetails.fontFile neq "" and not fileExists(arguments.fontDetails.fontFile)> <cfset retVal = throw("The specified font file #Chr(34)##arguments.inputFile##Chr(34)# could not be found on the server.")> <cfreturn retVal> </cfif> <cftry> <cfset rgb = getRGB(arguments.fontDetails.color)> <cfcatch type="any"> <cfset retVal = throw("Invalid color #Chr(34)##arguments.fontDetails.color##Chr(34)#")> <cfreturn retVal> </cfcatch> </cftry> <cfif inputFile neq ""> <cfset loadImage = readImage(inputFile, "NO")> <cfif loadImage.errorCode is 0> <cfset img = loadImage.img> <cfelse> <cfset retVal = throw(loadImage.errorMessage)> <cfreturn retVal> </cfif> <cfelse> <cfset img = objImage> </cfif> <cfif img.getType() eq 0> <cfset img = convertImageObject(img,img.TYPE_3BYTE_BGR)> </cfif> <cfscript> // load objects bgImage = CreateObject("java", "java.awt.image.BufferedImage"); fontImage = CreateObject("java", "java.awt.image.BufferedImage"); overlayImage = CreateObject("java", "java.awt.image.BufferedImage"); Color = CreateObject("java","java.awt.Color"); font = createObject("java","java.awt.Font"); font_stream = createObject("java","java.io.FileInputStream"); ac = CreateObject("Java", "java.awt.AlphaComposite"); // set up basic needs fontColor = Color.init(javacast("int", rgb.red), javacast("int", rgb.green), javacast("int", rgb.blue)); if (fontDetails.fontFile neq "") { font_stream.init(arguments.fontDetails.fontFile); font = font.createFont(font.TRUETYPE_FONT, font_stream); font = font.deriveFont(javacast("float",arguments.fontDetails.size)); } else { font.init(fontDetails.fontName, evaluate(fontDetails.style), fontDetails.size); } // get font metrics using a 1x1 bufferedImage fontImage.init(1,1,img.getType()); g2 = fontImage.createGraphics(); g2.setRenderingHints(getRenderingHints()); fc = g2.getFontRenderContext(); bounds = font.getStringBounds(content,fc); g2 = img.createGraphics(); g2.setRenderingHints(getRenderingHints()); g2.setFont(font); g2.setColor(fontColor); // in case you want to change the alpha // g2.setComposite(ac.getInstance(ac.SRC_OVER, 0.50)); // the location (arguments.fontDetails.size+y) doesn't really work // the way I want it to. g2.drawString(content,javacast("int",x),javacast("int",arguments.fontDetails.size+y)); if (outputFile eq "") { retVal.img = img; return retVal; } else { saveImage = writeImage(outputFile, img, jpegCompression); if (saveImage.errorCode gt 0) { return saveImage; } else { return retVal; } } </cfscript> </cffunction> <cffunction name="watermark" access="public" output="false"> <cfargument name="objImage1" required="yes" type="Any"> <cfargument name="objImage2" required="yes" type="Any"> <cfargument name="inputFile1" required="yes" type="string"> <cfargument name="inputFile2" required="yes" type="string"> <cfargument name="alpha" required="yes" type="numeric"> <cfargument name="placeAtX" required="yes" type="numeric"> <cfargument name="placeAtY" required="yes" type="numeric"> <cfargument name="outputFile" required="yes" type="string"> <cfargument name="jpegCompression" required="no" type="numeric" default="#variables.defaultJpegCompression#"> <cfset var retVal = StructNew()> <cfset var loadImage = StructNew()> <cfset var originalImage = ""> <cfset var wmImage = ""> <cfset var saveImage = StructNew()> <cfset var ac = ""> <cfset var rh = getRenderingHints()> <cfset retVal.errorCode = 0> <cfset retVal.errorMessage = ""> <cfif inputFile1 neq ""> <cfset loadImage = readImage(inputFile1, "NO")> <cfif loadImage.errorCode is 0> <cfset originalImage = loadImage.img> <cfelse> <cfset retVal = throw(loadImage.errorMessage)> <cfreturn retVal> </cfif> <cfelse> <cfset originalImage = objImage1> </cfif> <cfif originalImage.getType() eq 0> <cfset originalImage = convertImageObject(originalImage,originalImage.TYPE_3BYTE_BGR)> </cfif> <cfif inputFile2 neq ""> <cfset loadImage = readImage(inputFile2, "NO")> <cfif loadImage.errorCode is 0> <cfset wmImage = loadImage.img> <cfelse> <cfset retVal = throw(loadImage.errorMessage)> <cfreturn retVal> </cfif> <cfelse> <cfset wmImage = objImage2> </cfif> <cfif wmImage.getType() eq 0> <cfset wmImage = convertImageObject(wmImage,wmImage.TYPE_3BYTE_BGR)> </cfif> <cfscript> at = CreateObject("java", "java.awt.geom.AffineTransform"); op = CreateObject("java", "java.awt.image.AffineTransformOp"); ac = CreateObject("Java", "java.awt.AlphaComposite"); gfx = originalImage.getGraphics(); gfx.setComposite(ac.getInstance(ac.SRC_OVER, alpha)); at.init(); // op.init(at,op.TYPE_BILINEAR); op.init(at, rh); gfx.drawImage(wmImage, op, javaCast("int",arguments.placeAtX), javacast("int", arguments.placeAtY)); gfx.dispose(); if (outputFile eq "") { retVal.img = originalImage; return retVal; } else { saveImage = writeImage(outputFile, originalImage, jpegCompression); if (saveImage.errorCode gt 0) { return saveImage; } else { return retVal; } } </cfscript> </cffunction> <cffunction name="isURL" access="private" output="false" returnType="boolean"> <cfargument name="stringToCheck" required="yes" type="string"> <cfif REFindNoCase("^(((https?:)\/\/))[-[:alnum:]\?%,\.\/&##!@:=\+~_]+[A-Za-z0-9\/]$",stringToCheck) NEQ 0> <cfreturn true> <cfelse> <cfreturn false> </cfif> </cffunction> <!--- function returns RGB values in a structure for hex or the 16 HTML named colors ---> <cffunction name="getRGB" access="private" output="true" returnType="struct"> <cfargument name="color" type="string" required="yes"> <cfset var retVal = structNew()> <cfset var cnt = 0> <cfset var namedColors = "aqua,black,blue,fuchsia,gray,green,lime,maroon,navy,olive,purple,red,silver,teal,white,yellow"> <cfset var namedColorsHexValues = "00ffff,000000,0000ff,ff00ff,808080,008000,00ff00,800000,000080,808080,ff0000,c0c0c0,008080,ffffff,ffff00"> <cfset retVal.red = 0> <cfset retVal.green = 0> <cfset retVal.blue = 0> <cfset arguments.color = trim(arguments.color)> <cfif len(arguments.color) is 0> <cfreturn retVal> <cfelseif listFind(namedColors, arguments.color) gt 0> <cfset arguments.color = listGetAt(namedColorsHexValues, listFind(namedColors, arguments.color))> </cfif> <cfif left(arguments.color,1) eq "##"> <cfset arguments.color = right(arguments.color,len(arguments.color)-1)> </cfif> <cfif len(arguments.color) neq 6> <cfreturn retVal> <cfelse> <cftry> <cfset retVal.red = InputBaseN(mid(arguments.color,1,2),16)> <cfset retVal.green = InputBaseN(mid(arguments.color,3,2),16)> <cfset retVal.blue = InputBaseN(mid(arguments.color,5,2),16)> <cfcatch type="any"> <cfset retVal.red = 0> <cfset retVal.green = 0> <cfset retVal.blue = 0> <cfreturn retVal> </cfcatch> </cftry> </cfif> <cfreturn retVal> </cffunction> <cffunction name="throw" access="private" output="false" returnType="struct"> <cfargument name="detail" type="string" required="yes"> <cfargument name="force" type="boolean" required="no" default="no"> <cfset var retVal = StructNew()> <cfif variables.throwOnError or arguments.force> <cfthrow detail="#arguments.detail#" message="#arguments.detail#"> <cfelse> <cfset retVal.errorCode = 1> <cfset retVal.errorMessage = arguments.detail> <cfreturn retVal> </cfif> </cffunction> <cffunction name="debugDump" access="private"> <cfdump var="#arguments#"><cfabort> </cffunction> <cffunction name="convertImageObject" access="private" output="false" returnType="any"> <cfargument name="bImage" type="Any" required="yes"> <cfargument name="type" type="numeric" required="yes"> <cfscript> // convert the image to a specified BufferedImage type and return it var width = bImage.getWidth(); var height = bImage.getHeight(); var newImage = createObject("java","java.awt.image.BufferedImage").init(javacast("int",width), javacast("int",height), javacast("int",type)); // int[] rgbArray = new int[width*height]; var rgbArray = variables.arrObj.newInstance(variables.intClass, javacast("int",width*height)); bImage.getRGB( javacast("int",0), javacast("int",0), javacast("int",width), javacast("int",height), rgbArray, javacast("int",0), javacast("int",width) ); newImage.setRGB( javacast("int",0), javacast("int",0), javacast("int",width), javacast("int",height), rgbArray, javacast("int",0), javacast("int",width) ); return newImage; </cfscript> </cffunction> </cfcomponent>
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/cfm/image.cfc
ColdFusion CFC
asf20
47,065
<cfsetting enablecfoutputonly="yes" showdebugoutput="no"> <!--- * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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"> <!--- 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"> <cffunction name="SendError" returntype="void" output="true"> <cfargument name="number" required="true" type="Numeric"> <cfargument name="text" required="true"> <cfreturn SendUploadResults( "#ARGUMENTS.number#", "", "", "#ARGUMENTS.text#" )> </cffunction> <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 = "/"> <!--- 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 )>
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/cfm/cf_upload.cfm
ColdFusion
asf20
2,288
<cfsetting enablecfoutputonly="yes" showdebugoutput="no"> <!--- * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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>
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/cfm/cf_connector.cfm
ColdFusion
asf20
2,844
<cfsetting enablecfoutputonly="Yes"> <!--- * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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. * ---> <!--- disable connector for ColdFusion > CF5 ---> <cfif Left(SERVER.COLDFUSION.PRODUCTVERSION,Find(",",SERVER.COLDFUSION.PRODUCTVERSION)-1) gt 5> <cfabort> </cfif> <cfparam name="url.command" default="QuickUpload"> <cfparam name="url.type" default="File"> <cfparam name="url.currentFolder" default="/"> <cfif find( "/", getBaseTemplatePath() ) > <cfset REQUEST.Fs = "/"> <cfelse> <cfset REQUEST.Fs = "\"> </cfif> <cfif url.command eq "QuickUpload"> <cfset url.currentFolder = "/"> </cfif> <cfif not isDefined("REQUEST.config_included") or isDefined("URL.config_included")> <cfinclude template="config.cfm"> </cfif> <cfscript> function SendUploadResults(errorNumber, fileUrl, fileName, customMsg) { WriteOutput('<script type="text/javascript">'); // Minified version of the document.domain automatic fix script (#1919). // The original script can be found at _dev/domain_fix_template.js WriteOutput("(function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})();"); 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) or find( "\", url.currentFolder)> <cfset SendUploadResults(102, "", "", "")> <cfabort> </cfif> <cfif REFind('(/\.)|(//)|[[:cntrl:]]|([\\:\*\?\"<>])', 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> <cfelseif url.command eq "FileUpload"> <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> <cfif isDefined( "REQUEST.Config.TempDirectory" )> <cfset sTempDir = REQUEST.Config.TempDirectory> <cfelse> <cfset sTempDir = GetTempDirectory()> </cfif> <!--- first upload the file with an unique filename ---> <cffile action="upload" fileField="NewFile" destination="#sTempDir#" nameConflict="makeunique" mode="644" attributes="normal"> <cfif cffile.fileSize EQ 0> <cffile action="delete" file="#cffile.ServerDirectory##fs##cffile.ServerFile#"> <cfthrow> </cfif> <cfset sTempFilePath = CFFILE.ServerDirectory & REQUEST.fs & CFFILE.ServerFile> <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. counter = 0; tmpFileName = fileName; while( fileExists("#currentFolderPath##fileName#.#fileExt#") ) { fileExisted = true ; counter = counter + 1 ; fileName = tmpFileName & '(#counter#)' ; } </cfscript> <cfset destination = currentFolderPath & fileName & "." & fileExt> <cfif fileExisted> <cfset errorNumber = "201"> </cfif> <cftry> <cffile action="copy" source="#sTempFilePath#" destination="#destination#" mode="755"> <cfcatch type="any"> <cfset errorNumber = 102> </cfcatch> </cftry> <cftry> <cffile action="delete" file="#sTempFilePath#"> <cfcatch type="any"> </cfcatch> </cftry> </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#', replace( fileName & "." & fileExt, "'", "\'", "ALL"), "")> <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>
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/cfm/cf5_upload.cfm
ColdFusion
asf20
11,939
<cfsetting enablecfoutputonly="Yes"> <!--- * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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> <cfabort>
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/cfm/connector.cfm
ColdFusion
asf20
1,005
<cfsetting enablecfoutputonly="Yes"> <!--- * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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>
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/cfm/upload.cfm
ColdFusion
asf20
993
<cfsetting enablecfoutputonly="Yes"> <!--- * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 sTempDir = ""> <cfset var sTempFilePath = ""> <cfset var errorNumber = 0> <cfset var customMsg = ""> <cfset var counter = 0> <cfset var destination = ""> <cftry> <cfif isDefined( "REQUEST.Config.TempDirectory" )> <cfset sTempDir = REQUEST.Config.TempDirectory> <cfelse> <cfset sTempDir = GetTempDirectory()> </cfif> <cfif NOT DirectoryExists (sTempDir)> <cfthrow message="Invalid temporary directory: #sTempDir#"> </cfif> <cffile action="UPLOAD" filefield="NewFile" destination="#sTempDir#" 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> <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"> <cftry> <cffile action="copy" source="#sTempFilePath#" destination="#destination#" mode="755"> <cfcatch type="any"> <cfset errorNumber = 102> </cfcatch> </cftry> <cftry> <cffile action="delete" file="#sTempFilePath#"> <cfcatch type="any"> </cfcatch> </cftry> </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#" /></cfoutput> </cffunction>
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/cfm/cf_commands.cfm
ColdFusion
asf20
8,353
<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>
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/cfm/ImageObject.cfc
ColdFusion CFC
asf20
12,390
<cfsetting enablecfoutputonly="yes" showdebugoutput="no"> <!--- * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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. * ---> <!--- disable connector for ColdFusion > CF5 ---> <cfif Left(SERVER.COLDFUSION.PRODUCTVERSION,Find(",",SERVER.COLDFUSION.PRODUCTVERSION)-1) gt 5> <cfabort> </cfif> <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"> <cfset REQUEST.Config = Config> <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 invalidName = false; </cfscript> <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) or find("\",url.currentFolder) or REFind('(/\.)|(//)|[[:cntrl:]]|([\\:\*\?\"<>])', url.currentFolder)> <cfset invalidName = true> <cfset xmlContent = "<Error number=""102"" />"> <cfelseif isDefined("Config.ConfigAllowedCommands") and not ListFind(Config.ConfigAllowedCommands, url.command)> <cfset invalidName = true> <cfset xmlContent = '<Error number="1" text="The &quot;' & HTMLEditFormat(url.command) & '&quot; command isn''t allowed" />'> <cfelseif isDefined("Config.ConfigAllowedTypes") and not ListFind(Config.ConfigAllowedTypes, url.type)> <cfset invalidName = true> <cfset xmlContent = '<Error number="1" text="Invalid type specified" />'> </cfif> <cfset resourceTypeUrl = ""> <cfif not len(xmlContent)> <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") > <cfset resourceTypeDirectory = left( userFilesServerPath, Len(userFilesServerPath) - Len(url.currentFolder) )> </cfif> <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 REQUEST.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"); newFolderName = reReplace(newFolderName, '\.+', "_", "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 = 102> <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" ?>'; if (invalidName) { xmlHeader = xmlHeader & '<Connector>'; } else { xmlHeader = xmlHeader & '<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>
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/cfm/cf5_connector.cfm
ColdFusion
asf20
11,123
<cfsetting enablecfoutputonly="Yes"> <!--- * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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"> <cfif Len(ARGUMENTS.text)> <cfoutput><Error number="#ARGUMENTS.number#" text="#htmleditformat(ARGUMENTS.text)#" /></cfoutput> <cfelse> <cfoutput><Error number="#ARGUMENTS.number#" /></cfoutput> </cfif> </cffunction>
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/cfm/cf_basexml.cfm
ColdFusion
asf20
2,852
<cfsetting enablecfoutputonly="Yes"> <!--- * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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="true"> <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) or find( "\", sCurrentFolder) or REFind('(/\.)|(//)|[[:cntrl:]]|([\\:\*\?\"<>])', sCurrentFolder)> <cfif URL.Command eq "FileUpload" or URL.Command eq "QuickUpload"> <cfset SendUploadResults( 102, "", "", "") > <cfelse> <cfset SendError( 102, "" )> </cfif> </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 . \ / | : ? * " < > and control characters ---> <cfset sNewFolderName = rereplace( sNewFolderName, '\.+|\\+|\/+|\|+|\:+|\?+|\*+|"+|<+|>+|[[:cntrl:]]+', "_", "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=""> <cfif errorNumber and errorNumber neq 201> <cfset fileUrl = ""> <cfset fileName = ""> </cfif> <!--- Minified version of the document.domain automatic fix script (#1919). The original script can be found at _dev/domain_fix_template.js ---> <cfoutput> <script type="text/javascript"> (function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})(); 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 \ / | : ? * " < > and control characters ---> <cfset sNewFileName = rereplace( sNewFileName, '\\[.]+|\\+|\/+|\|+|\:+|\?+|\*+|"+|<+|>+|[[:cntrl:]]+', "_", "all" )> <cfreturn sNewFileName> </cffunction>
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/cfm/cf_io.cfm
ColdFusion
asf20
10,739
<cfsetting enablecfoutputonly="Yes"> <!--- * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 = false ; // 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" ; //Due to known issues with GetTempDirectory function, it is //recommended to set this vairiable to a valid directory //instead of using the GetTempDirectory function //(used by MX 6.0 and above) Config.TempDirectory = GetTempDirectory(); </cfscript> <cftry> <!--- code to maintain backwards compatibility with previous version of cfm connector ---> <cfif isDefined("application.userFilesPath")> <cflock scope="application" type="readonly" timeout="20"> <cfset config.userFilesPath = application.userFilesPath> </cflock> </cfif> <!--- catch potential "The requested scope application has not been enabled" exception ---> <cfcatch type="any"> </cfcatch> </cftry> <cfscript> // 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>
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/cfm/config.cfm
ColdFusion
asf20
6,875
<cfsetting enablecfoutputonly="Yes"> <!--- * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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>
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/cfm/cf_util.cfm
ColdFusion
asf20
3,986
<?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') ? '\\' : '/' ) ; }
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/php/phpcompat.php
PHP
asf20
359
<?php /* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 FindBadUtf8( $string ) { $regex = '([\x00-\x7F]'. '|[\xC2-\xDF][\x80-\xBF]'. '|\xE0[\xA0-\xBF][\x80-\xBF]'. '|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}'. '|\xED[\x80-\x9F][\x80-\xBF]'. '|\xF0[\x90-\xBF][\x80-\xBF]{2}'. '|[\xF1-\xF3][\x80-\xBF]{3}'. '|\xF4[\x80-\x8F][\x80-\xBF]{2}'. '|(.{1}))'; while (preg_match('/'.$regex.'/S', $string, $matches)) { if ( isset($matches[2])) { return true; } $string = substr($string, strlen($matches[0])); } return false; } function ConvertToXmlAttribute( $value ) { if ( defined( 'PHP_OS' ) ) { $os = PHP_OS ; } else { $os = php_uname() ; } if ( strtoupper( substr( $os, 0, 3 ) ) === 'WIN' || FindBadUtf8( $value ) ) { 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' ) ; //open_basedir restriction, see #1906 if ( $fp === false || !flock( $fp, LOCK_SH ) ) { return -1 ; } $chunk = fread( $fp, 1024 ) ; flock( $fp, LOCK_UN ) ; 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 ) { if (!@is_readable($filePath)) { return -1; } $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; } ?>
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/php/util.php
PHP
asf20
5,188
<?php /* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 ( $_GET['Command'] == 'FileUpload' ) SendUploadResults( $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 ) { if ($text) echo '<Error number="' . $number . '" text="' . htmlspecialchars( $text ) . '" />' ; else echo '<Error number="' . $number . '" />' ; } ?>
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/php/basexml.php
PHP
asf20
2,604
<?php /* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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. */ require('../../../../../../../global.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'] = true ; $Config['fcsyspicurlwhois'] = PICPATHsystem ;//图片前缀域名 // Path to user files relative to the document root. $Config['UserFilesPath'] = '/upfiles/'.date("Ym")."/" ; // 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") ; // After file is uploaded, sometimes it is required to change its permissions // so that it was possible to access it at the later time. // If possible, it is recommended to set more restrictive permissions, like 0755. // Set to 0 to disable this feature. // Note: not needed on Windows-based servers. $Config['ChmodOnUpload'] = 0777 ; // See comments above. // Used when creating folders that does not exist. $Config['ChmodOnFolderCreate'] = 0777 ; /* 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'] ; ?>
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/php/config.php
PHP
asf20
7,958
<?php /* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 ; } ?>
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/php/connector.php
PHP
asf20
2,324
<?php /* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 ) { global $Config ; $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 ( !empty($sParent) && !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' ) ; if ( isset( $Config['ChmodOnFolderCreate'] ) && !$Config['ChmodOnFolderCreate'] ) { mkdir( $folderPath ) ; } else { $permissions = 0777 ; if ( isset( $Config['ChmodOnFolderCreate'] ) ) { $permissions = $Config['ChmodOnFolderCreate'] ; } // To create the folder with 0777 permissions, we need to set umask to zero. $oldumask = umask(0) ; mkdir( $folderPath, $permissions ) ; 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( './' ) ; // #2124 ensure that no slash is at the end $sRealPath = rtrim($sRealPath,"\\/"); $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 ( !preg_match( '|/$|', $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, '..' ) || strpos( $sCurrentFolder, "\\" )) SendError( 102, '' ) ; if ( preg_match(",(/\.)|[[:cntrl:]]|(//)|(\\\\)|([\:\*\?\"\<\>\|]),", $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( '/\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[[:cntrl:]]/', '_', $sNewFolderName ) ; return $sNewFolderName ; } // Do a cleanup of the file name to avoid possible problems function SanitizeFileName( $sNewFileName ) { global $Config ; $sNewFileName = stripslashes( $sNewFileName ) ; //修改图片上传的命名方式是数字形式的 preg_match("/\.[\s\S]+$/",$sNewFileName,$arr); $sNewFileName=date("Ymdhis").$arr[0]; return $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( '/\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[[:cntrl:]]/', '_', $sNewFileName ) ; return $sNewFileName ; } // This is the function that sends the results of the uploading process. function SendUploadResults( $errorNumber, $fileUrl = '', $fileName = '', $customMsg = '' ) { // Minified version of the document.domain automatic fix script (#1919). // The original script can be found at _dev/domain_fix_template.js global $Config; echo <<<EOF <script type="text/javascript"> (function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})(); EOF; if ($errorNumber && $errorNumber != 201) { $fileUrl = ""; $fileName = ""; } $rpl = array( '\\' => '\\\\', '"' => '\\"' ) ; echo 'window.parent.OnUploadCompleted(' . $errorNumber . ',"' . strtr( $Config['fcsyspicurlwhois'].$fileUrl, $rpl ) . '","' . strtr( $fileName, $rpl ) . '", "' . strtr( $customMsg, $rpl ) . '") ;' ; echo '</script>' ; exit ; } ?>
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/php/io.php
PHP
asf20
9,447
<?php /* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 ) ; if ($oCurrentFolder !== false) { 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 ) ; if ($oCurrentFolder !== false) { 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 . '" />' ; } } } closedir( $oCurrentFolder ) ; } // 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 . '" />' ; } 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 = IsImageValid( $oFile['tmp_name'], $sExtension ) ) === false ) { $sErrorNumber = '202' ; } } if ( isset( $Config['HtmlExtensions'] ) ) { if ( !IsHtmlExtension( $sExtension, $Config['HtmlExtensions'] ) && ( $detectHtml = DetectHtml( $oFile['tmp_name'] ) ) === true ) { $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 ) ) { if ( isset( $Config['ChmodOnUpload'] ) && !$Config['ChmodOnUpload'] ) { break ; } $permissions = 0777; if ( isset( $Config['ChmodOnUpload'] ) && $Config['ChmodOnUpload'] ) { $permissions = $Config['ChmodOnUpload'] ; } $oldumask = umask(0) ; chmod( $sFilePath, $permissions ) ; umask( $oldumask ) ; } break ; } } if ( file_exists( $sFilePath ) ) { //previous checks failed, try once again if ( isset( $isImageValid ) && $isImageValid === -1 && IsImageValid( $sFilePath, $sExtension ) === false ) { @unlink( $sFilePath ) ; $sErrorNumber = '202' ; } else if ( isset( $detectHtml ) && $detectHtml === -1 && DetectHtml( $sFilePath ) === true ) { @unlink( $sFilePath ) ; $sErrorNumber = '202' ; } } } else $sErrorNumber = '202' ; } else $sErrorNumber = '202' ; $sFileUrl = CombinePaths( GetResourceTypePath( $resourceType, $sCommand ) , $currentFolder ) ; $sFileUrl = CombinePaths( $sFileUrl, $sFileName ) ; SendUploadResults( $sErrorNumber, $sFileUrl, $sFileName ) ; exit ; } ?>
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/php/commands.php
PHP
asf20
6,958
<?php /* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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 ) ; } /** * 循环建立文件夹 * @param $dir 路径要求传入物理路径 * @param $mode 权限模板,默认具有读写权限 */ function mkdirs($dir, $mode = 0777){ if (is_dir($dir) || @mkdir($dir, $mode)) return true; if (!mkdirs(dirname($dir), $mode)) return false; return @mkdir($dir, $mode); } // 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 = "/" ; // 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' ) ; //更新编辑器里的图片路径 mkdirs($SystemConest[0].$Config['UserFilesPath']); FileUpload( $sType, $sCurrentFolder, $sCommand ) ?>
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/php/upload.php
PHP
asf20
2,104
<!-- * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <script type="text/javascript"> // Automatically detect the correct document.domain (#1919). (function() { var d = document.domain ; while ( true ) { // Test if we can access a parent property. try { var test = window.opener.document.domain ; break ; } catch( e ) {} // Remove a domain part: www.mytest.example.com => mytest.example.com => example.com ... d = d.replace( /.*?(?:\.|$)/, '' ) ; if ( d.length == 0 ) break ; // It was not able to detect the domain. try { document.domain = d ; } catch (e) { break ; } } })() ; 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 = '' ; var date = new Date() frmUpload.action = sUploaderUrl + '?time=' + date.getTime(); if (document.getElementById('cmbType').value) { frmUpload.action = frmUpload.action + '&Type='+document.getElementById('cmbType').value; } if (document.getElementById('CurrentFolder').value) { frmUpload.action = frmUpload.action + '&CurrentFolder='+document.getElementById('CurrentFolder').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> Current Folder: <br> <input type="text" name="CurrentFolder" id="CurrentFolder" value="/"> </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>
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/uploadtest.html
HTML
asf20
5,580
<% ' FCKeditor - The text editor for Internet - http://www.fckeditor.net ' Copyright (C) 2003-2009 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", "" %>
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/asp/config.asp
Classic ASP
asf20
5,685
<% ' FCKeditor - The text editor for Internet - http://www.fckeditor.net ' Copyright (C) 2003-2009 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) sFolder = replace(sFolder, "\", "/") CombinePaths = RemoveFromEnd( sBasePath, "/" ) & "/" & RemoveFromStart( sFolder, "/" ) end function function CombineLocalPaths( sBasePath, sFolder) sFolder = replace(sFolder, "/", "\") ' The RemoveFrom* functions use RegExp, so we must escape the \ CombineLocalPaths = 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 = CombineLocalPaths( sResourceTypePath, folderPath ) End Function Sub CreateServerFolder( folderPath ) Dim oFSO Set oFSO = Server.CreateObject( "Scripting.FileSystemObject" ) Dim sParent sParent = oFSO.GetParentFolderName( folderPath ) ' If folderPath is a network path (\\server\folder\) then sParent is an empty string. ' Get out. if (sParent = "") then exit sub ' 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 = False 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 dim oRegex 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 OR InStr( 1, sCurrentFolder, "\" ) <> 0) Then SendError 102, "" End If Set oRegex = New RegExp oRegex.Global = True oRegex.Pattern = "(/\.)|(//)|([\\:\*\?\""\<\>\|]|[\u0000-\u001F]|\u007F)" if (oRegex.Test(sCurrentFolder)) 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 . \ / | : ? * " < > and control characters oRegex.Pattern = "(\.|\\|\/|\||:|\?|\*|""|\<|\>|[\u0000-\u001F]|\u007F)" 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 \ / | : ? * " < > and control characters oRegex.Pattern = "(\\|\/|\||:|\?|\*|""|\<|\>|[\u0000-\u001F]|\u007F)" 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"">" ' Minified version of the document.domain automatic fix script (#1919). ' The original script can be found at _dev/domain_fix_template.js Response.Write "(function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})();" Response.Write "window.parent.OnUploadCompleted(" & errorNumber & ",""" & Replace( fileUrl, """", "\""" ) & """,""" & Replace( fileName, """", "\""" ) & """,""" & Replace( customMsg , """", "\""" ) & """) ;" Response.Write "</script>" Response.End End Sub %>
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/asp/io.asp
Classic ASP
asf20
7,735
<%@ CodePage=65001 Language="VBScript"%> <% Option Explicit Response.Buffer = True %> <% ' FCKeditor - The text editor for Internet - http://www.fckeditor.net ' Copyright (C) 2003-2009 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"--> <% Sub SendError( number, text ) SendUploadResults number, "", "", text End Sub ' 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 = "/" ' 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 %>
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/asp/upload.asp
Classic ASP
asf20
1,884
<% ' FCKeditor - The text editor for Internet - http://www.fckeditor.net ' Copyright (C) 2003-2009 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 %>
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/asp/util.asp
Classic ASP
asf20
1,444
<% ' FCKeditor - The text editor for Internet - http://www.fckeditor.net ' Copyright (C) 2003-2009 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, CombineLocalPaths(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 & """ />" 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 = CombineLocalPaths(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 ) If ( sErrorNumber = "0" or sErrorNumber = "201" ) then SendUploadResults sErrorNumber, sFileUrl, sFileName, "" Else SendUploadResults sErrorNumber, "", "", "" End If End Sub %>
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/asp/commands.asp
Classic ASP
asf20
5,758
<% ' FCKeditor - The text editor for Internet - http://www.fckeditor.net ' Copyright (C) 2003-2009 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 %>
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/asp/class_upload.asp
Classic ASP
asf20
9,857
<% ' FCKeditor - The text editor for Internet - http://www.fckeditor.net ' Copyright (C) 2003-2009 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. on error resume next ' The CodePage property isn't supported in Windows 2000. #2604 Response.CodePage = 65001 on error goto 0 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"" ?>" If text <> "" then Response.Write "<Connector><Error number=""" & number & """ text=""" & Server.HTMLEncode( text ) & """ /></Connector>" else Response.Write "<Connector><Error number=""" & number & """ /></Connector>" end if Response.End End Sub %>
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/asp/basexml.asp
Classic ASP
asf20
2,082
<%@ CodePage=65001 Language="VBScript"%> <% Option Explicit Response.Buffer = True %> <% ' FCKeditor - The text editor for Internet - http://www.fckeditor.net ' Copyright (C) 2003-2009 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, "Invalid type specified" 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 %>
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/asp/connector.asp
Classic ASP
asf20
2,447
[//lasso /* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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' = (Encode_HTML: action_param('Command')), 'Type' = (Encode_HTML: 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' ); /*..................................................................... Custom tag sets the HTML response. */ define_tag( 'htmlreply', -namespace='fck_', -priority='replace', -required='uploadResult', -optional='NewFilePath', -type='string', -description='Sets the HTML response for the FCKEditor File Upload feature.' ); $__html_reply__ = '\ <script type="text/javascript"> (function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\\.|$)/,\'\');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})(); '; if($uploadResult == '0' || $uploadResult == '201'); $__html_reply__ = $__html_reply__ + '\ window.parent.OnUploadCompleted(' + $uploadResult + ',"' + $NewFilePath + '","' + $NewFilePath->split('/')->last + '"); </script> '; else; $__html_reply__ = $__html_reply__ + '\ window.parent.OnUploadCompleted(' + $uploadResult + ',"",""); </script> '; /if; /define_tag; /*..................................................................... Calculate the path to the current folder. */ $ServerPath == '' ? $ServerPath = $config->find('UserFilesPath'); var('currentFolderURL' = $ServerPath + $config->find('Subdirectories')->find(action_param('Type')) + $CurrentFolder ); $currentFolderURL = string_replace($currentFolderURL, -find='//', -replace='/'); if (!$config->find('Subdirectories')->find(action_param('Type'))); if($Command == 'FileUpload'); $responseType = 'html'; $uploadResult = '1'; fck_htmlreply( -uploadResult=$uploadResult ); else; $errorNumber = 1; $commandData += '<Error number="' + $errorNumber + '" text="Invalid type specified" />\n'; /if; else if($CurrentFolder->(Find: '..') || (String_FindRegExp: $CurrentFolder, -Find='(/\\.)|(//)|[\\\\:\\*\\?\\""\\<\\>\\|]|\\000|[\u007F]|[\u0001-\u001F]')); if($Command == 'FileUpload'); $responseType = 'html'; $uploadResult = '102'; fck_htmlreply( -uploadResult=$uploadResult ); else; $errorNumber = 102; $commandData += '<Error number="' + $errorNumber + '" />\n'; /if; else; /*..................................................................... Build the appropriate response per the 'Command' parameter. Wrap the entire process in an inline for file tag permissions. */ if($config->find('Enabled')); 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); if($size>0); $size = $size/1024; if ($size==0); $size = 1; /if; /if; $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'); $NewFolderName = (String_ReplaceRegExp: $NewFolderName, -find='\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|\\000|[\u007F]|[\u0001-\u001F]', -replace='_'); 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? */ if(file_uploads->size); $NewFile = file_uploads->get(1); else; $uploadResult = '202'; /if; 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'); $NewFileName = (String_ReplaceRegExp: $NewFileName, -find='\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|\\000|[\u007F]|[\u0001-\u001F]', -replace='_'); $NewFileName = (String_ReplaceRegExp: $NewFileName, -find='\\.(?![^.]*$)', -replace='_'); $OrigFilePath = $currentFolderURL + $NewFileName; $NewFilePath = $OrigFilePath; local('fileExtension') = '.' + $NewFile->find('OrigExtension'); #fileExtension = (String_ReplaceRegExp: #fileExtension, -find='\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|\\000|[\u007F]|[\u0001-\u001F]', -replace='_'); local('shortFileName') = $NewFileName->removetrailing(#fileExtension)&; /*..................................................... Make sure the file extension is allowed. */ local('allowedExt') = $config->find('AllowedExtensions')->find($Type); local('deniedExt') = $config->find('DeniedExtensions')->find($Type); if($allowedExt->Size > 0 && $allowedExt !>> $NewFile->find('OrigExtension')); $uploadResult = '202'; else($deniedExt->Size > 0 && $deniedExt >> $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 = file_currenterror( -errorcode); /select; /if; /if; fck_htmlreply( -uploadResult=$uploadResult, -NewFilePath=$NewFilePath ); case; $errorNumber = 1; $commandData += '<Error number="' + $errorNumber + '" text="Command isn\'t allowed" />\n'; /select; /inline; else; $errorNumber = 1; $commandData += '<Error number="' + $errorNumber + '" text="This file uploader is disabled. Please check the editor/filemanager/upload/lasso/config.lasso file." />\n'; /if; /if; /*..................................................................... 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" ?>'; if($errorNumber != '102'); $__html_reply__ += '<Connector command="' + (Encode_HTML: $Command) + '" resourceType="' + (Encode_HTML: $Type) + '">'; else; $__html_reply__ += '<Connector>'; /if; if($errorNumber != '102'); $__html_reply__ += '<CurrentFolder path="' + (Encode_HTML: $CurrentFolder) + '" url="' + (Encode_HTML: $currentFolderURL) + '" />'; /if; $__html_reply__ += $commandData + ' </Connector>'; /if; ]
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/lasso/connector.lasso
Lasso
asf20
11,642
[//lasso /* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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() ) ); ]
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/lasso/config.lasso
Lasso
asf20
2,359
[//lasso /* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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' = (Encode_HTML: action_param('Type')), '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')) + $CurrentFolder ); $currentFolderURL = string_replace($currentFolderURL, -find='//', -replace='/'); /*..................................................................... 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">'; // Minified version of the document.domain automatic fix script (#1919). // The original script can be found at _dev/domain_fix_template.js // Note: in Lasso replace \ with \\ $__html_reply__ = $__html_reply__ + "(function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})();"; $__html_reply__ = $__html_reply__ + '\ window.parent.OnUploadCompleted(' + #errorNumber + ',"' + string_replace((Encode_HTML: #fileUrl), -find='"', -replace='\\"') + '","' + string_replace((Encode_HTML: #fileUrl->split('/')->last), -find='"', -replace='\\"') + '","' + string_replace((Encode_HTML: #customMsg), -find='"', -replace='\\"') + '"); </script> '; /define_tag; if($CurrentFolder->(Find: '..') || (String_FindRegExp: $CurrentFolder, -Find='(/\\.)|(//)|[\\\\:\\*\\?\\""\\<\\>\\|]|\\000|[\u007F]|[\u0001-\u001F]')); $errorNumber = 102; /if; if($config->find('Enabled')); /*................................................................. Process an uploaded file. */ inline($connection); /*............................................................. Was a file actually uploaded? */ if($errorNumber != '102'); file_uploads->size ? $NewFile = file_uploads->get(1) | $errorNumber = 202; /if; 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'); $NewFileName = (String_ReplaceRegExp: $NewFileName, -find='\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|\\000|[\u007F]|[\u0001-\u001F]', -replace='_'); $NewFileName = (String_ReplaceRegExp: $NewFileName, -find='\\.(?![^.]*$)', -replace='_'); $OrigFilePath = $currentFolderURL + $NewFileName; $NewFilePath = $OrigFilePath; local('fileExtension') = '.' + $NewFile->find('OrigExtension'); local('shortFileName') = $NewFileName->removetrailing(#fileExtension)&; /*......................................................... Make sure the file extension is allowed. */ local('allowedExt') = $config->find('AllowedExtensions')->find($Type); local('deniedExt') = $config->find('DeniedExtensions')->find($Type); if($allowedExt->Size > 0 && $allowedExt !>> $NewFile->find('OrigExtension')); $errorNumber = 202; else($deniedExt->Size > 0 && $deniedExt >> $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; if ($errorNumber != 0 && $errorNumber != 201); $NewFilePath = ""; /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, -customMsg=$customMsg ); ]
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/lasso/upload.lasso
Lasso
asf20
6,159
<!-- * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <script type="text/javascript"> // Automatically detect the correct document.domain (#1919). (function() { var d = document.domain ; while ( true ) { // Test if we can access a parent property. try { var test = window.opener.document.domain ; break ; } catch( e ) {} // Remove a domain part: www.mytest.example.com => mytest.example.com => example.com ... d = d.replace( /.*?(?:\.|$)/, '' ) ; if ( d.length == 0 ) break ; // It was not able to detect the domain. try { document.domain = d ; } catch (e) { break ; } } })() ; 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>
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/test.html
HTML
asf20
5,672
<%@ 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-2009 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>
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/aspx/connector.aspx
ASP.NET
asf20
1,237
<%@ 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-2009 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>
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/aspx/config.ascx
ASP.NET
asf20
5,133
<%@ 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-2009 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>
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/aspx/upload.aspx
ASP.NET
asf20
1,221
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 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) if size > 0: size = round(size/1024) if size < 1: size = 1 files += """<File name="%s" size="%d" />""" % ( convertToXmlAttribute(someObject), size ) # 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 try: permissions = Config.ChmodOnFolderCreate if not permissions: os.makedirs(folderPath) except AttributeError: #ChmodOnFolderCreate undefined permissions = 0755 if permissions: 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(%d).%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 ): doChmod = False try: doChmod = Config.ChmodOnUpload permissions = Config.ChmodOnUpload except AttributeError: #ChmodOnUpload undefined doChmod = True permissions = 0755 if ( doChmod ): oldumask = os.umask(0) os.chmod( newFilePath, permissions ) os.umask( oldumask ) newFileUrl = combinePaths(self.webUserFilesFolder, currentFolder) + newFileName return self.sendUploadResults( errorNo , newFileUrl, newFileName ) else: return self.sendUploadResults( errorNo = 202, customMsg = "" ) else: return self.sendUploadResults( errorNo = 202, customMsg = "No File" )
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/py/fckcommands.py
Python
asf20
6,537
#!/usr/bin/env python """ * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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'] # After file is uploaded, sometimes it is required to change its permissions # so that it was possible to access it at the later time. # If possible, it is recommended to set more restrictive permissions, like 0755. # Set to 0 to disable this feature. # Note: not needed on Windows-based servers. ChmodOnUpload = 0755 # See comments above. # Used when creating folders that does not exist. ChmodOnFolderCreate = 0755 # 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']
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/py/.svn/text-base/config.py.svn-base
Python
asf20
7,095
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 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 . \ / | : ? * " < > and control characters return re.sub( '\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[\x00-\x1f\x7f-\x9f]', '_', 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 ( '\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[\x00-\x1f\x7f-\x9f]/', '_', 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 or '\\' in currentFolder: return None # Check for invalid folder paths (..) if re.search( '(/\\.)|(//)|([\\\\:\\*\\?\\""\\<\\>\\|]|[\x00-\x1F]|[\x7f-\x9f])', 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 ]
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/py/.svn/text-base/fckutil.py.svn-base
Python
asf20
4,490
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 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()
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/py/.svn/text-base/wsgi.py.svn-base
Python
asf20
1,629
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 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) if size > 0: size = round(size/1024) if size < 1: size = 1 files += """<File name="%s" size="%d" />""" % ( convertToXmlAttribute(someObject), size ) # 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 try: permissions = Config.ChmodOnFolderCreate if not permissions: os.makedirs(folderPath) except AttributeError: #ChmodOnFolderCreate undefined permissions = 0755 if permissions: 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(%d).%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 ): doChmod = False try: doChmod = Config.ChmodOnUpload permissions = Config.ChmodOnUpload except AttributeError: #ChmodOnUpload undefined doChmod = True permissions = 0755 if ( doChmod ): oldumask = os.umask(0) os.chmod( newFilePath, permissions ) os.umask( oldumask ) newFileUrl = combinePaths(self.webUserFilesFolder, currentFolder) + newFileName return self.sendUploadResults( errorNo , newFileUrl, newFileName ) else: return self.sendUploadResults( errorNo = 202, customMsg = "" ) else: return self.sendUploadResults( errorNo = 202, customMsg = "No File" )
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/py/.svn/text-base/fckcommands.py.svn-base
Python
asf20
6,537
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 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 = "/" # 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()
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/py/.svn/text-base/upload.py.svn-base
Python
asf20
3,072
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 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
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/py/.svn/text-base/fckconnector.py.svn-base
Python
asf20
2,686
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 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: if (command == "FileUpload"): return self.sendUploadResults( errorNo = 102, customMsg = "" ) else: 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.createServerFolder( 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()
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/py/.svn/text-base/connector.py.svn-base
Python
asf20
4,239
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 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() """
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/py/.svn/text-base/zope.py.svn-base
Python
asf20
5,685
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 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): if number != 1: return """<Error number="%s" />""" % (number) else: 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" "Minified version of the document.domain automatic fix script (#1919)." "The original script can be found at _dev/domain_fix_template.js" return """<script type="text/javascript"> (function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})(); window.parent.OnUploadCompleted(%(errorNumber)s,"%(fileUrl)s","%(fileName)s","%(customMsg)s"); </script>""" % { 'errorNumber': errorNo, 'fileUrl': fileUrl.replace ('"', '\\"'), 'fileName': fileName.replace ( '"', '\\"' ) , 'customMsg': customMsg.replace ( '"', '\\"' ), }
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/py/.svn/text-base/fckoutput.py.svn-base
Python
asf20
4,042
#!/usr/bin/env python """ * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 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'] # After file is uploaded, sometimes it is required to change its permissions # so that it was possible to access it at the later time. # If possible, it is recommended to set more restrictive permissions, like 0755. # Set to 0 to disable this feature. # Note: not needed on Windows-based servers. ChmodOnUpload = 0755 # See comments above. # Used when creating folders that does not exist. ChmodOnFolderCreate = 0755 # 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']
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/py/config.py
Python
asf20
7,095
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 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
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/py/fckconnector.py
Python
asf20
2,686
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 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: if (command == "FileUpload"): return self.sendUploadResults( errorNo = 102, customMsg = "" ) else: 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.createServerFolder( 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()
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/py/connector.py
Python
asf20
4,239
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 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 . \ / | : ? * " < > and control characters return re.sub( '\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[\x00-\x1f\x7f-\x9f]', '_', 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 ( '\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[\x00-\x1f\x7f-\x9f]/', '_', 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 or '\\' in currentFolder: return None # Check for invalid folder paths (..) if re.search( '(/\\.)|(//)|([\\\\:\\*\\?\\""\\<\\>\\|]|[\x00-\x1F]|[\x7f-\x9f])', 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 ]
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/py/fckutil.py
Python
asf20
4,490
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 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): if number != 1: return """<Error number="%s" />""" % (number) else: 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" "Minified version of the document.domain automatic fix script (#1919)." "The original script can be found at _dev/domain_fix_template.js" return """<script type="text/javascript"> (function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})(); window.parent.OnUploadCompleted(%(errorNumber)s,"%(fileUrl)s","%(fileName)s","%(customMsg)s"); </script>""" % { 'errorNumber': errorNo, 'fileUrl': fileUrl.replace ('"', '\\"'), 'fileName': fileName.replace ( '"', '\\"' ) , 'customMsg': customMsg.replace ( '"', '\\"' ), }
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/py/fckoutput.py
Python
asf20
4,042
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 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()
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/py/wsgi.py
Python
asf20
1,629
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 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 = "/" # 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()
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/py/upload.py
Python
asf20
3,072
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 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() """
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/py/zope.py
Python
asf20
5,685
##### # FCKeditor - The text editor for Internet - http://www.fckeditor.net # Copyright (C) 2003-2009 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" ?>' ; if ($text) { print '<Connector><Error number="' . $number . '" text="' . &specialchar_cnv( $text ) . '" /></Connector>' ; } else { print '<Connector><Error number="' . $number . '" /></Connector>' ; } exit ; } 1;
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/perl/basexml.pl
Perl
asf20
1,770
##### # FCKeditor - The text editor for Internet - http://www.fckeditor.net # Copyright (C) 2003-2009 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)) { if (defined $CHMOD_ON_FOLDER_CREATE && !$CHMOD_ON_FOLDER_CREATE) { mkdir("$folderPath"); } else { umask(000); if (defined $CHMOD_ON_FOLDER_CREATE) { mkdir("$folderPath",$CHMOD_ON_FOLDER_CREATE); } else { mkdir("$folderPath",0777); } } 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;
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/perl/io.pl
Perl
asf20
2,923
##### # FCKeditor - The text editor for Internet - http://www.fckeditor.net # Copyright (C) 2003-2009 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; # After file is uploaded, sometimes it is required to change its permissions # so that it was possible to access it at the later time. # If possible, it is recommended to set more restrictive permissions, like 0755. # Set to 0 to disable this feature. $CHMOD_ON_UPLOAD = 0777; # See comments above. # Used when creating folders that does not exist. $CHMOD_ON_FOLDER_CREATE = 0755; # 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) = @_; if (defined $CHMOD_ON_FOLDER_CREATE && !$CHMOD_ON_FOLDER_CREATE) { mkdir("$img_dir"); } else { umask(000); if (defined $CHMOD_ON_FOLDER_CREATE) { mkdir("$img_dir",$CHMOD_ON_FOLDER_CREATE); } else { mkdir("$img_dir",0777); } } 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;
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/perl/upload_fck.pl
Perl
asf20
18,777
##### # FCKeditor - The text editor for Internet - http://www.fckeditor.net # Copyright (C) 2003-2009 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. ##### ## # SECURITY: REMOVE/COMMENT THE FOLLOWING LINE TO ENABLE THIS CONNECTOR. ## &SendError( 1, 'This connector is disabled. Please check the "editor/filemanager/connectors/perl/config.cgi" file' ) ; $GLOBALS{'UserFilesPath'} = '/userfiles/'; # Map the "UserFiles" path to a local directory. $rootpath = &GetRootPath(); $GLOBALS{'UserFilesDirectory'} = $rootpath . $GLOBALS{'UserFilesPath'}; %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", "Image", "bmp|gif|jpeg|jpg|png", "Flash", "swf|flv", "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" );
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/perl/config.pl
Raku
asf20
1,511
#!/usr/bin/env perl ##### # FCKeditor - The text editor for Internet - http://www.fckeditor.net # Copyright (C) 2003-2009 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 config.pl. ## ## 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'; require 'config.pl'; &read_input(); &DoResponse(); sub DoResponse { if($FORM{'Command'} eq "" || $FORM{'Type'} eq "" || $FORM{'CurrentFolder'} eq "") { return ; } # Get the main request informaiton. $sCommand = &specialchar_cnv($FORM{'Command'}); $sResourceType = &specialchar_cnv($FORM{'Type'}); $sCurrentFolder = $FORM{'CurrentFolder'}; if ( !($sCommand =~ /^(FileUpload|GetFolders|GetFoldersAndFiles|CreateFolder)$/) ) { SendError( 1, "Command not allowed" ) ; } if ( !($sResourceType =~ /^(File|Image|Flash|Media)$/) ) { SendError( 1, "Invalid type specified" ) ; } # 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, "" ) ; } if ( $sCurrentFolder =~ /(\/\.)|[[:cntrl:]]|(\/\/)|(\\\\)|([\:\*\?\"\<\>\|])/ ) { 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 ; }
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/perl/.svn/text-base/connector.cgi.svn-base
Perl
asf20
3,441
#!/usr/bin/env perl ##### # FCKeditor - The text editor for Internet - http://www.fckeditor.net # Copyright (C) 2003-2009 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 config.pl. ## ## 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'; require 'config.pl'; &read_input(); &DoResponse(); sub DoResponse { # Get the main request information. $sCommand = 'FileUpload'; $sResourceType = &specialchar_cnv($FORM{'Type'}); $sCurrentFolder = "/"; if ($sResourceType eq '') { $sResourceType = 'File' ; } if ( !($sResourceType =~ /^(File|Image|Flash|Media)$/) ) { SendError( 1, "Invalid type specified" ) ; } # File Upload doesn't have to Return XML, so it must be intercepted before anything. if($sCommand eq 'FileUpload') { FileUpload($sResourceType,$sCurrentFolder); return ; } }
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/perl/.svn/text-base/upload.cgi.svn-base
Perl
asf20
2,192
##### # FCKeditor - The text editor for Internet - http://www.fckeditor.net # Copyright (C) 2003-2009 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'}; $sNewFolderName =~ s/\.|\\|\/|\||\:|\?|\*|\"|<|>|[[:cntrl:]]/_/g; # 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 . '" />'; } sub FileUpload { eval("use File::Copy;"); local($resourceType, $currentFolder) = @_; $allowedExtensions = $allowedExtensions{$resourceType}; $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; $sFileName =~ s/\\|\/|\||\:|\?|\*|\"|<|>|[[:cntrl:]]/_/g; $sFileName =~ s/\.(?![^.]*$)/_/g; $ext = ''; if($sFileName =~ /([^\\\/]*)\.(.*)$/) { $ext = $2; } $allowedRegex = qr/^($allowedExtensions)$/i; if (!($ext =~ $allowedRegex)) { SendUploadResults('202', '', '', ''); } $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"); if (defined $CHMOD_ON_UPLOAD) { if ($CHMOD_ON_UPLOAD) { umask(000); chmod($CHMOD_ON_UPLOAD,$sFilePath); } } else { umask(000); chmod(0777,$sFilePath); } unlink("$img_dir/$new_fname"); last; } } } else { $sErrorNumber = '202' ; } $sFileName =~ s/"/\\"/g; SendUploadResults($sErrorNumber, $GLOBALS{'UserFilesPath'}.$resourceType.$currentFolder.$sFileName, $sFileName, ''); } sub SendUploadResults { local($sErrorNumber, $sFileUrl, $sFileName, $customMsg) = @_; # Minified version of the document.domain automatic fix script (#1919). # The original script can be found at _dev/domain_fix_template.js # Note: in Perl replace \ with \\ and $ with \$ print <<EOF; Content-type: text/html <script type="text/javascript"> (function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\\.|\$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})(); EOF print 'window.parent.OnUploadCompleted(' . $sErrorNumber . ',"' . JS_cnv($sFileUrl) . '","' . JS_cnv($sFileName) . '","' . JS_cnv($customMsg) . '") ;'; print '</script>'; exit ; } 1;
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/perl/commands.pl
Perl
asf20
5,712
##### # FCKeditor - The text editor for Internet - http://www.fckeditor.net # Copyright (C) 2003-2009 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(&specialchar_cnv($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;
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/perl/util.pl
Perl
asf20
1,409
#!/usr/bin/env perl ##### # FCKeditor - The text editor for Internet - http://www.fckeditor.net # Copyright (C) 2003-2009 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 config.pl. ## ## 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'; require 'config.pl'; &read_input(); &DoResponse(); sub DoResponse { # Get the main request information. $sCommand = 'FileUpload'; $sResourceType = &specialchar_cnv($FORM{'Type'}); $sCurrentFolder = "/"; if ($sResourceType eq '') { $sResourceType = 'File' ; } if ( !($sResourceType =~ /^(File|Image|Flash|Media)$/) ) { SendError( 1, "Invalid type specified" ) ; } # File Upload doesn't have to Return XML, so it must be intercepted before anything. if($sCommand eq 'FileUpload') { FileUpload($sResourceType,$sCurrentFolder); return ; } }
10npsite
trunk/guanli/system/fckeditor/editor/filemanager/connectors/perl/upload.cgi
Perl
asf20
2,192