- fixed problem pointed out by Nahuel Grisolia <ngrisolia@cybsec.com>

- moved aspell_path config to setup, vor obvious reasons
- removed not used non-php server scripts
This commit is contained in:
Ralf Becker 2010-03-07 10:45:33 +00:00
parent 4a0dfa2fc8
commit 84888a119b
65 changed files with 416 additions and 9929 deletions

View File

@ -117,13 +117,6 @@
<option value="True"{selected_enabled_spellcheck_True}>{lang_Yes}</option>
</select>
</td>
</tr>
<tr class="row_on">
<td>{lang_Complete_path_to_aspell_program}:</td>
<td>
<input name="newsettings[aspell_path]" value="{value_aspell_path}" size="40">
</td>
</tr>
<tr class="th">
@ -206,21 +199,21 @@
<input name="newsettings[num_unsuccessful_id]" value="{value_num_unsuccessful_id}" size="5">
</td>
</tr>
<tr class="row_off">
<td>{lang_After_how_many_unsuccessful_attempts_to_login,_an_IP_should_be_blocked_(default_3)_?}:</td>
<td>
<input name="newsettings[num_unsuccessful_ip]" value="{value_num_unsuccessful_ip}" size="5">
</td>
</tr>
<tr class="row_on">
<td>{lang_How_many_minutes_should_an_account_or_IP_be_blocked_(default_30)_?}:</td>
<td>
<input name="newsettings[block_time]" value="{value_block_time}" size="5">
</td>
</tr>
<tr class="row_off">
<td>{lang_Admin_email_addresses_(comma-separated)_to_be_notified_about_the_blocking_(empty_for_no_notify)}:</td>
<td>

View File

