How to display code in plain text? - html

I want to display bare code on an HTML page, I tried this:
<script>
function getSize() {
var myFSO = new ActiveXObject("Scripting.FileSystemObject");
var filepath = document.upload.file.value;
var thefile = myFSO.getFile(filepath);
var size = thefile.size;
alert(size + " bytes");
}
</script>
The above JavaScript code is some code entered by the user. I can't figure out to show this bare code on the html page without being interpreted and screwed up by the browser.
How do I display bare code on an HTML page?

I'm not quite clear on the specifics of the issue, as pre tags should, in general, do the trick, but here's an alternative tag:
<xmp>[Code can be displayed here]</xmp>
If you're using a server-side language, though, I'd suggest converting to HTML entities before outputting, then using CSS to style it.
As well, be sure if you're accepting user input that any JavaScript is being filtered and never executed.

You can use the <pre> and <code> tags to display formatted code. But to prevent the code from executing and not displaying you'll need to convert the text to character entities. > becomes >, < becomes &lt, etc.
You could do this by using PHP, for example:
<?php echo htmlentities('function getSize() { var myFSO = new
ActiveXObject("Scripting.FileSystemObject");
var filepath =
document.upload.file.value; var
thefile = myFSO.getFile(filepath);
var size = thefile.size; alert(size
+ " bytes"); }'); ?>
As your system relies on user input, you might have to rely on AJAX to actually process the user input and convert it to HTML entities.

Use the <code></code> tag, and use javascript or your sever-side scripting language

Dump it into a textarea and render it like a div tag
This is a bit of a hack and parlor trick, but it works.
Get bare code rendered onto an HTML page is to place it in a text area and remove all the formatting around the textarea so it looks like a <div> tag:
Code:<br>
<textarea style="border: none;width:400;height:200;background-color:lightgrey;">
#include<iostream>
using namespace std;
class Box{
public:
int mymethod(){ cout << "is method"; }
};
int myfunction(){ cout << "is function"; }
int main(){
Box b;
b.mymethod();
myfunction();
}
</textarea>
<br>
Output:
<pre>is methodis function
</pre>
The above html code should render like this on the page:
What I've done is invalid HTML, it only works because customary error handling happens to handle it this way. You shouldn't put unescaped angle brackets in the content of a <textarea>. You get undefined behavior depending on how the browser chooses to interpret your textarea tag.

The most reliable method is to htmlencode the code to be displayed on the page.
For example
< into &lt
space into &nbsp
etc.

Related

Line breaks in templated HTML scriptlets

If I have an HTML file test.html:
<p><?= str ?></p>
And a script function:
var t = HtmlService.createTemplateFromFile("test.html");
t.str = "test\nstring";
var content = t.evaluate().setSandboxMode(...).getContent();
Logger.log(content);
Is there any way to safely replace the newline with an HTML line break? I can use String.prototype.replace() to replace \n with <br/>, but then I'd have to use <?!= to disable the HTML templating engine's contextual escaping. I'm dealing with untrusted input and so I need both escaping and smart handling of line breaks. Having it contextually would be nice. As things stand, I wrote my own escaper, but it is only good for one context.
I see two options for your scenario, the simple one is to forget the substitution entirely and use a <pre> tag, which will render your line breaks (and other formatting chars)
<pre> <?= str ?> </pre>
The second is to perform the substitution and sanitize your input with a custom function, so that you can safely use the force print scriptlet.
In your html:
<?!= sanitize(str); ?>
and in your .gs:
function sanitize(val){
var vals = val.split('\n'); //split string into an array on newlines
for(var i in vals){
vals[i] = Encoder.htmlEncode(vals[i]); //sanitize each element in the array
}
return vals.join('<br />'); //join the elements as a string, with <br /> as glue.
}
Note, in my example I'm using the library located here to sanitize the strings: http://www.strictly-software.com/scripts/downloads/encoder.js
If anyone's curious, this is the code I wound up using to sanitize the untrusted input for display. It's not safe for use inside tags, in script sections, etc. That's why Google's context aware sanitization is so handy.
function dumbEscapeAndBreak(str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\n/g, '<br/>');
}
function _testEscape() {
GSUnit.assertEquals('my<test<string>is>not&good&okay<br/>fine<br/>okay', dumbEscapeAndBreak("my<test<string>is>not&good&okay\nfine\nokay"));
}
Or you can do this:
In your .gs script function:
var t = HtmlService.createTemplateFromFile("test.html");
var paragraphs = "test\nstring";
t.str = paragraphs.split("\n");
In your test.html:
<?
for (i = 0; i < str.length; i++) {
?>
<span><?= str[i]?></span><br />
<!-- <p><?= str[i]?></p> -->
<?
}
?>
You can use the <span> or <p> tag, that is up to you. You can also write some simple logic to decide when to put the <br />, e.g. before <span> when i > 0. That will completely fulfil your "test\nstring".

