White Space / Coldfusion - coldfusion

What would be the correct way to stop the white space that ColdFusion outputs?
I know there is cfcontent and cfsetting enableCFoutputOnly. What is the correct way to do that?

In addition to <cfsilent>, <cfsetting enablecfoutputonly="yes"> and <cfprocessingdirective suppressWhiteSpace = "true"> is <cfcontent reset="true" />. You can delete whitespaces at the beginning of your document with it.
HTML5 document would then start like this:
<cfcontent type="text/html; charset=utf-8" reset="true" /><!doctype html>
XML document:
<cfcontent reset="yes" type="text/xml; charset=utf-8" /><CFOUTPUT>#VariableHoldingXmlDocAsString#</CFOUTPUT>
This way you won't get the "Content is not allowed in prolog"-error for XML docs.
If you are getting unwanted whitespaces from a function use the output-attribute to suppress any output and return your result as string - for example:
<cffunction name="getMyName" access="public" returntype="string" output="no">
<cfreturn "Seybsen" />
</cffunction>

You can modify the ColdFusion output by getting access to the ColdFusion Outpout Buffer. James Brown recently demo'd this at our user group meeting (Central Florida Web Developers User Group).
<cfscript>
out = getPageContext().getOut().getString();
newOutput = REreplace(out, 'regex', '', 'all');
</cfscript>
A great place to do this would be in Application.cfc onRequestEnd(). Your result could be a single line of HTML which is then sent to the browser. Work with your web server to GZip and you'll cut bandwidth a great deal.

In terms of tags, there is cfsilent
In the administrator there is a setting to 'Enable whitespace management'
Futher reading on cfsilent and cfcontent reset.

If neither <cfsilent> nor <cfsetting enablecfoutputonly="yes"> can satisfy you, then you are probably over-engineering this issue.
When you are asking solely out of aesthetic reasons, my recommendation is: Ignore the whitespace, it does not do any harm.

Alternatively, You can ensure your entire page is stored within a variable and all this processing is done within cfsilent tags. e.g.
<cfsilent>
<!-- some coldfusion -->
<cfsavecontent variable="pageContent">
<html>
<!-- some content -->
</html>
</cfsavecontent>
<!-- reformat pageContent if required -->
</cfsilent><cfoutput>#pageContent#</cfoutput>
Finally, you can perform any additional processing after you've generated the pagecontent but before you output it e.g. a regular expression to remove additional whitespace or some code tidying.

Here's a tip if you use CFC.
If you're not expecting your method to generate any output, use output="false" in <cffunction> and <cfcomponent> (not needed only if you're using CF9 script style). This will eliminate a lot of unwanted whitespaces.

If you have access to the server and want to implement it on every page request search for and install trimflt.jar. It's a Java servlet filter that will remove all whitespace and line breaks before sending it off. Drop the jar in the /WEB-INF/lib dir of CF and edit the web.xml file to add the filter. Its configurable as well to remove comments, exclude files or extensions, and preserve specific strings. Been running it for a few years without a problem. A set it and forget it solution.

I've found that even using every possible way to eliminate whitespace, your code may still have some unwanted spaces or line breaks. If you're still experiencing this you may need to sacrifice well formatted code for desired output.
for example, instead of:
<cfprocessingdirective suppressWhiteSpace = "true">
<cfquery ...>
...
...
...
</cfquery>
<cfoutput>
Welcome to the site #query.userName#
</cfoutput>
</cfprocessingdirective>
You may need to code:
<cfprocessingdirective suppressWhiteSpace = "true"><cfquery ...>
...
...
...
</cfquery><cfoutput>Welcome to the site #query.UserName#</cfoutput></cfprocessingdirective>
This isn't CF adding whitespace, but you adding whitespace when formatting your CF.
HTH

Related

Problem with anchor links using resolveurl