@ -1,7 +1,7 @@
<?php
/**
* eGW API - framework
*
*
* @link http://www.egroupware.org
* @author Ralf Becker <RalfBecker-AT-outdoor-training.de> rewrite in 12/2006
* @author Pim Snel <pim@lingewoud.nl> author of the idots template set
@ -14,7 +14,7 @@
/**
* eGW API - framework: virtual base class for all template sets
*
*
* This class creates / renders the eGW framework:
* a) html header
* b) navbar
@ -22,12 +22,12 @@
* d) main application area
* e) footer
* It replaces several methods in the common class and the diverse templates.
*
* Existing apps either set $GLOBALS['egw_info']['flags']['noheader'] and call $GLOBALS['egw']->common->egw_header() and
*
* Existing apps either set $GLOBALS['egw_info']['flags']['noheader'] and call $GLOBALS['egw']->common->egw_header() and
* (if $GLOBALS['egw_info']['flags']['nonavbar'] is true) parse_navbar() or it's done by the header.inc.php include.
* The app's hook_sidebox then calls the public function display_sidebox().
* And the app calls $GLOBALS['egw']->common->egw_footer().
*
*
* This are the authors (and their copyrights) of the original egw_header, egw_footer methods of the common class:
* This file written by Dan Kuykendall <seek3r@phpgroupware.org>
* and Joseph Engo <jengo@phpgroupware.org>
@ -47,7 +47,7 @@ class egw_framework
/**
* Constructor
*
*
* The constructor instanciates the class in $GLOBALS['egw']->framework, from where it should be used
*
* @return egw_framework
@ -61,24 +61,24 @@ class egw_framework
$GLOBALS['egw']->framework =& $this;
}
}
/**
* Renders an applicaton page with the complete eGW framework (header, navigation and menu)
*
*
* This is the (new) prefered way to render a page in eGW!
*
* @param string $content html of the main application area
* @param string $app_header=null application header, default what's set in $GLOBALS['egw_info']['flags']['app_header']
* @param string $navbar=null show the navigation, default !$GLOBALS['egw_info']['flags']['nonavbar'], false gives a typical popu
*
*
*/
function render($content,$app_header=null,$navbar=null)
{
if (!is_null($app_header)) $GLOBALS['egw_info']['flags']['app_header'] = $app_header;
if (!is_null($navbar)) $GLOBALS['egw_info']['flags']['nonavbar'] = !$navbar;
echo $this->header();
if (!isset($GLOBALS['egw_info']['flags']['nonavbar']) || !$GLOBALS['egw_info']['flags']['nonavbar'])
{
echo $this->navbar();
@ -95,7 +95,7 @@ class egw_framework
*/
function header()
{
die('virtual, need to be reimplemented in the template!!!');
die('virtual, need to be reimplemented in the template!!!');
}
/**
@ -105,9 +105,9 @@ class egw_framework
*/
function navbar()
{
die('virtual, need to be reimplemented in the template!!!');
die('virtual, need to be reimplemented in the template!!!');
}
/**
* Returns the content of one sidebox
*
@ -119,7 +119,7 @@ class egw_framework
{
die('virtual, need to be reimplemented in the template!!!');
}
/**
* Returns the html from the closing div of the main application area to the closing html-tag
*
@ -129,7 +129,7 @@ class egw_framework
{
die('virtual, need to be reimplemented in the template!!!');
}
/**
* displays a login screen
*
@ -140,7 +140,7 @@ class egw_framework
{
die('virtual, need to be reimplemented in the template!!!');
}
/**
* displays a login denied message
*
@ -150,7 +150,7 @@ class egw_framework
{
die('virtual, need to be reimplemented in the template!!!');
}
/**
* Get footer as array to eg. set as vars for a template (from idots' head.inc.php)
*
@ -165,13 +165,13 @@ class egw_framework
);
if($GLOBALS['egw_info']['user']['preferences']['common']['show_generation_time'])
{
$totaltime = sprintf('%4.2lf',perfgetmicrotime() - $GLOBALS['egw_info']['flags']['page_start_time']);
$totaltime = sprintf('%4.2lf',perfgetmicrotime() - $GLOBALS['egw_info']['flags']['page_start_time']);
$var['page_generation_time'] = '<div id="divGenTime"><br/><span>'.lang('Page was generated in %1 seconds',$totaltime).'</span></div>';
}
$var['powered_by'] = lang('Powered by').' <a href="'.$GLOBALS['egw_info']['server']['webserver_url'].'/about.php">eGroupWare</a> '.lang('version').' '.$GLOBALS['egw_info']['server']['versions']['phpgwapi'];
$var['activate_tooltips'] = '<script src="'.$GLOBALS['egw_info']['server']['webserver_url'].'/phpgwapi/js/wz_tooltip/wz_tooltip.js" type="text/javascript"></script>';
return $var;
}
@ -184,7 +184,7 @@ class egw_framework
{
ob_start();
// Include the apps footer files if it exists
if (EGW_APP_INC != EGW_API_INC && // this prevents an endless inclusion on the homepage
if (EGW_APP_INC != EGW_API_INC && // this prevents an endless inclusion on the homepage
// (some apps set currentapp in hook_home => it's not releyable)
(file_exists (EGW_APP_INC . '/footer.inc.php') || isset($_GET['menuaction'])) &&
$GLOBALS['egw_info']['flags']['currentapp'] != 'home' &&
@ -193,7 +193,7 @@ class egw_framework
!@$GLOBALS['egw_info']['flags']['noappfooter'])
{
list($app,$class,$method) = explode('.',(string)$_GET['menuaction']);
if ($class && is_object($GLOBALS[$class]) && is_array($GLOBALS[$class]->public_functions) &&
if ($class && is_object($GLOBALS[$class]) && is_array($GLOBALS[$class]->public_functions) &&
isset($GLOBALS[$class]->public_functions['footer']))
{
$GLOBALS[$class]->footer();
@ -206,7 +206,7 @@ class egw_framework
$content = ob_get_contents();
ob_end_clean();
return $content;
return $content;
}
/**
@ -217,20 +217,23 @@ class egw_framework
*/
function _get_header()
{
// get used language code
$lang_code = $GLOBALS['egw_info']['user']['preferences']['common']['lang'];
// get used language code (with a little xss check, if someone tries to sneak something in)
if (preg_match('/^[a-z]{2}(-[a-z]{2})?$/',$GLOBALS['egw_info']['user']['preferences']['common']['lang']))
{
$lang_code = $GLOBALS['egw_info']['user']['preferences']['common']['lang'];
}
//pngfix defaults to yes
if(!$GLOBALS['egw_info']['user']['preferences']['common']['disable_pngfix'])
{
$pngfix_src = $GLOBALS['egw_info']['server']['webserver_url'] . '/phpgwapi/templates/idots/js/pngfix.js';
$pngfix ='<!-- This solves the Internet Explorer PNG-transparency bug, but only for IE 5.5 and higher -->
$pngfix ='<!-- This solves the Internet Explorer PNG-transparency bug, but only for IE 5.5 and higher -->
<!--[if gte IE 5.5000]>
<script src="'.$pngfix_src.'" type="text/javascript">
</script>
<![endif]-->';
}
if(!$GLOBALS['egw_info']['user']['preferences']['common']['disable_slider_effects'])
{
$slider_effects_src = $GLOBALS['egw_info']['server']['webserver_url'] . '/phpgwapi/templates/idots/js/slidereffects.js';
@ -243,7 +246,7 @@ class egw_framework
$simple_show_hide = '<script src="'.$simple_show_hide_src.'" type="text/javascript">
</script>';
}
if ($GLOBALS['egw_info']['flags']['app_header'])
{
$app = $GLOBALS['egw_info']['flags']['app_header'];
@ -253,9 +256,9 @@ class egw_framework
$app = $GLOBALS['egw_info']['flags']['currentapp'];
$app = isset($GLOBALS['egw_info']['apps'][$app]) ? $GLOBALS['egw_info']['apps'][$app]['title'] : lang($app);
}
if($app!='wiki') $robots ='<meta name="robots" content="none" />';
return $this->_get_css()+array(
'img_icon' => EGW_IMAGES_DIR . '/favicon.ico',
'img_shortcut' => EGW_IMAGES_DIR . '/favicon.ico',
@ -294,12 +297,12 @@ class egw_framework
// current users for admins
$var['current_users'] = $this->_current_users();
// quick add selectbox
$var['quick_add'] = $this->_get_quick_add();
$var['user_info'] = $this->_user_time_info();
if($GLOBALS['egw_info']['user']['lastpasswd_change'] == 0)
{
@ -326,19 +329,19 @@ class egw_framework
$var['logo_file'] = $GLOBALS['egw']->common->image('phpgwapi',$GLOBALS['egw_info']['server']['login_logo_file']?$GLOBALS['egw_info']['server']['login_logo_file']:'logo');
}
$var['logo_url'] = $GLOBALS['egw_info']['server']['login_logo_url']?$GLOBALS['egw_info']['server']['login_logo_url']:'http://www.eGroupWare.org';
if (substr($var['logo_url'],0,4) != 'http')
{
$var['logo_url'] = 'http://'.$var['logo_url'];
}
$var['logo_title'] = $GLOBALS['egw_info']['server']['login_logo_title']?$GLOBALS['egw_info']['server']['login_logo_title']:'www.eGroupWare.org';
return $var;
}
/**
* Returns html with user and time
*
*
* @access protected
* @return void
*/
@ -356,7 +359,7 @@ class egw_framework
{
if( $GLOBALS['egw_info']['user']['apps']['admin'] && $GLOBALS['egw_info']['user']['preferences']['common']['show_currentusers'])
{
$current_users = '<a href="' . $GLOBALS['egw']->link('/index.php','menuaction=admin.uicurrentsessions.list_sessions') . '">' . lang('Current users') . ': ' . $GLOBALS['egw']->session->total() . '</a>';
$current_users = '<a href="' . $GLOBALS['egw']->link('/index.php','menuaction=admin.uicurrentsessions.list_sessions') . '">' . lang('Current users') . ': ' . $GLOBALS['egw']->session->total() . '</a>';
return $current_users;
}
}
@ -375,7 +378,7 @@ class egw_framework
}
$apps = $GLOBALS['egw']->link->app_list('add');
asort($apps); // sort them alphabetic
$options = array(lang('Add').' ...');
foreach($apps as $app => $label)
{
@ -397,17 +400,17 @@ class egw_framework
require_once(EGW_API_INC.'/class.html.inc.php');
$GLOBALS['egw']->html =& new html();
}
return $GLOBALS['egw']->html->select('quick_add','',$options,true,$options=' onchange="eval(this.value); this.value=0; return false;"');
return $GLOBALS['egw']->html->select('quick_add','',$options,true,$options=' onchange="eval(this.value); this.value=0; return false;"');
}
/**
* Prepare an array with apps used to render the navbar
*
*
* This is similar to the former common::navbar() method - though it returns the vars and does not place them in global scope.
*
* @internal PHP5 protected
* @static
* @static
* @return array
*/
function _get_navbar_apps()
@ -429,7 +432,7 @@ class egw_framework
unset($index);
unset($value);
unset($newarray);
$apps = array();
foreach($GLOBALS['egw_info']['user']['apps'] as $app => $data)
{
@ -500,10 +503,10 @@ class egw_framework
$apps['logout']['url'] = $GLOBALS['egw']->link('/logout.php');
$apps['logout']['icon'] = $GLOBALS['egw']->common->image('phpgwapi',Array('logout','nonav'));
$apps['logout']['icon_hover'] = $GLOBALS['egw']->common->image_on('phpgwapi',Array('logout','nonav'),'-over');
return $apps;
}
/**
* Used by template headers for including CSS in the header
*
@ -511,7 +514,7 @@ class egw_framework
* 'file_css' - link tag of the app.css file of the current app
* 'theme_css' - url of the theme css file
* 'print_css' - url of the print css file
*
*
* @internal PHP5 protected
* @author Dave Hall (*based* on verdilak? css inclusion code)
* @return array with keys 'app_css' from the css method of the menuaction-class and 'file_css' (app.css file of the application)
@ -542,7 +545,7 @@ class egw_framework
if (!file_exists(EGW_SERVER_ROOT.$css_file))
{
$css_file = '/'.$appname.'/templates/default/app.css';
if (!file_exists(EGW_SERVER_ROOT.$css_file)) $css_file = '';
}
if($css_file)
@ -565,7 +568,7 @@ class egw_framework
$print_css = '/phpgwapi/templates/idots/print.css';
}
$print_css = $GLOBALS['egw_info']['server']['webserver_url'] . $print_css .'?'.filemtime(EGW_SERVER_ROOT.$print_css);
return array(
'app_css' => $app_css,
'css_file' => $css_file,
@ -588,12 +591,12 @@ class egw_framework
function _get_js()
{
$java_script = '';
if(!@is_object($GLOBALS['egw']->js))
{
$GLOBALS['egw']->js =& CreateObject('phpgwapi.javascript');
}
// always include javascript helper functions
$GLOBALS['egw']->js->validate_file('jsapi','jsapi');
@ -608,18 +611,18 @@ class egw_framework
{
$GLOBALS['egw']->js->validate_jsapi();
}
if(@is_object($GLOBALS['egw']->js))
{
$java_script .= $GLOBALS['egw']->js->get_javascript_globals();
}
}
if ($GLOBALS['egw']->acl->check('run',1,'notifications') && !$GLOBALS['egw_info']['user']['preferences']['notifications']['disable_ajaxpopup'])
{
$GLOBALS['egw_info']['flags']['include_xajax'] = true;
}
if ($GLOBALS['egw_info']['flags']['include_xajax'])
{
require_once(EGW_SERVER_ROOT.'/phpgwapi/inc/xajax.inc.php');
@ -631,13 +634,13 @@ class egw_framework
$java_script .= $xajax->getJavascript($GLOBALS['egw_info']['server']['webserver_url'] . '/phpgwapi/js/');
}
/* this flag is for all javascript code that has to be put before other jscode.
/* this flag is for all javascript code that has to be put before other jscode.
Think of conf vars etc... (pim@lingewoud.nl) */
if (isset($GLOBALS['egw_info']['flags']['java_script_thirst']))
{
$java_script .= $GLOBALS['egw_info']['flags']['java_script_thirst'] . "\n";
}
if(@is_object($GLOBALS['egw']->js))
{
$java_script .= $GLOBALS['egw']->js->get_script_links();

View File

@ -500,18 +500,6 @@ class html
$spell = '_spellcheck';
$oFCKeditor->Config['SpellChecker'] = 'SpellerPages';
$oFCKeditor->Config['SpellerPagesServerScript'] = 'server-scripts/spellchecker.php?enabled=1';
if (isset($GLOBALS['egw_info']['server']['aspell_path']))
{
$oFCKeditor->Config['SpellerPagesServerScript'] .= '&aspell_path='.$GLOBALS['egw_info']['server']['aspell_path'];
}
if (isset($GLOBALS['egw_info']['user']['preferences']['common']['spellchecker_lang']))
{
$oFCKeditor->Config['SpellerPagesServerScript'] .= '&spellchecker_lang='.$GLOBALS['egw_info']['user']['preferences']['common']['spellchecker_lang'];
}
else
{
$oFCKeditor->Config['SpellerPagesServerScript'] .= '&spellchecker_lang='.$GLOBALS['egw_info']['user']['preferences']['common']['lang'];
}
$oFCKeditor->Config['FirefoxSpellChecker'] = false;
}
// Now setting the user preferences

View File

@ -1,148 +0,0 @@
<cfsetting enablecfoutputonly="true">
<!---
This code uses a CF User Defined Function and should work in CF version 5.0
and up without alteration.
Also if you are hosting your site at an ISP, you will have to check with them
to see if the use of <CFEXECUTE> is allowed. In most cases ISP will not allow
the use of that tag for security reasons. Clients would be able to access each
others files in certain cases.
--->
<!--- The following variables values must reflect your installation. --->
<cfset aspell_dir = "C:\Program Files\Aspell\bin">
<cfset lang = "en_US">
<cfset aspell_opts = "-a --lang=#lang# --encoding=utf-8 -H --rem-sgml-check=alt">
<cfset tempfile_in = GetTempFile(GetTempDirectory(), "spell_")>
<cfset tempfile_out = GetTempFile(GetTempDirectory(), "spell_")>
<cfset spellercss = "../spellerStyle.css">
<cfset word_win_src = "../wordWindow.js">
<cfset form.checktext = form["textinputs[]"]>
<!--- make no difference between URL and FORM scopes --->
<cfparam name="url.checktext" default="">
<cfparam name="form.checktext" default="#url.checktext#">
<!--- Takes care of those pesky smart quotes from MS apps, replaces them with regular quotes --->
<cfset submitted_text = ReplaceList(form.checktext,"%u201C,%u201D","%22,%22")>
<!--- submitted_text now is ready for processing --->
<!--- use carat on each line to escape possible aspell commands --->
<cfset text = "">
<cfset CRLF = Chr(13) & Chr(10)>
<cfloop list="#submitted_text#" index="field" delimiters=",">
<cfset text = text & "%" & CRLF
& "^A" & CRLF
& "!" & CRLF>
<!--- Strip all tags for the text. (by FredCK - #339 / #681) --->
<cfset field = REReplace(URLDecode(field), "<[^>]+>", " ", "all")>
<cfloop list="#field#" index="line" delimiters="#CRLF#">
<cfset text = ListAppend(text, "^" & Trim(JSStringFormat(line)), CRLF)>
</cfloop>
</cfloop>
<!--- create temp file from the submitted text, this will be passed to aspell to be check for misspelled words --->
<cffile action="write" file="#tempfile_in#" output="#text#" charset="utf-8">
<!--- execute aspell in an UTF-8 console and redirect output to a file. UTF-8 encoding is lost if done differently --->
<cfexecute name="cmd.exe" arguments='/c type "#tempfile_in#" | "#aspell_dir#\aspell.exe" #aspell_opts# > "#tempfile_out#"' timeout="100"/>
<!--- read output file for further processing --->
<cffile action="read" file="#tempfile_out#" variable="food" charset="utf-8">
<!--- remove temp files --->
<cffile action="delete" file="#tempfile_in#">
<cffile action="delete" file="#tempfile_out#">
<cfset texts = StructNew()>
<cfset texts.textinputs = "">
<cfset texts.words = "">
<cfset texts.abort = "">
<!--- Generate Text Inputs --->
<cfset i = 0>
<cfloop list="#submitted_text#" index="textinput">
<cfset texts.textinputs = ListAppend(texts.textinputs, 'textinputs[#i#] = decodeURIComponent("#textinput#");', CRLF)>
<cfset i = i + 1>
</cfloop>
<!--- Generate Words Lists --->
<cfset word_cnt = 0>
<cfset input_cnt = -1>
<cfloop list="#food#" index="aspell_line" delimiters="#CRLF#">
<cfset leftChar = Left(aspell_line, 1)>
<cfif leftChar eq "*">
<cfset input_cnt = input_cnt + 1>
<cfset word_cnt = 0>
<cfset texts.words = ListAppend(texts.words, "words[#input_cnt#] = [];", CRLF)>
<cfset texts.words = ListAppend(texts.words, "suggs[#input_cnt#] = [];", CRLF)>
<cfelse>
<cfif leftChar eq "&" or leftChar eq "##">
<!--- word that misspelled --->
<cfset bad_word = Trim(ListGetAt(aspell_line, 2, " "))>
<cfset bad_word = Replace(bad_word, "'", "\'", "ALL")>
<!--- sugestions --->
<cfset sug_list = Trim(ListRest(aspell_line, ":"))>
<cfset sug_list = ListQualify(Replace(sug_list, "'", "\'", "ALL"), "'")>
<!--- javascript --->
<cfset texts.words = ListAppend(texts.words, "words[#input_cnt#][#word_cnt#] = '#bad_word#';", CRLF)>
<cfset texts.words = ListAppend(texts.words, "suggs[#input_cnt#][#word_cnt#] = [#sug_list#];", CRLF)>
<cfset word_cnt = word_cnt + 1>
</cfif>
</cfif>
</cfloop>
<cfif texts.words eq "">
<cfset texts.abort = "alert('Spell check complete.\n\nNo misspellings found.'); top.window.close();">
</cfif>
<cfcontent type="text/html; charset=utf-8">
<cfoutput><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="#spellercss#" />
<script language="javascript" src="#word_win_src#"></script>
<script language="javascript">
var suggs = new Array();
var words = new Array();
var textinputs = new Array();
var error;
#texts.textinputs##CRLF#
#texts.words#
#texts.abort#
var wordWindowObj = new wordWindow();
wordWindowObj.originalSpellings = words;
wordWindowObj.suggestions = suggs;
wordWindowObj.textInputs = textinputs;
function init_spell() {
// check if any error occured during server-side processing
if( error ) {
alert( error );
} else {
// call the init_spell() function in the parent frameset
if (parent.frames.length) {
parent.init_spell( wordWindowObj );
} else {
alert('This page was loaded outside of a frameset. It might not display properly');
}
}
}
</script>
</head>
<body onLoad="init_spell();">
<script type="text/javascript">
wordWindowObj.writeBody();
</script>
</body>
</html></cfoutput>
<cfsetting enablecfoutputonly="false">

View File

@ -1,218 +1,240 @@
<?php
header('Content-type: text/html; charset=utf-8');
// The following variables values must reflect your installation needs.
//$aspell_prog = '"C:\Program Files\Aspell\bin\aspell.exe"'; // by FredCK (for Windows)
//$aspell_prog = 'aspell'; // by FredCK (for Linux)
if ($_GET['aspell_path'])
{
$aspell_prog = $_GET['aspell_path'];
}
else
{
$aspell_prog = 'aspell';
}
if ($_GET['spellchecker_lang'])
{
$lang = $_GET['spellchecker_lang'];
}
else
{
$lang = 'en_US';
}
//$lang = 'en_US';
$aspell_opts = "-a --lang=$lang --encoding=utf-8 -H --rem-sgml-check=alt"; // by FredCK
$tempfiledir = "./";
$spellercss = '../spellerStyle.css'; // by FredCK
$word_win_src = '../wordWindow.js'; // by FredCK
$textinputs = $_POST['textinputs']; # array
$input_separator = "A";
# set the JavaScript variable to the submitted text.
# textinputs is an array, each element corresponding to the (url-encoded)
# value of the text control submitted for spell-checking
function print_textinputs_var() {
global $textinputs;
foreach( $textinputs as $key=>$val ) {
# $val = str_replace( "'", "%27", $val );
echo "textinputs[$key] = decodeURIComponent(\"" . $val . "\");\n";
}
}
# make declarations for the text input index
function print_textindex_decl( $text_input_idx ) {
echo "words[$text_input_idx] = [];\n";
echo "suggs[$text_input_idx] = [];\n";
}
# set an element of the JavaScript 'words' array to a misspelled word
function print_words_elem( $word, $index, $text_input_idx ) {
echo "words[$text_input_idx][$index] = '" . escape_quote( $word ) . "';\n";
}
# set an element of the JavaScript 'suggs' array to a list of suggestions
function print_suggs_elem( $suggs, $index, $text_input_idx ) {
echo "suggs[$text_input_idx][$index] = [";
foreach( $suggs as $key=>$val ) {
if( $val ) {
echo "'" . escape_quote( $val ) . "'";
if ( $key+1 < count( $suggs )) {
echo ", ";
}
}
}
echo "];\n";
}
# escape single quote
function escape_quote( $str ) {
return preg_replace ( "/'/", "\\'", $str );
}
# handle a server-side error.
function error_handler( $err ) {
echo "error = '" . preg_replace( "/['\\\\]/", "\\\\$0", $err ) . "';\n";
}
## get the list of misspelled words. Put the results in the javascript words array
## for each misspelled word, get suggestions and put in the javascript suggs array
function print_checker_results() {
global $aspell_prog;
global $aspell_opts;
global $tempfiledir;
global $textinputs;
global $input_separator;
$aspell_err = "";
# create temp file
$tempfile = tempnam( $tempfiledir, 'aspell_data_' );
# open temp file, add the submitted text.
if( $fh = fopen( $tempfile, 'w' )) {
for( $i = 0; $i < count( $textinputs ); $i++ ) {
$text = urldecode( $textinputs[$i] );
// Strip all tags for the text. (by FredCK - #339 / #681)
$text = preg_replace( "/<[^>]+>/", " ", $text ) ;
$lines = explode( "\n", $text );
fwrite ( $fh, "%\n" ); # exit terse mode
fwrite ( $fh, "^$input_separator\n" );
fwrite ( $fh, "!\n" ); # enter terse mode
foreach( $lines as $key=>$value ) {
# use carat on each line to escape possible aspell commands
fwrite( $fh, "^$value\n" );
}
}
fclose( $fh );
# exec aspell command - redirect STDERR to STDOUT
$cmd = "$aspell_prog $aspell_opts < $tempfile 2>&1";
if( $aspellret = shell_exec( $cmd )) {
$linesout = explode( "\n", $aspellret );
$index = 0;
$text_input_index = -1;
# parse each line of aspell return
foreach( $linesout as $key=>$val ) {
$chardesc = substr( $val, 0, 1 );
# if '&', then not in dictionary but has suggestions
# if '#', then not in dictionary and no suggestions
# if '*', then it is a delimiter between text inputs
# if '@' then version info
if( $chardesc == '&' || $chardesc == '#' ) {
$line = explode( " ", $val, 5 );
print_words_elem( $line[1], $index, $text_input_index );
if( isset( $line[4] )) {
$suggs = explode( ", ", $line[4] );
} else {
$suggs = array();
}
print_suggs_elem( $suggs, $index, $text_input_index );
$index++;
} elseif( $chardesc == '*' ) {
$text_input_index++;
print_textindex_decl( $text_input_index );
$index = 0;
} elseif( $chardesc != '@' && $chardesc != "" ) {
# assume this is error output
$aspell_err .= $val;
}
}
if( $aspell_err ) {
$aspell_err = "Error executing `$cmd`\\n$aspell_err";
error_handler( $aspell_err );
}
} else {
error_handler( "System error: Aspell program execution failed (`$cmd`)" );
}
} else {
error_handler( "System error: Could not open file '$tempfile' for writing" );
}
# close temp file, delete file
unlink( $tempfile );
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="<?php echo $spellercss ?>" />
<script language="javascript" src="<?php echo $word_win_src ?>"></script>
<script language="javascript">
var suggs = new Array();
var words = new Array();
var textinputs = new Array();
var error;
<?php
print_textinputs_var();
print_checker_results();
?>
var wordWindowObj = new wordWindow();
wordWindowObj.originalSpellings = words;
wordWindowObj.suggestions = suggs;
wordWindowObj.textInputs = textinputs;
function init_spell() {
// check if any error occured during server-side processing
if( error ) {
alert( error );
} else {
// call the init_spell() function in the parent frameset
if (parent.frames.length) {
parent.init_spell( wordWindowObj );
} else {
alert('This page was loaded outside of a frameset. It might not display properly');
}
}
}
</script>
</head>
<!-- <body onLoad="init_spell();"> by FredCK -->
<body onLoad="init_spell();" bgcolor="#ffffff">
<script type="text/javascript">
wordWindowObj.writeBody();
</script>
</body>
</html>
<?php
header('Content-type: text/html; charset=utf-8');
// The following variables values must reflect your installation needs.
//$aspell_prog = '"C:\Program Files\Aspell\bin\aspell.exe"'; // by FredCK (for Windows)
//$aspell_prog = 'aspell'; // by FredCK (for Linux)
// This is to prevent abitrary access to FCK's spellchecker.php AND to supply the configured path and lang
function deny_no_egw_session(&$account)
{
die('Access denied, no EGroupware session!');
}
$GLOBALS['egw_info'] = array(
'flags' => array(
'currentapp' => 'home',
'noheader' => true,
'autocreate_session_callback' => 'deny_no_egw_session',
)
);
// will not continue, unless the header get's included and there is a valid eGW session
require('../../../../../../../../header.inc.php');
if (!empty($GLOBALS['egw_info']['user']['preferences']['common']['spellchecker_lang']))
{
$lang = $GLOBALS['egw_info']['user']['preferences']['common']['spellchecker_lang'];
}
else
{
$lang = $GLOBALS['egw_info']['user']['preferences']['common']['lang'];
}
$aspell_opts = '-a '.escapeshellarg('--lang='.$lang).' --encoding=utf-8 -H --rem-sgml-check=alt'; // by FredCK
$tempfiledir = "./";
$spellercss = '../spellerStyle.css'; // by FredCK
$word_win_src = '../wordWindow.js'; // by FredCK
$textinputs = $_POST['textinputs']; # array
$input_separator = "A";
# set the JavaScript variable to the submitted text.
# textinputs is an array, each element corresponding to the (url-encoded)
# value of the text control submitted for spell-checking
function print_textinputs_var() {
global $textinputs;
foreach( $textinputs as $key=>$val ) {
# $val = str_replace( "'", "%27", $val );
echo "textinputs[$key] = decodeURIComponent(\"" . $val . "\");\n";
}
}
# make declarations for the text input index
function print_textindex_decl( $text_input_idx ) {
echo "words[$text_input_idx] = [];\n";
echo "suggs[$text_input_idx] = [];\n";
}
# set an element of the JavaScript 'words' array to a misspelled word
function print_words_elem( $word, $index, $text_input_idx ) {
echo "words[$text_input_idx][$index] = '" . escape_quote( $word ) . "';\n";
}
# set an element of the JavaScript 'suggs' array to a list of suggestions
function print_suggs_elem( $suggs, $index, $text_input_idx ) {
echo "suggs[$text_input_idx][$index] = [";
foreach( $suggs as $key=>$val ) {
if( $val ) {
echo "'" . escape_quote( $val ) . "'";
if ( $key+1 < count( $suggs )) {
echo ", ";
}
}
}
echo "];\n";
}
# escape single quote
function escape_quote( $str ) {
return preg_replace ( "/'/", "\\'", $str );
}
# handle a server-side error.
function error_handler( $err ) {
echo "error = '" . preg_replace( "/['\\\\]/", "\\\\$0", $err ) . "';\n";
}
## get the list of misspelled words. Put the results in the javascript words array
## for each misspelled word, get suggestions and put in the javascript suggs array
function print_checker_results() {
global $aspell_opts;
global $tempfiledir;
global $textinputs;
global $input_separator;
$aspell_err = "";
// check if admin enabled serverside (aspell based) spellchecker
if (!isset($GLOBALS['egw_info']['server']['enabled_spellcheck']))
{
error_handler('Spellchecker is NOT enabled in global EGroupware configuration (Admin >> Site configuration)!');
return;
}
if (!empty($GLOBALS['egw_info']['server']['aspell_path']) &&
is_executable($GLOBALS['egw_info']['server']['aspell_path']))
{
$aspell_prog = $GLOBALS['egw_info']['server']['aspell_path'];
}
else // little fallback that might save linux users
{
$aspell_prog = 'aspell';
}
# create temp file
// use EGroupware's temp_dir
$tempfile = tempnam( $GLOBALS['egw_info']['server']['temp_dir'], 'aspell_data_' );
# open temp file, add the submitted text.
if( $fh = fopen( $tempfile, 'w' )) {
for( $i = 0; $i < count( $textinputs ); $i++ ) {
$text = urldecode( $textinputs[$i] );
// Strip all tags for the text. (by FredCK - #339 / #681)
$text = preg_replace( "/<[^>]+>/", " ", $text ) ;
$lines = explode( "\n", $text );
fwrite ( $fh, "%\n" ); # exit terse mode
fwrite ( $fh, "^$input_separator\n" );
fwrite ( $fh, "!\n" ); # enter terse mode
foreach( $lines as $key=>$value ) {
# use carat on each line to escape possible aspell commands
fwrite( $fh, "^$value\n" );
}
}
fclose( $fh );
# exec aspell command - redirect STDERR to STDOUT
$cmd = "$aspell_prog $aspell_opts < $tempfile 2>&1";
if( $aspellret = shell_exec( $cmd )) {
$linesout = explode( "\n", $aspellret );
$index = 0;
$text_input_index = -1;
# parse each line of aspell return
foreach( $linesout as $key=>$val ) {
$chardesc = substr( $val, 0, 1 );
# if '&', then not in dictionary but has suggestions
# if '#', then not in dictionary and no suggestions
# if '*', then it is a delimiter between text inputs
# if '@' then version info
if( $chardesc == '&' || $chardesc == '#' ) {
$line = explode( " ", $val, 5 );
print_words_elem( $line[1], $index, $text_input_index );
if( isset( $line[4] )) {
$suggs = explode( ", ", $line[4] );
} else {
$suggs = array();
}
print_suggs_elem( $suggs, $index, $text_input_index );
$index++;
} elseif( $chardesc == '*' ) {
$text_input_index++;
print_textindex_decl( $text_input_index );
$index = 0;
} elseif( $chardesc != '@' && $chardesc != "" ) {
# assume this is error output
$aspell_err .= $val;
}
}
if( $aspell_err ) {
$aspell_err = "Error executing `$cmd`\\n$aspell_err";
error_handler( $aspell_err );
}
} else {
error_handler( "System error: Aspell program execution failed (`$cmd`)" );
}
} else {
error_handler( "System error: Could not open file '$tempfile' for writing" );
}
# close temp file, delete file
unlink( $tempfile );
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="<?php echo $spellercss ?>" />
<script language="javascript" src="<?php echo $word_win_src ?>"></script>
<script language="javascript">
var suggs = new Array();
var words = new Array();
var textinputs = new Array();
var error;
<?php
print_textinputs_var();
print_checker_results();
?>
var wordWindowObj = new wordWindow();
wordWindowObj.originalSpellings = words;
wordWindowObj.suggestions = suggs;
wordWindowObj.textInputs = textinputs;
function init_spell() {
// check if any error occured during server-side processing
if( error ) {
alert( error );
} else {
// call the init_spell() function in the parent frameset
if (parent.frames.length) {
parent.init_spell( wordWindowObj );
} else {
alert('This page was loaded outside of a frameset. It might not display properly');
}
}
}
</script>
</head>
<!-- <body onLoad="init_spell();"> by FredCK -->
<body onLoad="init_spell();" bgcolor="#ffffff">
<script type="text/javascript">
wordWindowObj.writeBody();
</script>
</body>
</html>

View File

@ -1,181 +0,0 @@
#!/usr/bin/perl
use CGI qw/ :standard /;
use File::Temp qw/ tempfile tempdir /;
# my $spellercss = '/speller/spellerStyle.css'; # by FredCK
my $spellercss = '../spellerStyle.css'; # by FredCK
# my $wordWindowSrc = '/speller/wordWindow.js'; # by FredCK
my $wordWindowSrc = '../wordWindow.js'; # by FredCK
my @textinputs = param( 'textinputs[]' ); # array
# my $aspell_cmd = 'aspell'; # by FredCK (for Linux)
my $aspell_cmd = '"C:\Program Files\Aspell\bin\aspell.exe"'; # by FredCK (for Windows)
my $lang = 'en_US';
# my $aspell_opts = "-a --lang=$lang --encoding=utf-8"; # by FredCK
my $aspell_opts = "-a --lang=$lang --encoding=utf-8 -H --rem-sgml-check=alt"; # by FredCK
my $input_separator = "A";
# set the 'wordtext' JavaScript variable to the submitted text.
sub printTextVar {
for( my $i = 0; $i <= $#textinputs; $i++ ) {
print "textinputs[$i] = decodeURIComponent('" . escapeQuote( $textinputs[$i] ) . "')\n";
}
}
sub printTextIdxDecl {
my $idx = shift;
print "words[$idx] = [];\n";
print "suggs[$idx] = [];\n";
}
sub printWordsElem {
my( $textIdx, $wordIdx, $word ) = @_;
print "words[$textIdx][$wordIdx] = '" . escapeQuote( $word ) . "';\n";
}
sub printSuggsElem {
my( $textIdx, $wordIdx, @suggs ) = @_;
print "suggs[$textIdx][$wordIdx] = [";
for my $i ( 0..$#suggs ) {
print "'" . escapeQuote( $suggs[$i] ) . "'";
if( $i < $#suggs ) {
print ", ";
}
}
print "];\n";
}
sub printCheckerResults {
my $textInputIdx = -1;
my $wordIdx = 0;
my $unhandledText;
# create temp file
my $dir = tempdir( CLEANUP => 1 );
my( $fh, $tmpfilename ) = tempfile( DIR => $dir );
# temp file was created properly?
# open temp file, add the submitted text.
for( my $i = 0; $i <= $#textinputs; $i++ ) {
$text = url_decode( $textinputs[$i] );
# Strip all tags for the text. (by FredCK - #339 / #681)
$text =~ s/<[^>]+>/ /g;
@lines = split( /\n/, $text );
print $fh "\%\n"; # exit terse mode
print $fh "^$input_separator\n";
print $fh "!\n"; # enter terse mode
for my $line ( @lines ) {
# use carat on each line to escape possible aspell commands
print $fh "^$line\n";
}
}
# exec aspell command
my $cmd = "$aspell_cmd $aspell_opts < $tmpfilename 2>&1";
open ASPELL, "$cmd |" or handleError( "Could not execute `$cmd`\\n$!" ) and return;
# parse each line of aspell return
for my $ret ( <ASPELL> ) {
chomp( $ret );
# if '&', then not in dictionary but has suggestions
# if '#', then not in dictionary and no suggestions
# if '*', then it is a delimiter between text inputs
if( $ret =~ /^\*/ ) {
$textInputIdx++;
printTextIdxDecl( $textInputIdx );
$wordIdx = 0;
} elsif( $ret =~ /^(&|#)/ ) {
my @tokens = split( " ", $ret, 5 );
printWordsElem( $textInputIdx, $wordIdx, $tokens[1] );
my @suggs = ();
if( $tokens[4] ) {
@suggs = split( ", ", $tokens[4] );
}
printSuggsElem( $textInputIdx, $wordIdx, @suggs );
$wordIdx++;
} else {
$unhandledText .= $ret;
}
}
close ASPELL or handleError( "Error executing `$cmd`\\n$unhandledText" ) and return;
}
sub escapeQuote {
my $str = shift;
$str =~ s/'/\\'/g;
return $str;
}
sub handleError {
my $err = shift;
print "error = '" . escapeQuote( $err ) . "';\n";
}
sub url_decode {
local $_ = @_ ? shift : $_;
defined or return;
# change + signs to spaces
tr/+/ /;
# change hex escapes to the proper characters
s/%([a-fA-F0-9]{2})/pack "H2", $1/eg;
return $_;
}
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Display HTML
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
print <<EOF;
Content-type: text/html; charset=utf-8
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="$spellercss"/>
<script src="$wordWindowSrc"></script>
<script type="text/javascript">
var suggs = new Array();
var words = new Array();
var textinputs = new Array();
var error;
EOF
printTextVar();
printCheckerResults();
print <<EOF;
var wordWindowObj = new wordWindow();
wordWindowObj.originalSpellings = words;
wordWindowObj.suggestions = suggs;
wordWindowObj.textInputs = textinputs;
function init_spell() {
// check if any error occured during server-side processing
if( error ) {
alert( error );
} else {
// call the init_spell() function in the parent frameset
if (parent.frames.length) {
parent.init_spell( wordWindowObj );
} else {
error = "This page was loaded outside of a frameset. ";
error += "It might not display properly";
alert( error );
}
}
}
</script>
</head>
<body onLoad="init_spell();">
<script type="text/javascript">
wordWindowObj.writeBody();
</script>
</body>
</html>
EOF

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,65 +0,0 @@
<%@ CodePage=65001 Language="VBScript"%>
<%
Option Explicit
Response.Buffer = True
%>
<%
' FCKeditor - The text editor for Internet - http://www.fckeditor.net
' Copyright (C) 2003-2008 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 = GetCurrentFolder()
' Is Upload enabled?
if ( Not IsAllowedCommand( sCommand ) ) then
SendUploadResults "1", "", "", "The """ & sCommand & """ command isn't allowed"
end if
' Check if it is an allowed resource type.
if ( Not IsAllowedType( sResourceType ) ) Then
SendUploadResults "1", "", "", "The " & sResourceType & " resource type isn't allowed"
end if
FileUpload sResourceType, sCurrentFolder, sCommand
%>

View File

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

View File

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

View File

@ -1,32 +0,0 @@
<%@ 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* This is the File Browser Connector for ASP.NET.
*
* The code of this page if included in the FCKeditor.Net package,
* in the FredCK.FCKeditorV2.dll assembly file. So to use it you must
* include that DLL in your "bin" directory.
*
* To download the FCKeditor.Net package, go to our official web site:
* http://www.fckeditor.net
--%>
<FCKeditor:Config id="Config" runat="server"></FCKeditor:Config>

View File

@ -1,32 +0,0 @@
<%@ 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-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* This is the Uploader for ASP.NET.
*
* The code of this page if included in the FCKeditor.Net package,
* in the FredCK.FCKeditorV2.dll assemblyfile. So to use it you must
* include that DLL in your "bin" directory.
*
* To download the FCKeditor.Net package, go to our official web site:
* http://www.fckeditor.net
--%>
<FCKeditor:Config id="Config" runat="server"></FCKeditor:Config>

View File

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

View File

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

View File

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

View File

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

View File

@ -1,230 +0,0 @@
<cfsetting enablecfoutputonly="Yes">
<!---
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 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 = 0>
<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">
<cffile action="copy" source="#sTempFilePath#" destination="#destination#" mode="755">
</cfcatch>
</cftry>
</cflock>
<cfset sFileUrl = CombinePaths( GetResourceTypePath( ARGUMENTS.resourceType, sCommand ) , ARGUMENTS.currentFolder ) >
<cfset sFileUrl = CombinePaths( sFileUrl , sFileName ) >
<cfcatch type="fckeditor">
<cfset errorNumber = CFCATCH.ErrorCode>
</cfcatch>
<cfcatch type="any">
<cfset errorNumber = "1">
<cfset customMsg = CFCATCH.Message >
</cfcatch>
</cftry>
<cfset SendUploadResults( errorNumber, sFileUrl, sFileName, customMsg ) >
</cffunction>
<cffunction name="GetFolders" returntype="void" output="true">
<cfargument name="resourceType" type="String" required="true">
<cfargument name="currentFolder" type="String" required="true">
<cfset var i = 1>
<cfset var folders = "">
<!--- Map the virtual path to the local server path --->
<cfset var sServerDir = ServerMapFolder( ARGUMENTS.resourceType, ARGUMENTS.currentFolder, "GetFolders" ) >
<!--- Sort directories first, name ascending --->
<cfdirectory action="list" directory="#sServerDir#" name="qDir" sort="type,name">
<cfscript>
while( i lte qDir.recordCount )
{
if( compareNoCase( qDir.type[i], "FILE" ) and not listFind( ".,..", qDir.name[i] ) )
{
folders = folders & '<Folder name="#HTMLEditFormat( qDir.name[i] )#" />' ;
}
i = i + 1;
}
</cfscript>
<cfoutput><Folders>#folders#</Folders></cfoutput>
</cffunction>
<cffunction name="GetFoldersAndfiles" returntype="void" output="true">
<cfargument name="resourceType" type="String" required="true">
<cfargument name="currentFolder" type="String" required="true">
<cfset var i = 1>
<cfset var folders = "">
<cfset var files = "">
<!--- Map the virtual path to the local server path --->
<cfset var sServerDir = ServerMapFolder( ARGUMENTS.resourceType, ARGUMENTS.currentFolder, "GetFolders" ) >
<!--- Sort directories first, name ascending --->
<cfdirectory action="list" directory="#sServerDir#" name="qDir" sort="type,name">
<cfscript>
while( i lte qDir.recordCount )
{
if( not compareNoCase( qDir.type[i], "DIR" ) and not listFind( ".,..", qDir.name[i] ) )
{
folders = folders & '<Folder name="#HTMLEditFormat(qDir.name[i])#" />' ;
}
else if( not compareNoCase( qDir.type[i], "FILE" ) )
{
fileSizeKB = round(qDir.size[i] / 1024) ;
files = files & '<File name="#HTMLEditFormat(qDir.name[i])#" size="#IIf( fileSizeKB GT 0, DE( fileSizeKB ), 1)#" />' ;
}
i = i + 1 ;
}
</cfscript>
<cfoutput><Folders>#folders#</Folders></cfoutput>
<cfoutput><Files>#files#</Files></cfoutput>
</cffunction>
<cffunction name="CreateFolder" returntype="void" output="true">
<cfargument name="resourceType" required="true" type="string">
<cfargument name="currentFolder" required="true" type="string">
<cfset var sNewFolderName = url.newFolderName >
<cfset var sServerDir = "" >
<cfset var errorNumber = 0>
<cfset var sErrorMsg = "">
<cfset var currentFolderPath = ServerMapFolder( ARGUMENTS.resourceType, ARGUMENTS.currentFolder, 'CreateFolder' )>
<cfparam name="url.newFolderName" default="">
<cfscript>
sNewFolderName = SanitizeFolderName( sNewFolderName ) ;
</cfscript>
<cfif not len( sNewFolderName ) or len( sNewFolderName ) gt 255>
<cfset errorNumber = 102>
<cfelseif directoryExists( currentFolderPath & sNewFolderName )>
<cfset errorNumber = 101>
<cfelseif find( "..", sNewFolderName )>
<cfset errorNumber = 103>
<cfelse>
<cfset errorNumber = 0>
<!--- Map the virtual path to the local server path of the current folder. --->
<cfset sServerDir = currentFolderPath & sNewFolderName >
<cftry>
<cfdirectory action="create" directory="#currentFolderPath##sNewFolderName#" mode="755">
<cfcatch type="any">
<!---
un-resolvable error numbers in ColdFusion:
* 102 : Invalid folder name.
* 103 : You have no permissions to create the folder.
--->
<cfset errorNumber = 110>
</cfcatch>
</cftry>
</cfif>
<cfoutput><Error number="#errorNumber#" originalDescription="#HTMLEditFormat(sErrorMsg)#" /></cfoutput>
</cffunction>

View File

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

View File

@ -1,319 +0,0 @@
<cfsetting enablecfoutputonly="Yes">
<!---
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 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) >
<cfset SendError( 102, "" )>
</cfif>
<cfreturn sCurrentFolder>
</cffunction>
<cffunction name="SanitizeFolderName" returntype="String" output="false">
<cfargument name="sNewFolderName" required="true">
<!--- Do a cleanup of the folder name to avoid possible problems --->
<!--- Remove . \ / | : ? * " < > 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="">
<cfoutput>
<script type="text/javascript">
(function()
{
var d = document.domain ;
while ( true )
{
// Test if we can access a parent property.
try
{
var test = window.top.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 ;
}
}
})() ;
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>

View File

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

View File

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

View File

@ -1,189 +0,0 @@
<cfsetting enablecfoutputonly="Yes">
<!---
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 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();
// Configuration settings for each Resource Type
//
// - AllowedExtensions: the possible extensions that can be allowed.
// If it is empty then any file type can be uploaded.
// - DeniedExtensions: The extensions that won't be allowed.
// If it is empty then no restrictions are done here.
//
// For a file to be uploaded it has to fulfill both the AllowedExtensions
// and DeniedExtensions (that's it: not being denied) conditions.
//
// - FileTypesPath: the virtual folder relative to the document root where
// these resources will be located.
// Attention: It must start and end with a slash: '/'
//
// - FileTypesAbsolutePath: the physical path to the above folder. It must be
// an absolute path.
// If it's an empty string then it will be autocalculated.
// Usefull if you are using a virtual directory, symbolic link or alias.
// Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
// Attention: The above 'FileTypesPath' must point to the same directory.
// Attention: It must end with a slash: '/'
//
//
// - QuickUploadPath: the virtual folder relative to the document root where
// these resources will be uploaded using the Upload tab in the resources
// dialogs.
// Attention: It must start and end with a slash: '/'
//
// - QuickUploadAbsolutePath: the physical path to the above folder. It must be
// an absolute path.
// If it's an empty string then it will be autocalculated.
// Usefull if you are using a virtual directory, symbolic link or alias.
// Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
// Attention: The above 'QuickUploadPath' must point to the same directory.
// Attention: It must end with a slash: '/'
Config.AllowedExtensions = StructNew() ;
Config.DeniedExtensions = StructNew() ;
Config.FileTypesPath = StructNew() ;
Config.FileTypesAbsolutePath = StructNew() ;
Config.QuickUploadPath = StructNew() ;
Config.QuickUploadAbsolutePath = StructNew() ;
Config.AllowedExtensions["File"] = "7z,aiff,asf,avi,bmp,csv,doc,fla,flv,gif,gz,gzip,jpeg,jpg,mid,mov,mp3,mp4,mpc,mpeg,mpg,ods,odt,pdf,png,ppt,pxd,qt,ram,rar,rm,rmi,rmvb,rtf,sdc,sitd,swf,sxc,sxw,tar,tgz,tif,tiff,txt,vsd,wav,wma,wmv,xls,xml,zip" ;
Config.DeniedExtensions["File"] = "" ;
Config.FileTypesPath["File"] = Config.UserFilesPath & 'file/' ;
Config.FileTypesAbsolutePath["File"] = iif( Config.ServerPath eq "", de(""), de(Config.ServerPath & 'file/') ) ;
Config.QuickUploadPath["File"] = Config.FileTypesPath["File"] ;
Config.QuickUploadAbsolutePath["File"] = Config.FileTypesAbsolutePath["File"] ;
Config.AllowedExtensions["Image"] = "bmp,gif,jpeg,jpg,png" ;
Config.DeniedExtensions["Image"] = "" ;
Config.FileTypesPath["Image"] = Config.UserFilesPath & 'image/' ;
Config.FileTypesAbsolutePath["Image"] = iif( Config.ServerPath eq "", de(""), de(Config.ServerPath & 'image/') ) ;
Config.QuickUploadPath["Image"] = Config.FileTypesPath["Image"] ;
Config.QuickUploadAbsolutePath["Image"] = Config.FileTypesAbsolutePath["Image"] ;
Config.AllowedExtensions["Flash"] = "swf,flv" ;
Config.DeniedExtensions["Flash"] = "" ;
Config.FileTypesPath["Flash"] = Config.UserFilesPath & 'flash/' ;
Config.FileTypesAbsolutePath["Flash"] = iif( Config.ServerPath eq "", de(""), de(Config.ServerPath & 'flash/') ) ;
Config.QuickUploadPath["Flash"] = Config.FileTypesPath["Flash"] ;
Config.QuickUploadAbsolutePath["Flash"] = Config.FileTypesAbsolutePath["Flash"] ;
Config.AllowedExtensions["Media"] = "aiff,asf,avi,bmp,fla,flv,gif,jpeg,jpg,mid,mov,mp3,mp4,mpc,mpeg,mpg,png,qt,ram,rm,rmi,rmvb,swf,tif,tiff,wav,wma,wmv" ;
Config.DeniedExtensions["Media"] = "" ;
Config.FileTypesPath["Media"] = Config.UserFilesPath & 'media/' ;
Config.FileTypesAbsolutePath["Media"] = iif( Config.ServerPath eq "", de(""), de(Config.ServerPath & 'media/') ) ;
Config.QuickUploadPath["Media"] = Config.FileTypesPath["Media"] ;
Config.QuickUploadAbsolutePath["Media"] = Config.FileTypesAbsolutePath["Media"] ;
</cfscript>
<cftry>
<!--- code to maintain backwards compatibility with previous version of cfm connector --->
<cfif isDefined("application.userFilesPath")>
<cflock scope="application" type="readonly" timeout="5">
<cfset config.userFilesPath = application.userFilesPath>
</cflock>
<cfelseif isDefined("server.userFilesPath")>
<cflock scope="server" type="readonly" timeout="5">
<cfset config.userFilesPath = server.userFilesPath>
</cflock>
</cfif>
<!--- look for config struct in application and server scopes --->
<cfif isDefined("application.FCKeditor") and isStruct(application.FCKeditor)>
<cflock scope="application" type="readonly" timeout="5">
<cfset variables.FCKeditor = duplicate(application.FCKeditor)>
</cflock>
<cfelseif isDefined("server.FCKeditor") and isStruct(server.FCKeditor)>
<cflock scope="server" type="readonly" timeout="5">
<cfset variables.FCKeditor = duplicate(server.FCKeditor)>
</cflock>
</cfif>
<!--- catch potential "The requested scope application has not been enabled" exception --->
<cfcatch type="any">
</cfcatch>
</cftry>
<cfif isDefined("FCKeditor")>
<!--- copy key values from external to local config (i.e. override default config as required) --->
<cfscript>
function structCopyKeys(stFrom, stTo) {
for ( key in stFrom ) {
if ( isStruct(stFrom[key]) ) {
structCopyKeys(stFrom[key],stTo[key]);
} else {
stTo[key] = stFrom[key];
}
}
}
structCopyKeys(FCKeditor, config);
</cfscript>
</cfif>

View File

@ -1,32 +0,0 @@
<cfsetting enablecfoutputonly="Yes">
<!---
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 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>

View File

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

View File

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

View File

@ -1,322 +0,0 @@
[//lasso
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* This is the File Manager Connector for Lasso.
*/
/*.....................................................................
Include global configuration. See config.lasso for details.
*/
include('config.lasso');
/*.....................................................................
Translate current date/time to GMT for custom header.
*/
var('headerDate') = date_localtogmt(date)->format('%a, %d %b %Y %T GMT');
/*.....................................................................
Convert query string parameters to variables and initialize output.
*/
var(
'Command' = action_param('Command'),
'Type' = action_param('Type'),
'CurrentFolder' = action_param('CurrentFolder'),
'ServerPath' = action_param('ServerPath'),
'NewFolderName' = action_param('NewFolderName'),
'NewFile' = null,
'NewFileName' = string,
'OrigFilePath' = string,
'NewFilePath' = string,
'commandData' = string,
'folders' = '\t<Folders>\n',
'files' = '\t<Files>\n',
'errorNumber' = integer,
'responseType' = 'xml',
'uploadResult' = '0'
);
/*.....................................................................
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 )
{
// Test if we can access a parent property.
try
{
var test = window.top.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 ;
}
}
})() ;
';
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
);
if($CurrentFolder->(Find: '..') || $CurrentFolder->(Find: '\\'));
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.
*/
inline($connection);
select($Command);
/*.............................................................
List all subdirectories in the 'Current Folder' directory.
*/
case('GetFolders');
$commandData += '\t<Folders>\n';
iterate(file_listdirectory($currentFolderURL), local('this'));
#this->endswith('/') ? $commandData += '\t\t<Folder name="' + #this->removetrailing('/')& + '" />\n';
/iterate;
$commandData += '\t</Folders>\n';
/*.............................................................
List both files and folders in the 'Current Folder' directory.
Include the file sizes in kilobytes.
*/
case('GetFoldersAndFiles');
iterate(file_listdirectory($currentFolderURL), local('this'));
if(#this->endswith('/'));
$folders += '\t\t<Folder name="' + #this->removetrailing('/')& + '" />\n';
else;
local('size') = file_getsize($currentFolderURL + #this) / 1024;
$files += '\t\t<File name="' + #this + '" size="' + #size + '" />\n';
/if;
/iterate;
$folders += '\t</Folders>\n';
$files += '\t</Files>\n';
$commandData += $folders + $files;
/*.............................................................
Create a directory 'NewFolderName' within the 'Current Folder.'
*/
case('CreateFolder');
$NewFolderName = (String_ReplaceRegExp: $NewFolderName, -find='\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>', -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='\\\\|\\/|\\||\\:|\\?|\\*|"|<|>', -replace='_');
$OrigFilePath = $currentFolderURL + $NewFileName;
$NewFilePath = $OrigFilePath;
local('fileExtension') = '.' + $NewFile->find('OrigExtension');
#fileExtension = (String_ReplaceRegExp: #fileExtension, -find='\\\\|\\/|\\||\\:|\\?|\\*|"|<|>', -replace='_');
local('shortFileName') = $NewFileName->removetrailing(#fileExtension)&;
/*.....................................................
Make sure the file extension is allowed.
*/
if($config->find('DeniedExtensions')->find($Type) >> $NewFile->find('OrigExtension'));
$uploadResult = '202';
else;
/*.................................................
Rename the target path until it is unique.
*/
while(file_exists($NewFilePath));
$NewFilePath = $currentFolderURL + #shortFileName + '(' + loop_count + ')' + #fileExtension;
/while;
/*.................................................
Copy the uploaded file to its final location.
*/
file_copy($NewFile->find('path'), $NewFilePath);
/*.................................................
Set the error code for the response. Note whether
the file had to be renamed.
*/
select(file_currenterror( -errorcode));
case(0);
$OrigFilePath != $NewFilePath ? $uploadResult = 201;
case;
$uploadResult = file_currenterror( -errorcode);
/select;
/if;
/if;
fck_htmlreply(
-uploadResult=$uploadResult,
-NewFilePath=$NewFilePath
);
/select;
/inline;
/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" ?>
<Connector command="' + $Command + '" resourceType="' + $Type + '">';
if($errorNumber != '102');
$__html_reply__ += '<CurrentFolder path="' + $CurrentFolder + '" url="' + $currentFolderURL + '" />';
/if;
$__html_reply__ += $commandData + '
</Connector>';
/if;
]

View File

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

View File

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

View File

@ -1,214 +0,0 @@
#####
# FCKeditor - The text editor for Internet - http://www.fckeditor.net
# Copyright (C) 2003-2008 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 . '" originalDescription="' . $cnv_errmsg . '" />';
}
sub FileUpload
{
eval("use File::Copy;");
local($resourceType, $currentFolder) = @_;
$sErrorNumber = '0' ;
$sFileName = '' ;
if($new_fname) {
# Map the virtual path to the local server path.
$sServerDir = &ServerMapFolder($resourceType,$currentFolder);
# Get the uploaded file name.
$sFileName = $new_fname;
$sFileName =~ s/\\|\/|\||\:|\?|\*|\"|<|>|[[:cntrl:]]/_/g;
$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, $resourceType.$currentFolder.$sFileName, $sFileName, '');
}
sub SendUploadResults
{
local($sErrorNumber, $sFileUrl, $sFileName, $customMsg) = @_;
print <<EOF;
Content-type: text/html
<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.top.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 ;
}
}
})() ;
EOF
print 'window.parent.OnUploadCompleted(' . $sErrorNumber . ',"' . JS_cnv($sFileUrl) . '","' . JS_cnv($sFileName) . '","' . JS_cnv($customMsg) . '") ;';
print '</script>';
exit ;
}
1;

View File

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

View File

@ -1,141 +0,0 @@
#####
# FCKeditor - The text editor for Internet - http://www.fckeditor.net
# Copyright (C) 2003-2008 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;

View File

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

View File

@ -1,686 +0,0 @@
#####
# FCKeditor - The text editor for Internet - http://www.fckeditor.net
# Copyright (C) 2003-2008 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;

View File

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

View File

@ -1,146 +0,0 @@
#!/usr/bin/env python
"""
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 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']

View File

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

View File

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

View File

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

View File

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

View File

@ -1,126 +0,0 @@
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 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( '(?u)\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[^\u0000-\u001f\u007f-\u009f]', '_', 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 ( '(?u)/\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[^\u0000-\u001f\u007f-\u009f]/', '_', 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
return currentFolder
def mapServerPath( environ, url):
" Emulate the asp Server.mapPath function. Given an url path return the physical directory that it corresponds to "
# This isn't correct but for the moment there's no other solution
# If this script is under a virtual directory or symlink it will detect the problem and stop
return combinePaths( getRootPath(environ), url )
def mapServerFolder(resourceTypePath, folderPath):
return combinePaths ( resourceTypePath , folderPath )
def getRootPath(environ):
"Purpose: returns the root path on the server"
# WARNING: this may not be thread safe, and doesn't work w/ VirtualServer/mod_python
# Use Config.UserFilesAbsolutePath instead
if environ.has_key('DOCUMENT_ROOT'):
return environ['DOCUMENT_ROOT']
else:
realPath = os.path.realpath( './' )
selfPath = environ['SCRIPT_FILENAME']
selfPath = selfPath [ : selfPath.rfind( '/' ) ]
selfPath = selfPath.replace( '/', os.path.sep)
position = realPath.find(selfPath)
# This can check only that this script isn't run from a virtual dir
# But it avoids the problems that arise if it isn't checked
raise realPath
if ( position < 0 or position <> len(realPath) - len(selfPath) or realPath[ : position ]==''):
raise Exception('Sorry, can\'t map "UserFilesPath" to a physical path. You must set the "UserFilesAbsolutePath" value in "editor/filemanager/connectors/py/config.py".')
return realPath[ : position ]

View File

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

View File

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

View File

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

View File

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

View File

@ -1,159 +0,0 @@
<%
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 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 integration file for Active FoxPro Pages.
*
DEFINE CLASS goFckeditor AS CONTAINER OLEPUBLIC
cInstanceName =""
BasePath =""
cWIDTH =""
cHEIGHT =""
ToolbarSet =""
cValue=""
DIMENSION aConfig(10,2)
&& -----------------------------------------------------------------------
FUNCTION fckeditor( tcInstanceName )
LOCAL lnLoop,lnLoop2
THIS.cInstanceName = tcInstanceName
THIS.BasePath = '/fckeditor/'
THIS.cWIDTH = '100%'
THIS.cHEIGHT = '200'
THIS.ToolbarSet = 'Default'
THIS.cValue = ''
FOR lnLoop=1 TO 10
FOR lnLoop2=1 TO 2
THIS.aConfig(lnLoop,lnLoop2) = ""
NEXT
NEXT
RETURN
ENDFUNC
&& -----------------------------------------------------------------------
FUNCTION CREATE()
? THIS.CreateHtml()
RETURN
ENDFUNC
&& -----------------------------------------------------------------------
FUNCTION CreateHtml()
LOCAL html
LOCAL lcLink
HtmlValue = THIS.cValue && HTMLSPECIALCHARS()
html = []
IF THIS.IsCompatible()
lcLink = THIS.BasePath+[editor/fckeditor.html?InstanceName=]+THIS.cInstanceName
IF ( !THIS.ToolbarSet == '' )
lcLink = lcLink + [&Toolbar=]+THIS.ToolbarSet
ENDIF
&& Render the LINKED HIDDEN FIELD.
html = html + [<input type="hidden" id="]+THIS.cInstanceName +[" name="]+THIS.cInstanceName +[" value="]+HtmlValue+[" style="display:none" />]
&& Render the configurations HIDDEN FIELD.
html = html + [<input type="hidden" id="]+THIS.cInstanceName +[___Config" value="]+THIS.GetConfigFieldString() + [" style="display:none" />] +CHR(13)+CHR(10)
&& Render the EDITOR IFRAME.
html = html + [<iframe id="]+THIS.cInstanceName +[___Frame" src="Link" width="]+THIS.cWIDTH+[" height="]+THIS.cHEIGHT+[" frameborder="0" scrolling="no"></iframe>]
ELSE
IF ( AT("%", THIS.cWIDTH)=0 )
WidthCSS = THIS.cWIDTH + 'px'
ELSE
WidthCSS = THIS.cWIDTH
ENDIF
IF ( AT("%",THIS.cHEIGHT)=0 )
HeightCSS = THIS.cHEIGHT + 'px'
ELSE
HeightCSS = THIS.cHEIGHT
ENDIF
html = html + [<textarea name="]+THIS.cInstanceName +[" rows="4" cols="40" style="width: ]+WidthCSS+[ height: ]+HeightCSS+[">]+HtmlValue+[</textarea>]
ENDIF
RETURN (html)
ENDFUNC
&& -----------------------------------------------------------------------
FUNCTION IsCompatible()
LOCAL llRetval
LOCAL sAgent
llRetval=.F.
SET POINT TO "."
sAgent = LOWER(ALLTRIM(request.servervariables("HTTP_USER_AGENT")))
IF AT("msie",sAgent) >0 .AND. AT("mac",sAgent)=0 .AND. AT("opera",sAgent)=0
iVersion=VAL(SUBSTR(sAgent,AT("msie",sAgent)+5,3))
llRetval= iVersion > 5.5
ELSE
IF AT("gecko/",sAgent)>0
iVersion=VAL(SUBSTR(sAgent,AT("gecko/",sAgent)+6,8))
llRetval =iVersion > 20030210
ENDIF
ELSE
IF AT("opera/",sAgent)>0
iVersion=VAL(SUBSTR(sAgent,AT("opera/",sAgent)+6,4))
llRetval =iVersion >= 9.5
ENDIF
ELSE
IF AT("applewebkit/",sAgent)>0
iVersion=VAL(SUBSTR(sAgent,AT("applewebkit/",sAgent)+12,3))
llRetval =iVersion >= 522
ENDIF
ENDIF
SET POINT TO
RETURN (llRetval)
ENDFUNC
&& -----------------------------------------------------------------------
FUNCTION GetConfigFieldString()
LOCAL sParams
LOCAL bFirst
LOCAL sKey
sParams = ""
bFirst = .T.
FOR lnLoop=1 TO 10 && ALEN(this.aconfig)
IF !EMPTY(THIS.aConfig(lnLoop,1))
IF bFirst = .F.
sParams = sParams + "&"
ELSE
bFirst = .F.
ENDIF
sParams = sParams +THIS.aConfig(lnLoop,1)+[=]+THIS.aConfig(lnLoop,2)
ELSE
EXIT
ENDIF
NEXT
RETURN(sParams)
ENDFUNC
ENDDEFINE
%>

View File

@ -1,235 +0,0 @@
<!--
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 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 integration file for ASP.
*
* It defines the FCKeditor class that can be used to create editor
* instances in ASP pages on server side.
-->
<%
Class FCKeditor
private sBasePath
private sInstanceName
private sWidth
private sHeight
private sToolbarSet
private sValue
private oConfig
Private Sub Class_Initialize()
sBasePath = "/fckeditor/"
sWidth = "100%"
sHeight = "200"
sToolbarSet = "Default"
sValue = ""
Set oConfig = CreateObject("Scripting.Dictionary")
End Sub
Public Property Let BasePath( basePathValue )
sBasePath = basePathValue
End Property
Public Property Let InstanceName( instanceNameValue )
sInstanceName = instanceNameValue
End Property
Public Property Let Width( widthValue )
sWidth = widthValue
End Property
Public Property Let Height( heightValue )
sHeight = heightValue
End Property
Public Property Let ToolbarSet( toolbarSetValue )
sToolbarSet = toolbarSetValue
End Property
Public Property Let Value( newValue )
If ( IsNull( newValue ) OR IsEmpty( newValue ) ) Then
sValue = ""
Else
sValue = newValue
End If
End Property
Public Property Let Config( configKey, configValue )
oConfig.Add configKey, configValue
End Property
' Generates the instace of the editor in the HTML output of the page.
Public Sub Create( instanceName )
response.write CreateHtml( instanceName )
end Sub
' Returns the html code that must be used to generate an instance of FCKeditor.
Public Function CreateHtml( instanceName )
dim html
If IsCompatible() Then
Dim sFile, sLink
If Request.QueryString( "fcksource" ) = "true" Then
sFile = "fckeditor.original.html"
Else
sFile = "fckeditor.html"
End If
sLink = sBasePath & "editor/" & sFile & "?InstanceName=" + instanceName
If (sToolbarSet & "") <> "" Then
sLink = sLink + "&amp;Toolbar=" & sToolbarSet
End If
html = ""
' Render the linked hidden field.
html = html & "<input type=""hidden"" id=""" & instanceName & """ name=""" & instanceName & """ value=""" & Server.HTMLEncode( sValue ) & """ style=""display:none"" />"
' Render the configurations hidden field.
html = html & "<input type=""hidden"" id=""" & instanceName & "___Config"" value=""" & GetConfigFieldString() & """ style=""display:none"" />"
' Render the editor IFRAME.
html = html & "<iframe id=""" & instanceName & "___Frame"" src=""" & sLink & """ width=""" & sWidth & """ height=""" & sHeight & """ frameborder=""0"" scrolling=""no""></iframe>"
Else
Dim sWidthCSS, sHeightCSS
If InStr( sWidth, "%" ) > 0 Then
sWidthCSS = sWidth
Else
sWidthCSS = sWidth & "px"
End If
If InStr( sHeight, "%" ) > 0 Then
sHeightCSS = sHeight
Else
sHeightCSS = sHeight & "px"
End If
html = "<textarea name=""" & instanceName & """ rows=""4"" cols=""40"" style=""width: " & sWidthCSS & "; height: " & sHeightCSS & """>" & Server.HTMLEncode( sValue ) & "</textarea>"
End If
CreateHtml = html
End Function
Private Function IsCompatible()
IsCompatible = FCKeditor_IsCompatibleBrowser()
End Function
Private Function GetConfigFieldString()
Dim sParams
Dim bFirst
bFirst = True
Dim sKey
For Each sKey in oConfig
If bFirst = False Then
sParams = sParams & "&amp;"
Else
bFirst = False
End If
sParams = sParams & EncodeConfig( sKey ) & "=" & EncodeConfig( oConfig(sKey) )
Next
GetConfigFieldString = sParams
End Function
Private Function EncodeConfig( valueToEncode )
' The locale of the asp server makes the conversion of a boolean to string different to "true" or "false"
' so we must do it manually
If vartype(valueToEncode) = vbBoolean then
If valueToEncode=True Then
EncodeConfig="True"
Else
EncodeConfig="False"
End If
Else
EncodeConfig = Replace( valueToEncode, "&", "%26" )
EncodeConfig = Replace( EncodeConfig , "=", "%3D" )
EncodeConfig = Replace( EncodeConfig , """", "%22" )
End if
End Function
End Class
' A function that can be used to check if the current browser is compatible with FCKeditor
' without the need to create an instance of the class.
Function FCKeditor_IsCompatibleBrowser()
Dim sAgent
sAgent = Request.ServerVariables("HTTP_USER_AGENT")
Dim iVersion
Dim re, Matches
If InStr(sAgent, "MSIE") > 0 AND InStr(sAgent, "mac") <= 0 AND InStr(sAgent, "Opera") <= 0 Then
iVersion = CInt( FCKeditor_ToNumericFormat( Mid(sAgent, InStr(sAgent, "MSIE") + 5, 3) ) )
FCKeditor_IsCompatibleBrowser = ( iVersion >= 5.5 )
ElseIf InStr(sAgent, "Gecko/") > 0 Then
iVersion = CLng( Mid( sAgent, InStr( sAgent, "Gecko/" ) + 6, 8 ) )
FCKeditor_IsCompatibleBrowser = ( iVersion >= 20030210 )
ElseIf InStr(sAgent, "Opera/") > 0 Then
iVersion = CSng( FCKeditor_ToNumericFormat( Mid( sAgent, InStr( sAgent, "Opera/" ) + 6, 4 ) ) )
FCKeditor_IsCompatibleBrowser = ( iVersion >= 9.5 )
ElseIf InStr(sAgent, "AppleWebKit/") > 0 Then
Set re = new RegExp
re.IgnoreCase = true
re.global = false
re.Pattern = "AppleWebKit/(\d+)"
Set Matches = re.Execute(sAgent)
FCKeditor_IsCompatibleBrowser = ( re.Replace(Matches.Item(0).Value, "$1") >= 522 )
Else
FCKeditor_IsCompatibleBrowser = False
End If
End Function
' By Agrotic
' On ASP, when converting string to numbers, the number decimal separator is localized
' so 5.5 will not work on systems were the separator is "," and vice versa.
Private Function FCKeditor_ToNumericFormat( numberStr )
If IsNumeric( "5.5" ) Then
FCKeditor_ToNumericFormat = Replace( numberStr, ",", ".")
Else
FCKeditor_ToNumericFormat = Replace( numberStr, ".", ",")
End If
End Function
%>

View File

@ -1,232 +0,0 @@
<cfcomponent output="false" displayname="FCKeditor" hint="Create an instance of the FCKeditor.">
<!---
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 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 ==
*
* ColdFusion MX integration.
* Note this CFC is created for use only with Coldfusion MX and above.
* For older version, check the fckeditor.cfm.
*
* Syntax:
*
* <cfscript>
* fckEditor = createObject("component", "fckeditor.fckeditor");
* fckEditor.instanceName="myEditor";
* fckEditor.basePath="/fckeditor/";
* fckEditor.value="<p>This is my <strong>initial</strong> html text.</p>";
* fckEditor.width="100%";
* fckEditor.height="200";
* // ... additional parameters ...
* fckEditor.create(); // create instance now.
* </cfscript>
*
* See your macromedia coldfusion mx documentation for more info.
*
* *** Note:
* Do not use path names with a "." (dot) in the name. This is a coldfusion
* limitation with the cfc invocation.
--->
<cfinclude template="fckutils.cfm">
<cffunction
name="Create"
access="public"
output="true"
returntype="void"
hint="Outputs the editor HTML in the place where the function is called"
>
<cfoutput>#CreateHtml()#</cfoutput>
</cffunction>
<cffunction
name="CreateHtml"
access="public"
output="false"
returntype="string"
hint="Retrieves the editor HTML"
>
<cfparam name="this.instanceName" type="string" />
<cfparam name="this.width" type="string" default="100%" />
<cfparam name="this.height" type="string" default="200" />
<cfparam name="this.toolbarSet" type="string" default="Default" />
<cfparam name="this.value" type="string" default="" />
<cfparam name="this.basePath" type="string" default="/fckeditor/" />
<cfparam name="this.checkBrowser" type="boolean" default="true" />
<cfparam name="this.config" type="struct" default="#structNew()#" />
<cfscript>
// display the html editor or a plain textarea?
if( isCompatible() )
return getHtmlEditor();
else
return getTextArea();
</cfscript>
</cffunction>
<cffunction
name="isCompatible"
access="private"
output="false"
returnType="boolean"
hint="Check browser compatibility via HTTP_USER_AGENT, if checkBrowser is true"
>
<cfscript>
var sAgent = lCase( cgi.HTTP_USER_AGENT );
var stResult = "";
var sBrowserVersion = "";
// do not check if argument "checkBrowser" is false
if( not this.checkBrowser )
return true;
return FCKeditor_IsCompatibleBrowser();
</cfscript>
</cffunction>
<cffunction
name="getTextArea"
access="private"
output="false"
returnType="string"
hint="Create a textarea field for non-compatible browsers."
>
<cfset var result = "" />
<cfset var sWidthCSS = "" />
<cfset var sHeightCSS = "" />
<cfscript>
if( Find( "%", this.width ) gt 0)
sWidthCSS = this.width;
else
sWidthCSS = this.width & "px";
if( Find( "%", this.width ) gt 0)
sHeightCSS = this.height;
else
sHeightCSS = this.height & "px";
result = "<textarea name=""#this.instanceName#"" rows=""4"" cols=""40"" style=""width: #sWidthCSS#; height: #sHeightCSS#"">#HTMLEditFormat(this.value)#</textarea>" & chr(13) & chr(10);
</cfscript>
<cfreturn result />
</cffunction>
<cffunction
name="getHtmlEditor"
access="private"
output="false"
returnType="string"
hint="Create the html editor instance for compatible browsers."
>
<cfset var sURL = "" />
<cfset var result = "" />
<cfscript>
// try to fix the basePath, if ending slash is missing
if( len( this.basePath) and right( this.basePath, 1 ) is not "/" )
this.basePath = this.basePath & "/";
// construct the url
sURL = this.basePath & "editor/fckeditor.html?InstanceName=" & this.instanceName;
// append toolbarset name to the url
if( len( this.toolbarSet ) )
sURL = sURL & "&amp;Toolbar=" & this.toolbarSet;
</cfscript>
<cfscript>
result = result & "<input type=""hidden"" id=""#this.instanceName#"" name=""#this.instanceName#"" value=""#HTMLEditFormat(this.value)#"" style=""display:none"" />" & chr(13) & chr(10);
result = result & "<input type=""hidden"" id=""#this.instanceName#___Config"" value=""#GetConfigFieldString()#"" style=""display:none"" />" & chr(13) & chr(10);
result = result & "<iframe id=""#this.instanceName#___Frame"" src=""#sURL#"" width=""#this.width#"" height=""#this.height#"" frameborder=""0"" scrolling=""no""></iframe>" & chr(13) & chr(10);
</cfscript>
<cfreturn result />
</cffunction>
<cffunction
name="GetConfigFieldString"
access="private"
output="false"
returnType="string"
hint="Create configuration string: Key1=Value1&Key2=Value2&... (Key/Value:HTML encoded)"
>
<cfset var sParams = "" />
<cfset var key = "" />
<cfset var fieldValue = "" />
<cfset var fieldLabel = "" />
<cfset var lConfigKeys = "" />
<cfset var iPos = "" />
<cfscript>
/**
* CFML doesn't store casesensitive names for structure keys, but the configuration names must be casesensitive for js.
* So we need to find out the correct case for the configuration keys.
* We "fix" this by comparing the caseless configuration keys to a list of all available configuration options in the correct case.
* changed 20041206 hk@lwd.de (improvements are welcome!)
*/
lConfigKeys = lConfigKeys & "CustomConfigurationsPath,EditorAreaCSS,ToolbarComboPreviewCSS,DocType";
lConfigKeys = lConfigKeys & ",BaseHref,FullPage,Debug,AllowQueryStringDebug,SkinPath";
lConfigKeys = lConfigKeys & ",PreloadImages,PluginsPath,AutoDetectLanguage,DefaultLanguage,ContentLangDirection";
lConfigKeys = lConfigKeys & ",ProcessHTMLEntities,IncludeLatinEntities,IncludeGreekEntities,ProcessNumericEntities,AdditionalNumericEntities";
lConfigKeys = lConfigKeys & ",FillEmptyBlocks,FormatSource,FormatOutput,FormatIndentator";
lConfigKeys = lConfigKeys & ",StartupFocus,ForcePasteAsPlainText,AutoDetectPasteFromWord,ForceSimpleAmpersand";
lConfigKeys = lConfigKeys & ",TabSpaces,ShowBorders,SourcePopup,ToolbarStartExpanded,ToolbarCanCollapse";
lConfigKeys = lConfigKeys & ",IgnoreEmptyParagraphValue,PreserveSessionOnFileBrowser,FloatingPanelsZIndex,TemplateReplaceAll,TemplateReplaceCheckbox";
lConfigKeys = lConfigKeys & ",ToolbarLocation,ToolbarSets,EnterMode,ShiftEnterMode,Keystrokes";
lConfigKeys = lConfigKeys & ",ContextMenu,BrowserContextMenuOnCtrl,FontColors,FontNames,FontSizes";
lConfigKeys = lConfigKeys & ",FontFormats,StylesXmlPath,TemplatesXmlPath,SpellChecker,IeSpellDownloadUrl";
lConfigKeys = lConfigKeys & ",SpellerPagesServerScript,FirefoxSpellChecker,MaxUndoLevels,DisableObjectResizing,DisableFFTableHandles";
lConfigKeys = lConfigKeys & ",LinkDlgHideTarget,LinkDlgHideAdvanced,ImageDlgHideLink,ImageDlgHideAdvanced,FlashDlgHideAdvanced";
lConfigKeys = lConfigKeys & ",ProtectedTags,BodyId,BodyClass,DefaultLinkTarget,CleanWordKeepsStructure";
lConfigKeys = lConfigKeys & ",LinkBrowser,LinkBrowserURL,LinkBrowserWindowWidth,LinkBrowserWindowHeight,ImageBrowser";
lConfigKeys = lConfigKeys & ",ImageBrowserURL,ImageBrowserWindowWidth,ImageBrowserWindowHeight,FlashBrowser,FlashBrowserURL";
lConfigKeys = lConfigKeys & ",FlashBrowserWindowWidth,FlashBrowserWindowHeight,LinkUpload,LinkUploadURL,LinkUploadWindowWidth";
lConfigKeys = lConfigKeys & ",LinkUploadWindowHeight,LinkUploadAllowedExtensions,LinkUploadDeniedExtensions,ImageUpload,ImageUploadURL";
lConfigKeys = lConfigKeys & ",ImageUploadAllowedExtensions,ImageUploadDeniedExtensions,FlashUpload,FlashUploadURL,FlashUploadAllowedExtensions";
lConfigKeys = lConfigKeys & ",FlashUploadDeniedExtensions,SmileyPath,SmileyImages,SmileyColumns,SmileyWindowWidth,SmileyWindowHeight";
for( key in this.config )
{
iPos = listFindNoCase( lConfigKeys, key );
if( iPos GT 0 )
{
if( len( sParams ) )
sParams = sParams & "&amp;";
fieldValue = this.config[key];
fieldName = listGetAt( lConfigKeys, iPos );
// set all boolean possibilities in CFML to true/false values
if( isBoolean( fieldValue) and fieldValue )
fieldValue = "true";
else if( isBoolean( fieldValue) )
fieldValue = "false";
sParams = sParams & HTMLEditFormat( fieldName ) & '=' & HTMLEditFormat( fieldValue );
}
}
return sParams;
</cfscript>
</cffunction>
</cfcomponent>

View File

@ -1,159 +0,0 @@
<cfsetting enablecfoutputonly="Yes">
<!---
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 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 ==
*
* ColdFusion integration.
* Note this module is created for use with Coldfusion 4.52 and above.
* For a cfc version for coldfusion mx check the fckeditor.cfc.
*
* Syntax:
*
* <cfmodule name="path/to/cfc/fckeditor"
* instanceName="myEditor"
* toolbarSet="..."
* width="..."
* height="..:"
* value="..."
* config="..."
* >
--->
<!--- ::
* Attribute validation
:: --->
<cfparam name="attributes.instanceName" type="string">
<cfparam name="attributes.width" type="string" default="100%">
<cfparam name="attributes.height" type="string" default="200">
<cfparam name="attributes.toolbarSet" type="string" default="Default">
<cfparam name="attributes.value" type="string" default="">
<cfparam name="attributes.basePath" type="string" default="/fckeditor/">
<cfparam name="attributes.checkBrowser" type="boolean" default="true">
<cfparam name="attributes.config" type="struct" default="#structNew()#">
<cfinclude template="fckutils.cfm">
<!--- ::
* check browser compatibility via HTTP_USER_AGENT, if checkBrowser is true
:: --->
<cfscript>
if( attributes.checkBrowser )
{
isCompatibleBrowser = FCKeditor_IsCompatibleBrowser();
}
else
{
// If we should not check browser compatibility, assume true
isCompatibleBrowser = true;
}
</cfscript>
<cfif isCompatibleBrowser>
<!--- ::
* show html editor area for compatible browser
:: --->
<cfscript>
// try to fix the basePath, if ending slash is missing
if( len( attributes.basePath) and right( attributes.basePath, 1 ) is not "/" )
attributes.basePath = attributes.basePath & "/";
// construct the url
sURL = attributes.basePath & "editor/fckeditor.html?InstanceName=" & attributes.instanceName;
// append toolbarset name to the url
if( len( attributes.toolbarSet ) )
sURL = sURL & "&amp;Toolbar=" & attributes.toolbarSet;
// create configuration string: Key1=Value1&Key2=Value2&... (Key/Value:HTML encoded)
/**
* CFML doesn't store casesensitive names for structure keys, but the configuration names must be casesensitive for js.
* So we need to find out the correct case for the configuration keys.
* We "fix" this by comparing the caseless configuration keys to a list of all available configuration options in the correct case.
* changed 20041206 hk@lwd.de (improvements are welcome!)
*/
lConfigKeys = "";
lConfigKeys = lConfigKeys & "CustomConfigurationsPath,EditorAreaCSS,ToolbarComboPreviewCSS,DocType";
lConfigKeys = lConfigKeys & ",BaseHref,FullPage,Debug,AllowQueryStringDebug,SkinPath";
lConfigKeys = lConfigKeys & ",PreloadImages,PluginsPath,AutoDetectLanguage,DefaultLanguage,ContentLangDirection";
lConfigKeys = lConfigKeys & ",ProcessHTMLEntities,IncludeLatinEntities,IncludeGreekEntities,ProcessNumericEntities,AdditionalNumericEntities";
lConfigKeys = lConfigKeys & ",FillEmptyBlocks,FormatSource,FormatOutput,FormatIndentator";
lConfigKeys = lConfigKeys & ",StartupFocus,ForcePasteAsPlainText,AutoDetectPasteFromWord,ForceSimpleAmpersand";
lConfigKeys = lConfigKeys & ",TabSpaces,ShowBorders,SourcePopup,ToolbarStartExpanded,ToolbarCanCollapse";
lConfigKeys = lConfigKeys & ",IgnoreEmptyParagraphValue,PreserveSessionOnFileBrowser,FloatingPanelsZIndex,TemplateReplaceAll,TemplateReplaceCheckbox";
lConfigKeys = lConfigKeys & ",ToolbarLocation,ToolbarSets,EnterMode,ShiftEnterMode,Keystrokes";
lConfigKeys = lConfigKeys & ",ContextMenu,BrowserContextMenuOnCtrl,FontColors,FontNames,FontSizes";
lConfigKeys = lConfigKeys & ",FontFormats,StylesXmlPath,TemplatesXmlPath,SpellChecker,IeSpellDownloadUrl";
lConfigKeys = lConfigKeys & ",SpellerPagesServerScript,FirefoxSpellChecker,MaxUndoLevels,DisableObjectResizing,DisableFFTableHandles";
lConfigKeys = lConfigKeys & ",LinkDlgHideTarget ,LinkDlgHideAdvanced,ImageDlgHideLink ,ImageDlgHideAdvanced,FlashDlgHideAdvanced";
lConfigKeys = lConfigKeys & ",ProtectedTags,BodyId,BodyClass,DefaultLinkTarget,CleanWordKeepsStructure";
lConfigKeys = lConfigKeys & ",LinkBrowser,LinkBrowserURL,LinkBrowserWindowWidth,LinkBrowserWindowHeight,ImageBrowser";
lConfigKeys = lConfigKeys & ",ImageBrowserURL,ImageBrowserWindowWidth,ImageBrowserWindowHeight,FlashBrowser,FlashBrowserURL";
lConfigKeys = lConfigKeys & ",FlashBrowserWindowWidth ,FlashBrowserWindowHeight,LinkUpload,LinkUploadURL,LinkUploadWindowWidth";
lConfigKeys = lConfigKeys & ",LinkUploadWindowHeight,LinkUploadAllowedExtensions,LinkUploadDeniedExtensions,ImageUpload,ImageUploadURL";
lConfigKeys = lConfigKeys & ",ImageUploadAllowedExtensions,ImageUploadDeniedExtensions,FlashUpload,FlashUploadURL,FlashUploadAllowedExtensions";
lConfigKeys = lConfigKeys & ",FlashUploadDeniedExtensions,SmileyPath,SmileyImages,SmileyColumns,SmileyWindowWidth,SmileyWindowHeight";
sConfig = "";
for( key in attributes.config )
{
iPos = listFindNoCase( lConfigKeys, key );
if( iPos GT 0 )
{
if( len( sConfig ) )
sConfig = sConfig & "&amp;";
fieldValue = attributes.config[key];
fieldName = listGetAt( lConfigKeys, iPos );
sConfig = sConfig & urlEncodedFormat( fieldName ) & '=' & urlEncodedFormat( fieldValue );
}
}
</cfscript>
<cfoutput>
<input type="hidden" id="#attributes.instanceName#" name="#attributes.instanceName#" value="#HTMLEditFormat(attributes.value)#" style="display:none" />
<input type="hidden" id="#attributes.instanceName#___Config" value="#sConfig#" style="display:none" />
<iframe id="#attributes.instanceName#___Frame" src="#sURL#" width="#attributes.width#" height="#attributes.height#" frameborder="0" scrolling="no"></iframe>
</cfoutput>
<cfelse>
<!--- ::
* show plain textarea for non compatible browser
:: --->
<cfscript>
// append unit "px" for numeric width and/or height values
if( isNumeric( attributes.width ) )
attributes.width = attributes.width & "px";
if( isNumeric( attributes.height ) )
attributes.height = attributes.height & "px";
</cfscript>
<!--- Fixed Bug ##1075166. hk@lwd.de 20041206 --->
<cfoutput>
<textarea name="#attributes.instanceName#" rows="4" cols="40" style="WIDTH: #attributes.width#; HEIGHT: #attributes.height#">#HTMLEditFormat(attributes.value)#</textarea>
</cfoutput>
</cfif>
<cfsetting enablecfoutputonly="No"><cfexit method="exittag">

View File

@ -1,108 +0,0 @@
[//lasso
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 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 integration file for Lasso.
*
* It defines the FCKeditor class ("custom type" in Lasso terms) that can
* be used to create editor instances in Lasso pages on server side.
*/
define_type(
'editor',
-namespace='fck_',
-description='Creates an instance of FCKEditor.'
);
local(
'instancename' = 'FCKEditor1',
'width' = '100%',
'height' = '200',
'toolbarset' = 'Default',
'initialvalue' = string,
'basepath' = '/fckeditor/',
'config' = array,
'checkbrowser' = true,
'displayerrors' = false
);
define_tag(
'onCreate',
-required='instancename', -type='string',
-optional='width', -type='string',
-optional='height', -type='string',
-optional='toolbarset', -type='string',
-optional='initialvalue', -type='string',
-optional='basepath', -type='string',
-optional='config', -type='array'
);
self->instancename = #instancename;
local_defined('width') ? self->width = #width;
local_defined('height') ? self->height = #height;
local_defined('toolbarset') ? self->toolbarset = #toolbarset;
local_defined('initialvalue') ? self->initialvalue = #initialvalue;
local_defined('basepath') ? self->basepath = #basepath;
local_defined('config') ? self->config = #config;
/define_tag;
define_tag('create');
if(self->isCompatibleBrowser);
local('out' = '
<input type="hidden" id="' + self->instancename + '" name="' + self->instancename + '" value="' + encode_html(self->initialvalue) + '" style="display:none" />
' + self->parseConfig + '
<iframe id="' + self->instancename + '___Frame" src="' + self->basepath + 'editor/fckeditor.html?InstanceName=' + self->instancename + '&Toolbar=' + self->toolbarset + '" width="' + self->width + '" height="' + self->height + '" frameborder="0" scrolling="no"></iframe>
');
else;
local('out' = '
<textarea name="' + self->instancename + '" rows="4" cols="40" style="width: ' + self->width + '; height: ' + self->height + '">' + encode_html(self->initialvalue) + '</textarea>
');
/if;
return(@#out);
/define_tag;
define_tag('isCompatibleBrowser');
local('result' = false);
if (client_browser->Find("MSIE") && !client_browser->Find("mac") && !client_browser->Find("Opera"));
#result = client_browser->Substring(client_browser->Find("MSIE")+5,3)>=5.5;
/if;
if (client_browser->Find("Gecko/"));
#result = client_browser->Substring(client_browser->Find("Gecko/")+6,8)>=20030210;
/if;
if (client_browser->Find("Opera/"));
#result = client_browser->Substring(client_browser->Find("Opera/")+6,4)>=9.5;
/if;
if (client_browser->Find("AppleWebKit/"));
#result = client_browser->Substring(client_browser->Find("AppleWebKit/")+12,3)>=522;
/if;
return(#result);
/define_tag;
define_tag('parseConfig');
if(self->config->size);
local('out' = '<input type="hidden" id="' + self->instancename + '___Config" value="');
iterate(self->config, local('this'));
loop_count > 1 ? #out += '&amp;';
#out += encode_html(#this->first) + '=' + encode_html(#this->second);
/iterate;
#out += '" style="display:none" />\n';
return(@#out);
/if;
/define_tag;
/define_type;
]

View File

@ -1,143 +0,0 @@
#####
# FCKeditor - The text editor for Internet - http://www.fckeditor.net
# Copyright (C) 2003-2008 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 integration file for Perl.
#####
#my $InstanceName;
#my $BasePath;
#my $Width;
#my $Height;
#my $ToolbarSet;
#my $Value;
#my %Config;
sub FCKeditor
{
local($instanceName) = @_;
$InstanceName = $instanceName;
$BasePath = '/fckeditor/';
$Width = '100%';
$Height = '200';
$ToolbarSet = 'Default';
$Value = '';
}
sub Create
{
print &CreateHtml();
}
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 CreateHtml
{
$HtmlValue = &specialchar_cnv($Value);
$Html = '' ;
if(&IsCompatible()) {
$Link = $BasePath . "editor/fckeditor.html?InstanceName=$InstanceName";
if($ToolbarSet ne '') {
$Link .= "&amp;Toolbar=$ToolbarSet";
}
#// Render the linked hidden field.
$Html .= "<input type=\"hidden\" id=\"$InstanceName\" name=\"$InstanceName\" value=\"$HtmlValue\" style=\"display:none\" />" ;
#// Render the configurations hidden field.
$cfgstr = &GetConfigFieldString();
$wk = $InstanceName."___Config";
$Html .= "<input type=\"hidden\" id=\"$wk\" value=\"$cfgstr\" style=\"display:none\" />" ;
#// Render the editor IFRAME.
$wk = $InstanceName."___Frame";
$Html .= "<iframe id=\"$wk\" src=\"$Link\" width=\"$Width\" height=\"$Height\" frameborder=\"0\" scrolling=\"no\"></iframe>";
} else {
if($Width =~ /\%/g){
$WidthCSS = $Width;
} else {
$WidthCSS = $Width . 'px';
}
if($Height =~ /\%/g){
$HeightCSS = $Height;
} else {
$HeightCSS = $Height . 'px';
}
$Html .= "<textarea name=\"$InstanceName\" rows=\"4\" cols=\"40\" style=\"width: $WidthCSS; height: $HeightCSS\">$HtmlValue</textarea>";
}
return($Html);
}
sub IsCompatible
{
$sAgent = $ENV{'HTTP_USER_AGENT'};
if(($sAgent =~ /MSIE/i) && !($sAgent =~ /mac/i) && !($sAgent =~ /Opera/i)) {
$iVersion = substr($sAgent,index($sAgent,'MSIE') + 5,3);
return($iVersion >= 5.5) ;
} elsif($sAgent =~ /Gecko\//i) {
$iVersion = substr($sAgent,index($sAgent,'Gecko/') + 6,8);
return($iVersion >= 20030210) ;
} elsif($sAgent =~ /Opera\//i) {
$iVersion = substr($sAgent,index($sAgent,'Opera/') + 6,4);
return($iVersion >= 9.5) ;
} elsif($sAgent =~ /AppleWebKit\/(\d+)/i) {
return($1 >= 522) ;
} else {
return(0); # 2.0 PR fix
}
}
sub GetConfigFieldString
{
$sParams = '';
$bFirst = 0;
foreach $sKey (keys %Config) {
$sValue = $Config{$sKey};
if($bFirst == 1) {
$sParams .= '&amp;';
} else {
$bFirst = 1;
}
$k = &specialchar_cnv($sKey);
$v = &specialchar_cnv($sValue);
if($sValue eq "true") {
$sParams .= "$k=true";
} elsif($sValue eq "false") {
$sParams .= "$k=false";
} else {
$sParams .= "$k=$v";
}
}
return($sParams);
}
1;

View File

@ -1,160 +0,0 @@
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 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 integration file for Python.
"""
import cgi
import os
import re
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;')
text = replace(text, "'", '&#39;')
return text
# The FCKeditor class
class FCKeditor(object):
def __init__(self, instanceName):
self.InstanceName = instanceName
self.BasePath = '/fckeditor/'
self.Width = '100%'
self.Height = '200'
self.ToolbarSet = 'Default'
self.Value = '';
self.Config = {}
def Create(self):
return self.CreateHtml()
def CreateHtml(self):
HtmlValue = escape(self.Value)
Html = ""
if (self.IsCompatible()):
File = "fckeditor.html"
Link = "%seditor/%s?InstanceName=%s" % (
self.BasePath,
File,
self.InstanceName
)
if (self.ToolbarSet is not None):
Link += "&amp;ToolBar=%s" % self.ToolbarSet
# Render the linked hidden field
Html += "<input type=\"hidden\" id=\"%s\" name=\"%s\" value=\"%s\" style=\"display:none\" />" % (
self.InstanceName,
self.InstanceName,
HtmlValue
)
# Render the configurations hidden field
Html += "<input type=\"hidden\" id=\"%s___Config\" value=\"%s\" style=\"display:none\" />" % (
self.InstanceName,
self.GetConfigFieldString()
)
# Render the editor iframe
Html += "<iframe id=\"%s\__Frame\" src=\"%s\" width=\"%s\" height=\"%s\" frameborder=\"0\" scrolling=\"no\"></iframe>" % (
self.InstanceName,
Link,
self.Width,
self.Height
)
else:
if (self.Width.find("%%") < 0):
WidthCSS = "%spx" % self.Width
else:
WidthCSS = self.Width
if (self.Height.find("%%") < 0):
HeightCSS = "%spx" % self.Height
else:
HeightCSS = self.Height
Html += "<textarea name=\"%s\" rows=\"4\" cols=\"40\" style=\"width: %s; height: %s;\" wrap=\"virtual\">%s</textarea>" % (
self.InstanceName,
WidthCSS,
HeightCSS,
HtmlValue
)
return Html
def IsCompatible(self):
if (os.environ.has_key("HTTP_USER_AGENT")):
sAgent = os.environ.get("HTTP_USER_AGENT", "")
else:
sAgent = ""
if (sAgent.find("MSIE") >= 0) and (sAgent.find("mac") < 0) and (sAgent.find("Opera") < 0):
i = sAgent.find("MSIE")
iVersion = float(sAgent[i+5:i+5+3])
if (iVersion >= 5.5):
return True
return False
elif (sAgent.find("Gecko/") >= 0):
i = sAgent.find("Gecko/")
iVersion = int(sAgent[i+6:i+6+8])
if (iVersion >= 20030210):
return True
return False
elif (sAgent.find("Opera/") >= 0):
i = sAgent.find("Opera/")
iVersion = float(sAgent[i+6:i+6+4])
if (iVersion >= 9.5):
return True
return False
elif (sAgent.find("AppleWebKit/") >= 0):
p = re.compile('AppleWebKit\/(\d+)', re.IGNORECASE)
m = p.search(sAgent)
if (m.group(1) >= 522):
return True
return False
else:
return False
def GetConfigFieldString(self):
sParams = ""
bFirst = True
for sKey in self.Config.keys():
sValue = self.Config[sKey]
if (not bFirst):
sParams += "&amp;"
else:
bFirst = False
if (sValue):
k = escape(sKey)
v = escape(sValue)
if (sValue == "true"):
sParams += "%s=true" % k
elif (sValue == "false"):
sParams += "%s=false" % k
else:
sParams += "%s=%s" % (k, v)
return sParams

View File

@ -1,78 +0,0 @@
<!---
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 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 ==
*
* ColdFusion integration.
* This function is used by FCKeditor module to check browser compatibility
--->
<cfscript>
function FCKeditor_IsCompatibleBrowser()
{
sAgent = lCase( cgi.HTTP_USER_AGENT );
isCompatibleBrowser = false;
// check for Internet Explorer ( >= 5.5 )
if( find( "msie", sAgent ) and not find( "mac", sAgent ) and not find( "opera", sAgent ) )
{
// try to extract IE version
stResult = reFind( "msie ([5-9]\.[0-9])", sAgent, 1, true );
if( arrayLen( stResult.pos ) eq 2 )
{
// get IE Version
sBrowserVersion = mid( sAgent, stResult.pos[2], stResult.len[2] );
if( sBrowserVersion GTE 5.5 )
isCompatibleBrowser = true;
}
}
// check for Gecko ( >= 20030210+ )
else if( find( "gecko/", sAgent ) )
{
// try to extract Gecko version date
stResult = reFind( "gecko/(200[3-9][0-1][0-9][0-3][0-9])", sAgent, 1, true );
if( arrayLen( stResult.pos ) eq 2 )
{
// get Gecko build (i18n date)
sBrowserVersion = mid( sAgent, stResult.pos[2], stResult.len[2] );
if( sBrowserVersion GTE 20030210 )
isCompatibleBrowser = true;
}
}
else if( find( "opera/", sAgent ) )
{
// try to extract Opera version
stResult = reFind( "opera/([0-9]+\.[0-9]+)", sAgent, 1, true );
if( arrayLen( stResult.pos ) eq 2 )
{
if ( mid( sAgent, stResult.pos[2], stResult.len[2] ) gte 9.5)
isCompatibleBrowser = true;
}
}
else if( find( "applewebkit", sAgent ) )
{
// try to extract Gecko version date
stResult = reFind( "applewebkit/([0-9]+)", sAgent, 1, true );
if( arrayLen( stResult.pos ) eq 2 )
{
if( mid( sAgent, stResult.pos[2], stResult.len[2] ) gte 522 )
isCompatibleBrowser = true;
}
}
return isCompatibleBrowser;
}
</cfscript>

View File

@ -176,7 +176,7 @@
if (isset($checks[$name]))
{
if ($checks[$name] == $data) continue; // identical check --> ignore it
if ($data['func'] == 'pear_check' || in_array($data['func'],array('extension_check','php_ini_check')) && !isset($data['warning']))
{
if (isset($checks[$name]['from']) && $checks[$name]['from'] && !is_array($checks[$name]['from']))
@ -214,7 +214,7 @@
}
if ($checks) $sorted_checks += $checks;
$checks =& $sorted_checks;
// some constants for pre php4.3
if (!defined('PHP_SHLIB_SUFFIX'))
{
@ -224,7 +224,7 @@
{
define('PHP_SHLIB_PREFIX',PHP_SHLIB_SUFFIX == 'dll' ? 'php_' : '');
}
function php_version($name,$args)
{
global $passed_icon, $error_icon;
@ -250,20 +250,20 @@
$pear_config = '/etc/php5/cli/pear.conf';
}
@include_once 'PEAR/Config.php';
if (!class_exists('PEAR_Config')) return false;
$config = new PEAR_Config('',$pear_config);
//echo "<pre>config = ".print_r($config,true)."</pre>\n";
$channel = $config->get('default_channel');
//echo "<pre>channel = ".print_r($channel,true)."</pre>\n";
if (!method_exists($config,'getRegistry')) return false; // PEAR version to old
$reg = &$config->getRegistry();
//echo "<pre>reg = ".print_r($reg,true)."</pre>\n";
// a bug in pear causes an endless loop if the install-dir does not exist
// bug reported: http://pear.php.net/bugs/bug.php?id=11317
if (!file_exists($reg->install_dir)) return false;
@ -277,21 +277,21 @@
$name = isset($package['package']) ? $package['package'] : $package['name'];
$version = $package['version'];
if (is_array($version)) $version = $version['release'];
$packages[$name] = $version;
// echo "<p>$name: ".print_r($package['version'],true)."</p>\n";
}
ksort($packages);
return $packages;
}
function pear_check($package,$args)
{
global $passed_icon, $warning_icon;
static $pear_available = null;
static $pear_packages = null;
$min_version = isset($args['version']) ? $args['version'] : null;
if (is_null($pear_packages))
@ -320,7 +320,7 @@
if (is_null($pear_available))
{
$pear_available = @include_once('PEAR.php');
if (!class_exists('PEAR')) $pear_available = false;
}
if ($pear_available && $package)
@ -328,21 +328,21 @@
$file = str_replace('_','/',$package).'.php';
$available = @include_once($file);
if (!class_exists($package)) $available = false;
}
}
// is the right version availible
// is the right version availible
$available = (@$available || $pear_available && !$package) && (!$min_version || version_compare($min_version,$version_available) <= 0);
echo '<div>'.($available ? $passed_icon : $warning_icon).' <span'.($available ? '' : ' class="setup_warning"').'>'.
lang('Checking PEAR%1 is installed',($package?'::'.$package:'').($min_version?" ($min_version)":'')).': '.
($available ? ($version_available ? $version_available : lang('True')) : lang('False'))."</span></div>\n";
($available ? ($version_available ? $version_available : lang('True')) : lang('False'))."</span></div>\n";
if (!$available) // give further info only if not availible
{
echo '<div class="setup_info">' . lang('PEAR%1 is needed by: %2.',$package ? '::'.$package : '',
is_array($args['from']) ? implode(', ',$args['from']) : $args['from']);
if (!$pear_available)
{
echo ' '.lang('PEAR (%1) is a PHP repository and is usually in a package called %2.',
@ -598,10 +598,10 @@
function mk_value($value)
{
if (!preg_match('/^([0-9]+)([mk]+)$/i',$value,$matches)) return $value;
return (strtolower($matches[2]) == 'm' ? 1024*1024 : 1024) * (int) $matches[1];
}
function php_ini_check($name,$args)
{
global $passed_icon, $error_icon, $warning_icon, $is_windows;
@ -691,16 +691,16 @@
global $passed_icon, $warning_icon;
$available = (function_exists('imagecopyresampled') || function_exists('imagecopyresized'));
echo "<div>".($available ? $passed_icon : $warning_icon).' <span'.($available?'':' class="setup_warning"').'>'.lang('Checking for GD support...').': '.($available ? lang('True') : lang('False'))."</span></div>\n";
if (!$available)
{
echo lang('Your PHP installation does not have appropriate GD support. You need gd library version 1.8 or newer to see Gantt charts in projects.')."\n";
}
return $available;
}
if ($run_by_webserver)
{
$tpl_root = $GLOBALS['egw_setup']->html->setup_tpl_dir('setup');
@ -711,7 +711,7 @@
));
$ConfigDomain = get_var('ConfigDomain',Array('POST','COOKIE'));
if (@$_GET['intro']) {
if($ConfigLang = get_var('ConfigLang',array('POST','COOKIE')))
if(($ConfigLang = setup::get_lang()))
{
$GLOBALS['egw_setup']->set_cookie('ConfigLang',$ConfigLang,(int) (time()+(1200*9)),'/');
}

View File

@ -17,7 +17,7 @@
var $db;
var $common;
var $accounts;
function invalidate_session_cache() { }
}
@ -40,14 +40,14 @@
var $process;
var $lang;
var $html;
var $system_charset;
/* table name vars */
var $tbl_apps;
var $tbl_config;
var $tbl_hooks;
/**
* @var float $required_php_version php version required by eGroupWare
*/
@ -92,13 +92,13 @@
$this->db->Database = $GLOBALS['egw_domain'][$this->ConfigDomain]['db_name'];
$this->db->User = $GLOBALS['egw_domain'][$this->ConfigDomain]['db_user'];
$this->db->Password = $GLOBALS['egw_domain'][$this->ConfigDomain]['db_pass'];
$this->db->set_app('phpgwapi');
if ($connect_and_setcharset)
{
$this->db->Halt_On_Error = 'no'; // table might not be created at that stage
$this->set_table_names(); // sets/checks config- and applications-table-name
// Set the DB's client charset if a system-charset is set
@ -123,7 +123,7 @@
{
$this->db->Link_ID->SetCharSet($this->system_charset);
}
}
}
$this->db->Halt_On_Error = 'yes'; // setting the default again
}
}
@ -166,6 +166,21 @@
setcookie($cookiename,$cookievalue,$cookietime,'/',$this->cookie_domain);
}
/**
* Get configuration language from $_POST or $_COOKIE and validate it
*
* @return string
*/
static function get_lang()
{
$ConfigLang = get_var('ConfigLang', array('POST','COOKIE'));
if (preg_match('/^[a-z]{2}(-[a-z]{2})?$/',$ConfigLang))
{
return $ConfigLang;
}
return 'en';
}
/**
* authenticate the setup user
*
@ -175,7 +190,7 @@
{
#phpinfo();
$FormLogout = get_var('FormLogout', array('GET','POST'));
$ConfigLang = get_var('ConfigLang', array('POST','COOKIE'));
$ConfigLang = self::get_lang();
if(!$FormLogout)
{
$ConfigLogin = get_var('ConfigLogin', array('POST'));
@ -331,7 +346,7 @@
* check if username and password is valid
*
* this function compares the supplied and stored username and password
* as any of the passwords can be clear text or md5 we convert them to md5
* as any of the passwords can be clear text or md5 we convert them to md5
* internal and compare always the md5 hashs
*
* @param string $user the user supplied username
@ -353,16 +368,16 @@
{
$conf_pw = md5($conf_pw);
}
// Verify that $pw is not already encoded as md5
if(!preg_match('/^[0-9a-f]{32}$/',$pw))
{
$pw = md5($pw);
}
return $pw == $conf_pw;
}
function checkip($remoteip='')
@ -661,7 +676,7 @@
{
return False;
}
//echo "DELETING hooks for: " . $setup_info[$appname]['name'];
if (!is_object($this->hooks))
{
@ -900,7 +915,7 @@
* @param $passwd string cleartext pw
* @param string/boolean $primary_group Groupname for users primary group or False for a group, default 'Default'
* @param boolean $changepw user has right to change pw, default False = Pw change NOT allowed
* @param string $email
* @param string $email
* @return int the numerical user-id
*/
function add_account($username,$first,$last,$passwd,$primary_group='Default',$changepw=False,$email='')
@ -932,11 +947,11 @@
if ($primary_group) // only for users, NOT groups
{
$memberships = $GLOBALS['egw']->accounts->memberships($accountid,true);
if($primary_group_id && !in_array($primary_group_id,$memberships))
{
$memberships[] = $primary_group_id;
$GLOBALS['egw']->accounts->set_memberships($memberships,$accountid);
}
if (!$changepw) $this->add_acl('preferences','nopasswordchange',$accountid);
@ -944,7 +959,7 @@
error_log("setup::add_account('$username','$first','$last',\$passwd,'$primary_group',$changepw,'$email') successfull created accountid=$accountid");
return $accountid;
}
/**
* Set the memberships of an account
*
@ -954,10 +969,10 @@
function set_memberships($groups,$user)
{
$this->setup_account_object();
return $GLOBALS['egw']->accounts->set_memberships($groups,$user);
}
/**
* Check if accounts other then the automatically installed anonymous account exist
*
@ -974,7 +989,7 @@
'start' => 0,
'offset' => 2 // we only need to check 2 accounts, if we just check for not anonymous
));
if (!$accounts || !is_array($accounts) || !count($accounts))
{
return false;
@ -994,7 +1009,7 @@
* Add ACL rights
*
* Dont use it to set group-membership, use set_memberships instead!
*
*
* @param $app string/array with app-names
* @param $locations string eg. run
* @param $account int/string accountid or account_lid
@ -1037,7 +1052,7 @@
}
}
}
/**
* checks if one of the given tables exist, returns the first match
*
@ -1047,12 +1062,12 @@
function table_exist($tables,$force_refresh=False)
{
static $table_names = False;
if (!$table_names || $force_refresh) $table_names = $this->db->table_names();
if (!$table_names) return false;
foreach($table_names as $data)
foreach($table_names as $data)
{
if (($key = array_search($data['table_name'],$tables)) !== false)
{
@ -1061,7 +1076,7 @@
}
return false;
}
/**
* Checks and set the names of the tables, which get accessed before an update: eg. config- and applications-table
*

View File

@ -69,7 +69,7 @@
}
$GLOBALS['header_template']->set_var('domain','');
$setting = get_var('setting',Array('POST'));
while($setting && list($k,$v) = @each($setting))
{
@ -169,7 +169,7 @@
$manual_remote_egw_url = 'http://manual.egroupware.org/egroupware';
$url_parts = explode('/',$_SERVER['PHP_SELF']);
$script = array_pop($url_parts);
$lang = get_var('ConfigLang',Array('POST','COOKIE'));
$lang = setup::get_lang();
$url = $manual_remote_egw_url.'/manual/index.php?referer='.urlencode($manual_remote_egw_url.'/setup/'.$script).
($lang ? '&lang='.urlencode($lang) : '');
$GLOBALS['setup_tpl']->set_var('manual','<a href="'.$url.'" target="manual" onclick="'.

View File

@ -55,7 +55,7 @@
* @param string $type='new' defaults to new(install), could also be 'upgrade'
* @param boolean $DEBUG=false print debugging info
* @param boolean $force_en=false install english language files
* @param string $system_charset=null charset to use
* @param string $system_charset=null charset to use
*/
function pass($setup_info,$method='new',$DEBUG=False,$force_en=False)
{
@ -178,7 +178,7 @@
$langs = false;
if ($method == 'new')
{
$langs[] = ($own_lang = get_var('ConfigLang',Array('POST','COOKIE')));
$langs[] = ($own_lang = setup::get_lang());
if ($own_lang != 'en') $langs[] = 'en';
}
$this->translation->drop_add_all_langs($langs);
@ -194,7 +194,7 @@
function save_minimal_config()
{
$is_windows = strtoupper(substr(PHP_OS,0,3)) == 'WIN';
$GLOBALS['current_config']['site_title'] = 'eGroupWare';
$GLOBALS['current_config']['hostname'] = $_SERVER['HTTP_HOST'] ? $_SERVER['HTTP_HOST'] : 'localhost';
@ -213,6 +213,7 @@
}
$GLOBALS['current_config']['files_dir'] = '/var/lib/'.$egroupwareDirName.'/'.$GLOBALS['egw_setup']->ConfigDomain.'/files';
$GLOBALS['current_config']['backup_dir'] = '/var/lib/'.$egroupwareDirName.'/'.$GLOBALS['egw_setup']->ConfigDomain.'/backup';
$GLOBALS['current_config']['aspell_path'] = '/usr/bin/aspell';
} else {
if(@is_dir('c:\\windows\\temp')) {
$GLOBALS['current_config']['temp_dir'] = 'c:\\windows\\temp';
@ -221,14 +222,20 @@
}
$GLOBALS['current_config']['files_dir'] = 'c:\\Program files\\'.$egroupwareDirName.'\\'.$GLOBALS['egw_setup']->ConfigDomain.'\\files';
$GLOBALS['current_config']['backup_dir'] = 'c:\\Program files\\'.$egroupwareDirName.'\\'.$GLOBALS['egw_setup']->ConfigDomain.'\\backup';
}
$GLOBALS['current_config']['aspell_path'] = 'C:\\Program Files\\Aspell\\bin\\aspell.exe';
}
// only set aspell path, if it's installed
if (!is_executable($GLOBALS['current_config']['aspell_path']))
{
unset($GLOBALS['current_config']['aspell_path']);
}
$datetime =& CreateObject('phpgwapi.datetime');
$GLOBALS['current_config']['tz_offset'] = $datetime->getbestguess();
unset($datetime);
// RalfBecker: php.net recommend this for security reasons, it should be our default too
$GLOBALS['current_config']['usecookies'] = 'True';
if ($GLOBALS['egw_setup']->system_charset)
{
$GLOBALS['current_config']['system_charset'] = $GLOBALS['egw_setup']->system_charset;
@ -517,9 +524,9 @@
}
/* if upgrade required, or if we are running again after an upgrade or dependency failure */
if($DEBUG)
{
echo '<div style="text-align: left; border: thin dashed black; margin-top: 5px;">'."process->upgrade(): Incoming : appname: $appname, version: $appdata[currentver], status: $appdata[status]\n";
if($DEBUG)
{
echo '<div style="text-align: left; border: thin dashed black; margin-top: 5px;">'."process->upgrade(): Incoming : appname: $appname, version: $appdata[currentver], status: $appdata[status]\n";
}
if($appdata['status'] == 'U' || $appdata['status'] == 'D' ||$appdata['status'] == 'V' || $appdata['status'] == '') // TODO this is not getting set for api upgrade, sometimes ???
{
@ -534,7 +541,7 @@
include ($appdir . 'tables_update.inc.php');
$this->updateincluded[$appname] = True;
}
while ($currentver && $currentver != $targetver &&
while ($currentver && $currentver != $targetver &&
function_exists($function = $appname . '_upgrade' . str_replace('.','_',$currentver)))
{
if($DEBUG)
@ -558,7 +565,7 @@
}
}
if ($currentver == $targetver) // upgrades succesful
{
{
if($DEBUG)
{
echo "<br>process->upgrade(): Upgrade of $appname to $targetver is completed.\n";
@ -598,7 +605,7 @@
$GLOBALS['egw_setup']->register_hooks($appname);
}
}
}
else
{

View File

@ -19,7 +19,7 @@
class setup_translation
{
var $langarray = array();
var $no_translation_marker = '*';
/**
@ -29,7 +29,7 @@
*/
function setup_translation()
{
$ConfigLang = get_var('ConfigLang',Array('POST','COOKIE'));
$ConfigLang = setup::get_lang();
if(!$ConfigLang)
{
@ -39,7 +39,7 @@
{
$lang = $ConfigLang;
}
$fn = '.' . SEP . 'lang' . SEP . 'phpgw_' . $lang . '.lang';
if (!file_exists($fn))
{
@ -55,7 +55,7 @@
$this->langarray[strtolower(trim($message_id))] = str_replace("\n",'',$content);
}
fclose($fp);
if (!$GLOBALS['egw_setup']->system_charset)
{
$GLOBALS['egw_setup']->system_charset = $this->langarray['charset'];
@ -69,7 +69,7 @@
* @param $key phrase to translate
* @param $vars vars sent to lang function, passed to us
*/
function translate($key, $vars=False)
function translate($key, $vars=False)
{
$ret = $key . $this->no_translation_marker;
$key = strtolower(trim($key));
@ -123,7 +123,7 @@
$this->setup_translation_sql();
return $this->sql->add_langs($appname,$DEBUG,$force_langs);
}
function drop_add_all_langs($langs=False)
{
$this->setup_translation_sql();
@ -134,7 +134,7 @@
}
return $this->sql->install_langs($langs,'dumpold');
}
/**
* List availible charsets and it's supported languages
* @param boolean/string $name=false name for selectbox or false to return an array
@ -159,7 +159,7 @@
if ($phrase == 'charset')
{
$charset = trim(strtolower($charset));
if ($charset != 'utf-8')
{
$charsets[$charset] .= (isset($charsets[$charset]) ? ', ' : $charset.': ') . $language;
@ -177,8 +177,8 @@
return $charsets;
}
$html =& CreateObject('phpgwapi.html');
return $html->select($name,trim(strtolower($selected)),$charsets,true);
}
}
}
?>

View File

@ -14,7 +14,7 @@
*/
error_reporting(error_reporting() & ~E_NOTICE);
// for an old header, we need to setup the reference before including it
$GLOBALS['phpgw_info'] =& $GLOBALS['egw_info'];
@ -78,15 +78,15 @@
{
$docroots = array(realpath(EGW_SERVER_ROOT),realpath($_SERVER['DOCUMENT_ROOT']));
$dir = realpath($dir);
foreach ($docroots as $docroot)
{
$len = strlen($docroot);
if ($docroot == substr($dir,0,$len) && $len>0)
{
$rest = substr($dir,$len);
if (!strlen($rest) || $rest[0] == DIRECTORY_SEPARATOR)
{
$msg = lang('is in the webservers docroot');
@ -145,7 +145,7 @@
{
if (!$ConfigLang)
{
$ConfigLang = get_var('ConfigLang',Array('POST','COOKIE'));
$ConfigLang = setup::get_lang();
}
$select = '<select name="ConfigLang"'.($onChange ? ' onchange="this.form.submit();"' : '').'>' . "\n";
$languages = get_langs();

View File

@ -1,7 +1,7 @@
<!-- $Id$ -->
<!-- BEGIN header -->
<form method="post" action="{action_url}">
<table align="center" cellspacing="0" border="5" width="90%" >
<tr class="th">
@ -14,7 +14,7 @@
<tr class="th">
<td colspan="2"><b>{lang_Path_information}</b></td>
</tr>
<tr class="row_off">
<td>{lang_Enter_the_full_path_for_temporary_files.<br />Examples:_/tmp,_C:\TEMP}:</td>
<td><input name="newsettings[temp_dir]" value="{value_temp_dir}" size="40" /></td>
@ -24,12 +24,12 @@
<td>{lang_Enter_the_full_path_for_users_and_group_files.<br />Examples:_/files,_E:\FILES}:<br /><b>{lang_This_has_to_be_outside_the_webservers_document-root!!!}</b><br />{lang_or_http://webdav.domain.com_(WebDAV)}:</td>
<td><input name="newsettings[files_dir]" value="{value_files_dir}" size="40" /></td>
</tr>
<tr class="row_off">
<td>{lang_Enter_the_full_path_to_the_backup_directory.<br />if_empty:_files_directory}/db_backup:<br /><b>{lang_This_has_to_be_outside_the_webservers_document-root!!!}</b></td>
<td><input name="newsettings[backup_dir]" value="{value_backup_dir}" size="40" /></td>
</tr>
<tr class="row_on">
<td>{lang_Enter_the_location_of_eGroupWare's_URL.<br />Example:_http://www.domain.com/egroupware_&nbsp;_or_&nbsp;_/egroupware<br /><b>No_trailing_slash</b>}:</td>
<td><input name="newsettings[webserver_url]" value="{value_webserver_url}" size="40" /></td>
@ -45,6 +45,14 @@
</select>
</td>
</tr>
<tr class="row_on">
<td>{lang_Complete_path_to_aspell_program}:</td>
<td>
<input name="newsettings[aspell_path]" value="{value_aspell_path}" size="40">
</td>
</tr>
<tr class="row_on">
<td colspan="2">&nbsp;</td>
</tr>
@ -219,7 +227,7 @@
</select>
</td>
</tr>
<tr class="row_off">
<td>{lang_Allow_authentication_via_cookie}:</td>
<td>
@ -228,8 +236,8 @@
<option value="True" {selected_allow_cookie_auth_True}>{lang_Yes}</option>
</select>
</td>
</tr>
</tr>
<tr class="row_on">
<td>{lang_Auto_login_anonymous_user}:</td>
<td>
@ -394,7 +402,7 @@
<li>{lang_You_need_to_save_the_settings_you_made_here_first!}</li>
</td>
</tr>
<tr class="th">
<td colspan="2"><b>{lang_If_using_ADS_(Active_Directory)_authentication}:</b></td>
</tr>