Allow using some html tags in MVC 4

How i can allow client to use html tags in MVC 4?
I would like to save records to the database and when it extract in view allow only some HTML tags (< b > < i > < img >) and others tags must be represented as text.
My Controller:
[ValidateInput(false)]
[HttpPost]
public ActionResult Rep(String a)
{
var dbreader = new DataBaseReader();
var text = Request["report_text"];
dbreader.SendReport(text, uid, secret).ToString();
...
}
My View:
#{
var dbreader = new DataBaseReader();
var reports = dbreader.GetReports();
foreach (var report in reports)
{
<div class="report_content">#Html.Raw(report.content)</div>
...
}
}
You can replace all < chars to HTML entity:
tags = tags.Replace("<", "<");
Now, replace back only allowed tags:
tags = tags
.Replace("<b>", "<b>")
.Replace("</b>", "</b>")
.Replace("<i>", "</i>")
.Replace("</i>", "</i>")
.Replace("<img ", "<img ");
And render to page using #Html.Raw(tags)
If you are trying some property of your view model object to accept Html text, use AllowHtmlAttribute
[AllowHtml]
public string UserComment{ get; set; }
and before binding to the view
model.UserComment=model.UserComment.Replace("<othertagstart/end>",""); //hard
Turn off validation for report_text (1) and write custom HTML encoder (2):
Step 1:
Request.Unvalidated().Form["report_text"]
More info here. You don't need to turn off validation for entire controller action.
Step 2:
Write a custom html encoder (convert all tags except b, i, img to e.g.: script -> ;ltscript;gt), since you are customizing a default behaviour of request validation and html tag filtering. Consider to safeguard yourself from SQL injection attacks by checking SQL parameters passed to stored procedures/functions etc.
You may want to check out BBCode BBCode on Wikipedia. This way you have some control on what is allowed and what's not, and prevent illegal usage.
This would work like this:
A user submits something like 'the meeting will now be on [b]monday![/b]'
Before saving it to your database you remove all real html tags ('< ... >') to avoid the use of illegal tags or code injection, but leave the pseudo tags as they are.
When viewed you convert only the allowed pseudo html tags into real html
I found solution of my problem:
html = Regex.Replace(html, "<b>(.*?)</>", "<b>$1</b>");
html = Regex.Replace(html, "<i>(.*?)</i>", "<i>$1</i>");
html = Regex.Replace(html, "<img(?:.*?)src="(.*?)"(?:.*?)/>", "<img src=\"$1\"/>");

code tag and pre css in html not functioning properly