I'm using <cfhttp> to pull in content from another site (coldfusion) and resolveurl="true" so all the links work. The problem I'm having is resolveurl is making the anchor links (href="#search") absolute links as well breaking them. My question is is there a way to make resolveurl="true" bypass anchor links somehow?
For starters, let's use the tutorial code from Adobe.com posted in the comments. You'll want to do something similar.
<cfhttp url="https://www.adobe.com"
method="get" result="httpResp" timeout="120">
<cfhttpparam type="header" name="Content-Type" value="application/json" />
</cfhttp>
<cfscript>
// Find all the URLs in a web page retrieved via cfhttp
// The search is case sensitive
result = REMatch("https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?", httpResp.Filecontent);
</cfscript>
<!-- Now, Loop through those URLs--->
<cfoutput>
<cfloop array="#result#" item="item" index="index">
<cfif LEFT(item, 1) is "##">
<!---Your logic if it's just an anchor--->
<cfelse>
<!---Your logic if it's a full link--->
</cfif>
<br/>
</cfloop>
</cfoutput>
If it tries to return a full URL before the anchor as you say, (I've been getting inconsistent results with resolveurl="true") hit it with this to only grab the bit you want.
<cfoutput>
<cfloop array="#result#" item="item" index="index">
#ListLast(item, "##")#
</cfloop>
</cfoutput>
What this code does is grab all the URLs, and parse them for anchors.
You'll have to decide what to do next inside your loop. Maybe preserve the values and add them to a new array, so you can save it somewhere with the links fixed?
It's impossible to assume in a situation like this.
There does not appear to be a way to prevent CF from resolving the hashes. In our usage of it the current result is actually beneficial since when we present content from another site we usually want the user to be sent there.
Here is a way to replace link href values with just anchor if one is present using regular expressions. I'm sure there are combinations of issues that could occur here if really malformed html.
<cfsavecontent variable="testcontent">
<strong>test</strong>
go to google
go to section
</cfsavecontent>
<cfset domain = replace("current.domain", ".", "\.", "all") />
<cfset match = "(href\s*=\s*(""|'))\s*(http://#domain#[^##'""]+)(##[^##'""]+)\s*(""|')" />
<cfset result = reReplaceNoCase(testcontent, match, "\1\4\6", "all") />
<cfoutput><pre>#encodeForHTML(result)#</pre></cfoutput>
Output
<strong>test</strong>
go to google
<a href="#section>go to section</a>
Another option if you are displaying the content in a normal page with js/jquery available is to run through each link on display and update it to just be the anchor. This will be less likely error with malformed html. Let me know if you have any interest in that approach.

cf10 unable to add text to HTML Head

I am getting the following error on a page we are loading:
coldfusion.runtime.CfErrorWrapper
Unable to add text to HTML HEAD tag.
[empty string]
caused by
Template
Unable to add text to HTML HEAD tag.
ColdFusion was unable to add the text you specified to the output stream. This is probably because you have already used a CFFLUSH tag in your template or buffered output is turned off.
I've done a sweep of all the files that are included in our application and cannot find anything that uses CFFlush.
output is set to 'no' on all cfcs and components. I also tried adding cfsetting showdebugoutput = no in a file. That didn't help.
I turned request debugging on in cfadmin and that didn't help.
The HTML Head works fine in other parts of our app, it just seems to be on this one page.
The only thing really different about this page is that it is a particularly long page.
If it's a particularly long page, then CF may be flushing the buffer on its own. If you check in the CFAdmin, on the settings page, there is a setting for Maximum Output Buffer size. I believe the default is 1024 KB. If your page is over 1 meg of content, then CF may flush the buffer before your <cfhtmlhead /> tag runs. Try increasing the buffer size, or changing the placement of the <cfhtmlhead /> tag to see if that corrects the issue.
I've run into the same problem recently but the behavior wasn't predictable. I believe that Dan Short's answer is correct. I created some test pages to see if I could reproduce the problem. Each time TestTemplate.cfm is included, CFHTMLHEAD writes a simple JavaScript alert to the head tag. Once the buffer is reached, and the page is automatically flushed, any subsequent CFHTMLHEAD tag use will result in an error, specifically, the error in the original post. As Dan indicates, you can work your way around this issue by changing the maximum output buffer size.
file: index.cfm
<html>
<head><title>Test Page</title></head>
<body>
<cfset SampleScript = "<script src='sample.js'></script>">
cfset Count = 0>
<cfinclude template="TestTemplate.cfm">
<cfinclude template="TestTemplate.cfm">
<cfinclude template="TestTemplate.cfm">
</body>
</html>
file TestTemplate.cfm
<cfhtmlhead text="#SampleScript#">
<cfset Count++>
<cfoutput>
<h1>Count #Count#</h1>
</cfoutput>
<cfoutput>
<cfloop from="1" to="100000" index="i">
<cfscript>
j = randRange(i, 1000000);
k = randRange(i, 1000000);
l = j * k;
writeOutput(l);
</cfscript>
</cfloop>
</cfoutput>
file sample.js
alert('Boo!');
server.log showed another error that I was submitting too many fields with a POST request. I had to increase this limit on the Settings page.
To fix this, login to Coldfusion Admin, go to Memory Variables, and uncheck 'Disable updating Coldfusion internal cookies using Coldfusion tags/functions.' Save your settings and restart your website.

How do I replace text in all href attributes of anchor tags?

I need to replace the text inside all href values. I think a regular expression is the way to do it, but I'm no regex pro. Any thoughts on how I'd do the following using ColdFusion?
so it is changed to:
Thanks!
Here's an update to the question: I have this code and need the pattern below:
<cfset matches = ReMatch('<a[^>]*href="http[^"]*"[^>]*>(.+?)</a>', arguments.htmlCode) /> <cfdump var="#matches#">
<cfset links = arrayNew(1)>
<cfloop index="a" array="#matches#">
<cfset arrayAppend(links, rereplace(a, 'need regex'," {clickurl}","all"))>
</cfloop>
<cfdump var="#links#">
Here's how to do it with jSoup HTML parser:
<cfset jsoup = createObject('java','org.jsoup.Jsoup') />
<cfset Dom = jsoup.parse( InputHtml ) />
<cfset Dom.select('a[href]').attr('href','{replaced}') />
<cfset NewHtml = Dom.html() />
(On CF9 and earlier, this requires placing the jsoup's jar in CF's lib directory, or using JavaLoader.)
Using a HTML parser is usually better than using regex, not least because it's easier to maintain and understand.
Here's an imperfect way of doing it with a regex:
<cfset NewHtml = InputHtml.replaceAll
( '(?<=<a.{0,99}?\shref\s{0,99}?=\s{0,99}?)(?:"[^"]+|''[^'']+)(["'])'
, '$1{replaced}$1'
)/>
Which hopefully demonstrates why using a tool such as jsoup is definitely the way to go...
(btw, the above is using the Java regex engine (via string.replaceAll), so it can use the lookbehind functionality, which doesn't exist in CF's built-in regex (rereplace/rematch/etc))
Update, based on the new code sample you've provided...
Here is an example of how to use jsoup for what you're doing - it might still need some updates (depending on what {clickurl} is eventually going to be doing), but it currently functions the same as your sample code is attempting:
<cfset jsoup = createObject('java','org.jsoup.Jsoup') />
<cfset links = jsoup.parse( Arguments.HtmlCode )
<!--- select all links beginning http and change their href --->
.select('a[href^=http]').attr('href',' {clickurl}')
<!--- get HTML for all links, then split into array. --->
.outerHtml().split('(?<=</a>)(?!$)')
/>
<cfdump var=#links# />
That middle bit is all a single cfset, but I split it up and added comments for clarity. (You could of course do this with multiple variables and 3+ cfsets if you preferred that.)
Again, it's not a regex, because what you're doing involves parsing HTML, and regex is not designed for parsing tag-based syntax, so isn't very good at it - there are too many quirks and variations with HTML and describing them in a single regex gets very complicated very quickly.