in html i am using the code tag as below and also i am using the css as shown below :-
<style type="text/css">
code { white-space: pre; }
</style>
<code>
public static ArrayList<File> getFiles(File[] files){
ArrayList<File> _files = new ArrayList<File>();
for (int i=0; i<files.length; i++)
if (files[i].isDirectory())
_files.addAll(getFiles(new File(files[i].toString()).listFiles()));
else
_files.add(files[i]);
return _files;
}
public static File[] getAllFiles(File[] files) {
ArrayList<File> fs = getFiles(files);
return (File[]) fs.toArray(new File[fs.size()]);
}
</code>
When i use the code tag as shown above some part of the code is missing in the html page when viewed. when view the above html page the output is as shown below:-
public static ArrayList getFiles(File[] files){
ArrayList _files = new ArrayList();
for (int i=0; i fs = getFiles(files);
return (File[]) fs.toArray(new File[fs.size()]);
}
In the first method some part is missing and the second method is not appearing at all. what is the problem and how to fix it?
You have these <File> inside your <code> tag, you need to convert them to < and > html entities
Demo
<code>
public static ArrayList<File> getFiles(File[] files){
ArrayList<File> _files = new ArrayList<File>();
for (int i=0; i<files.length; i++)
if (files[i].isDirectory())
_files.addAll(getFiles(new File(files[i].toString()).listFiles()));
else
_files.add(files[i]);
return _files;
}
public static File[] getAllFiles(File[] files) {
ArrayList<File> fs = getFiles(files);
return (File[]) fs.toArray(new File[fs.size()]);
}
</code>
As already identified by Mr. Alien, you have characters being interpreted as markup inside your <code> block.
As an alternative to escaping lots of characters, providing your code does not include the string </script, you can exploit the parsing and (non)execution behaviour of the <script> element like this:
<code>
<script type="text/x-code">
public static ArrayList<File> getFiles(File[] files){
ArrayList<File> _files = new ArrayList<File>();
for (int i=0; i<files.length; i++)
if (files[i].isDirectory())
_files.addAll(getFiles(new File(files[i].toString()).listFiles()));
else
_files.add(files[i]);
return _files;
}
public static File[] getAllFiles(File[] files) {
ArrayList<File> fs = getFiles(files);
return (File[]) fs.toArray(new File[fs.size()]);
}
</script>
</code>
with this CSS:
script[type=text\/x-code] {
display: block;
white-space: pre;
line-height: 20px;
margin-top: -20px;
}
See JSfiddle: http://jsfiddle.net/fZuPm/3/
Update: In the comments, RoToRa raises some interesting points about the "correctness" of this approach, and I thank RoToRa for them.
Using a type attribute to stop the contents of a script tag from being executed as JavaScript is a well understood technique, and although the list of type names that cause script to be executed varies from browser to browser, finding one that won't cause execution is not hard.
More interesting is the question of the semantics. It is my view that the semantics of the script element are essentially inert, like a div or span element, while RoToRa's view is that it affects the semantics of the content. Looking at the specs, it is not easy to resolve. HTML 4.01 says very little about the semantics of the script element, concentrating solely on its functionality.
The HTML5 spec is not much better, but it does say "The element does not represent content for the user.". I don't know what to make of that. Saying what an element doesn't do is not very helpful. If it implies that its contents are semantically "hidden" from the user, such that the its contents are not semantically part of contents of the containing code element, then this technique should not be used.
If, however, it means that no new semantics are introduced by the script element, then there doesn't appear to be any problem.
I can't find any evidence of a script element being semantically required to contain script, as RoToRa suggests, and while it might be considered common-sense to infer that, that's not how HTML semantics works.
In many ways, this approach is really about trying to find a way to do validly what the XMP element does in browsers anyway, but is not valid. XMP was very nearly made valid in HTML5 but just missed out. The editor described it as a tough call. Using the script element like this meets that requirement, but it seems nevertheless to be controversial. If you are uncomfortable with whatever semantics you feel are being applied is this approach, I would suggest that you don't use it.

Put a bit of HTML inside a <pre> tag?

How do I put a bit of HTML inside a tag without escaping it? Or am I using an incorrect tag?
P.S. I cannot escape the HTML, it is produced by the server.
If you have no control over the emitted HTML, you can still encode it on the client side.
Here is how you would escape all markup inside <pre> tags using the jQuery library:
$(function() {
var pre = $('pre');
pre.html(htmlEncode(pre.html()));
});
function htmlEncode(value){
return $('<div/>').text(value).html();
}
Edit: As requested, same code without using jQuery:
function encodePreElements() {
var pre = document.getElementsByTagName('pre');
for(var i = 0; i < pre.length; i++) {
var encoded = htmlEncode(pre[i].innerHTML);
pre[i].innerHTML = encoded;
}
};
function htmlEncode(value) {
var div = document.createElement('div');
var text = document.createTextNode(value);
div.appendChild(text);
return div.innerHTML;
}
And run the encodePreElements after the DOM has been loaded:
<body onLoad='encodePreElements()'>
<pre>Foo <b>bar</b></pre>
</body>
This:
<pre>
<‍div>Hello<‍/div>
</pre>
Prints this:
<div>Hello</div>
Zero Width Joiner = ‍
You need to escape the HTML, like so:
You can use HTML entities that are escaped and printed without compiling.
< // will print <
> // will print >
Using these two, you can print any HTML elements.
<div> // will print <div>
To solve your specific problem, you will need to parse the HTML string and convert the chevrons to these entities.

jsf messages: adding link

Currently in JSF, all HTML contained within a message (rich:messages tag) is escaped and just shows up as the markup. For example, in my backing bean, I have:
createMessage("Title created successfully with product number: " + product.getProductNumber() + ".");
where createMessage() is just a helper function that adds a new Message to the faces context and is then viewable in my rich:messages tag.
When this message is created, my message simply shows up with the escaped HTML:
Title created successfully with product number: 1234.
Is there any way to avoid this and just provide an actual link in the message instead?
Thanks in advance
~Zack
A quick solution is to create a new renderer.
I've done this for h:messages as I wanted to separate the messages of different severities into separate divs. If you never want to use the default renderer then it's a good option.
The standard class that you would overwrite/extend is:
public class MessagesRenderer extends HtmlBasicRenderer
You would just use a ResponseWriter that doesn't escape the text. The concrete class is the HtmlResponseWriter which escapes the text. You could extend this and overwrite the
public void writeText(Object text, String componentPropertyName)
so that it doesn't use HtmlUtils.
Then just add your new renderer to faces-config.xml
<render-kit>
<renderer>
<component-family>javax.faces.Messages</component-family>
<renderer-type>javax.faces.Messages</renderer-type>
<renderer-class>com.mypackage.MessagesRenderer</renderer-class>
</renderer>
</render-kit>
It sounds like you need to create your own version of rich:messages that has an escape attribute, like h:outputText, so you can disable HTML escaping.
If you're using jquery you can unescape the xml characters:
<script type="text/javascript">
//<![CDATA[
$(document).ready(function() {
$(".esc").each(function(i) {
var h = $(this).html();
h = h.replace(/</gi, "<");
h = h.replace(/>/gi, ">");
$(this).html(h);
});
});
//]]>
</script>