Content-disposition being ignored in IE 9 and Firefox 13

I am trying to dynamically create an inline PDF that, when the user chooses to save it, prompts with my custom filename. According to the documentation, the saveasname attribute should do what I want.
(format="PDF" only) The filename that appears in the SaveAs dialog when a user saves a PDF file written to the browser.
However, what is happening in both IE 9 and in Firefox 13.0.1 is that the filename that appears in the SaveAs dialog is the same as my CF template, but with a PDF extension. (In other words, my code is in makepdf.cfm and the SaveAs prompts me to save makepdf.pdf.) In Chrome, however, it works perfectly. (All on Windows 7.)
Here is my code to create the PDF:
<cfdocument format="pdf" bookmark="true" saveasname="MyReport.pdf">
If I explicitly declare the content disposition and content type, like so
<cfheader name="Content-Disposition" value="inline; filename=MyReport.pdf">
<cfcontent type="application/x-pdf">
<cfdocument format="pdf" bookmark="true" saveasname="MyReport.pdf">
Chrome tells me that "Content-Disposition" has been declared twice
Firefox tells me the PDF file is corrupt
IE just ignores it (and still doesn't show the right filename)
If I just rely on the header
<cfheader name="Content-Disposition" value="inline; filename=MyReport.pdf">
<cfcontent type="application/x-pdf">
<cfdocument format="pdf" bookmark="true">
I get the same behavior as the first snippet of code.
I know how to get the browser to prompt for download rather than displaying inline, and everything works as expected then, but that's not the desired behavior.
I need to use times and dates in filenames and the end users are not savvy enough to keep from overwriting their files (should they choose to save them).
Is there something I'm missing that will get IE and Firefox to do what they're supposed to? What other browsers are going to do this? Mobile Safari?
The problem seems to be that "filename=xxx" was really intended for the "attachment" disposition, and not all the browser PDF plugins recognise it as a mechanism for specifying the inline "save as", as you've discovered.
A different approach to getting them all to use your preferred filename would be to manipulate the URL using web server rewrite rules. As a simple example you'd have your script for generating the pdfs and serving them inline: pdf.cfm
<cfheader name="Content-Disposition" value="inline">
<cfdocument format="PDF" mimetype="application/pdf">Test</cfdocument>
Then create a re-write rule which matches URLs in the form /pdf/myfilename and passes them to pdf.cfm. On IIS7 this might be:
<rule name="Inline PDF SaveAs" stopProcessing="true">
<match url="^/pdf/[\w-]+$" ignoreCase="true" />
<action type="Rewrite" url="/pdf.cfm" appendQueryString="false" />
</rule>
This will match filenames containing alphanumeric, underscore and hyphen characters only. You wouldn't want to allow spaces, or invalid filename characters.
When you access /pdf/myreport the PDF will be displayed inline by the plugin, and when you save it, the default filename will be myreport.pdf.
If you're using a framework which supports Search Engine Safe URLs or "routes", you could do the same without needing web server rewrites.
UPDATE: In fact you don't need to use URL rewriting: simply append a forward slash and then the desired filename to the CF script URL, e.g.
/pdf.cfm/myreport
The plugin will use whatever comes after the final slash as the "Save As..." name.
Make sure you use ATTACHMENT and not INLINE.
IE does NOT like INLINE and will open a word document as READ ONLY as well as not assuming the filename you give it.
Example:
<cfheader name="content-disposition" value="attachment; filename=#filename#.doc" charset="utf-8">
NOT
<cfheader name="content-disposition" value="inline; filename=#filename#.doc" charset="utf-8">
I would use the name attribute of the cfdocument tag which will store the contents in a variable. Then use the cfheader and cfcontent tags as you have above with the exception of replacing "inline;" with "attachment;"
I use code like this:
<cfdocument name="pdf"> ... </cfdocument>
<cfheader name="Content-Disposition" value="attachment;filename=MyReport.pdf;" />
<cfcontent type="application/pdf" variable="#pdf#" />

is there a way to add some spacing to cfmail type=text emails in Coldfusion when using variables only?

I'm a little in awe on how my first Cfmails are looking.
Problem is, I'm using variables for both text and content and I would still like to have some sort of spacing.
For example, if I have:
<cfprocessingdirective suppresswhitespace="No">
<cfmail
TO="#Local.User.email#"
FROM="..."
SERVER="..."
USERNAME="..."
PASSWORD="..."
WRAPTEXT="80"
SUBJECT="#tx_automailer_register_subject# - #Local.User.Comp#">
#tx_automailer_default_hello#
#tx_automailer_register_info#
#tx_automailer_register_iln#: #Local.User.iln#
#tx_firma#: #Local.User.firma#
#tx_ansprechpartner#: #Local.User.ansprechpartner#
#tx_adresse#: #Local.User.adresse#
#tx_plz#: #Local.User.plz#
#tx_ort#: #Local.User.ort#
...
The only place this looks nice is my cfc :-) In the mail itself everything is going bazooka.
Question:
Is there a way to space this? I have also tried to space according to length of variables, but this also does not really do any good and I'm not really keen on doing math for this...
Thanks for help!
The only option may be to post process the content. Build up the pretty content in a cfsavecontent, then run through cleanup function.
<cfprocessingdirective suppresswhitespace="No">
<cfsavecontent variable="message">
#tx_automailer_default_hello#
#tx_automailer_register_info#
#tx_automailer_register_iln#: #Local.User.iln#
#tx_firma#: #Local.User.firma#
#tx_ansprechpartner#: #Local.User.ansprechpartner#
#tx_adresse#: #Local.User.adresse#
#tx_plz#: #Local.User.plz#
#tx_ort#: #Local.User.ort#
</cfsavecontent>
<cfmail
TO="#Local.User.email#"
FROM="..."
SERVER="..."
USERNAME="..."
PASSWORD="..."
WRAPTEXT="80"
SUBJECT="#tx_automailer_register_subject# - #Local.User.Comp#"
>#cleanupTextMessage(message)#</cfmail>
<cffunction name="cleanupTextMessage" output="false">
<cfargument name="content" />
<!--- remove whitespace at beginning of each line --->
<cfset arguments.content = reReplace(arguments.content, "^\s+", "", "all") />
<!--- replace any multiple whitespace characters with one space --->
<cfset arguments.content = reReplace(arguments.content, "\s+", " ", "all") />
<cfreturn arguments.content />
</cffunction>
You might actually be able to nest the cfsavecontent inside cfmail, or create a custom tag that does savecontent and function actions.
Note: I was answering under the assumption the question was "how to make code look good without affecting the resulting text message". If you were trying to do something different with the resulting text output let me know.
You can use HTML To do it by adding the TYPE="html" to your cfmail attributes. Then put in a "pre" tag if you want that sysprint type look. as in
<pre>
#tx_automailer_default_hello#
#tx_automailer_register_info#
....
</pre>
Or you could add a table as in:
<table
<tr>
<td>#tx_automailer_default_hello#</td>
</tr>
<tr><td>
#tx_automailer_register_info#
</td>
If you want to stick with plain text you need to make sure you have tabs/spaces counted correctly and that none of your lines is longer than 80 chars (or they will wrap..without a beat too).
If you're set on plaintext email and are confident that the recipient will be using a fixed-width font, you can use lJustify() to align your text and pad with spaces.
Left justifies characters in a string of a specified length.
#lJustify(tx_automailer_register_iln & ":",32)# #lJustify(Local.User.iln,25)#
#lJustify(tx_firma & ":",32)# #lJustify(Local.User.firma,25)#
#lJustify(tx_ansprechpartner & ":",32)# #lJustify(Local.User.ansprechpartner,25)#
#lJustify(tx_adresse & ":",32)# #lJustify(Local.User.adresse,25)#
#lJustify(tx_plz & ":",32)# #lJustify(Local.User.plz,25)#
#lJustify(tx_ort & ":",32)# #lJustify(Local.User.ort,25)#