© 2007-2011 Matt Chisholm
matt dash pottymouth at theory dot org
What does it do?
PottyMouth transforms completely unstructured and untrusted text to valid, nice-looking, completely safe XHTML.
PottyMouth is designed to handle input text from non-technical, potentially careless or malicious users. It produces HTML that is completely safe, programmatically and visually, to include on any web page. And you don’t need to make your users read any instructions before they start typing. They don’t even need to know that PottyMouth is being used.
What is it for?
PottyMouth is ideal for displaying blog comments, text email bodies in a web mail application or mailing list web archive, or any text fields on any site with user input text, such as a social networking, dating, or community site. In short, any input which is displayed in HTML and is input as text by a non-technical and/or untrusted user. It has been in use on mosuki.com since January 2007, on spydentify.com since January 2008, and on flakenot.com since December 2009.
What is it not for?
PottyMouth is not intended for HTML page generation, such as writing blog entries, where the author is an authorized and trusted user who may want to exert more control over the content of his or her post. Markdown and SmartyPants, or Textism are good solutions for trusted HTML authoring.
PottyMouth is also not intended for wikis, where the text is more heavily structured and where poorly formatted or malicious input can be quickly corrected by another user. There are many good wiki packages out there; this is not one of them.
Why should I care about…?
…unstructured text input?
The average, non-technical user doesn’t care about formatting syntax and won’t take the time to learn it. PottyMouth lets your website display any user input without having to make your users learn anything. The only “syntax” that PottyMouth uses are conventions that are ubiquitous on-line. If your site displays text input from external programs, third-party sites, or other sources like email, you can’t rely on your users to know about your site’s text formatting conventions.
You want to allow your users the freedom to put whatever they want on your site. But you don’t want badly formatted text to make that text look ugly, or to screw up the layout of other elements on the page.
…untrusted text input?
If it’s possible for an untrusted or anonymous user to input text that gets inserted in HTML on your site, you need to process that text to make sure it cannot cause problems for other visitors. If your site displays text input from external programs, third-party sites, or other sources like email, you can’t control or check that text until you are displaying it.
What does it prevent?
PottyMouth prevents against a wide range of potential problems:
- no overriding of site CSS via
- no attacks via malicious
<embed>or other media tags
- no damage to site layout via inserted CSS or
height, or other HTML attributes
Although the problems above could be solved by simply allowing a short white-list of HTML tags and no HTML attributes whatsoever, inserting raw HTML tags is a feature that non-technical users don’t need. And PottyMouth automatically detects most of the instances where the average user would want HTML tags.
Instead of having syntax that users must learn, PottyMouth relies on some ubiquitous text formatting conventions to generate the best HTML possible.
Paragraphs, newlines, and ad-hoc lists
PottyMouth intelligently identifies paragraph breaks, newlines, and ad-hoc lists. A sequence of one or more blank lines is considered to separate two paragraphs (or other block-like items, like lists). Within a single paragraph, PottyMouth distinguishes between “short” and “long” lines and treats them differently.
- A sequence of long lines is treated as a single, unbroken line, without newlines.
- A single short line between two long lines is also treated as part of the single, long line, and does not insert a newline either. This ensures that text that has been hard wrapped more than once at decreasing line lengths is repaired, and rendered as a single unbroken paragraph.
- Two or more consecutive short lines are treated as an ad-hoc list, and a line break is inserted between them. Thus a list-like sequences of short lines are preserved.
Extensive testing has shown that fifty characters is a good threshold between short and long lines (this threshold is configurable if your data differs, however). Here’s an example:
This is some text that has been through a bunch of broken email programs and got hard line wrapped really badly at some point because a programmer was lazy. here's some more text where someone decided to list their favorite things: raspberries pink hair devil ducks science fiction And that list goes right in the middle of a paragraph, but does it screw up potty mouth? Nope.
This is some text that has been through a bunch of broken email programs and got hard line wrapped really badly at some point because a programmer was lazy.
here’s some more text where someone decided to list their favorite things:
And that list goes right in the middle of a paragraph, but does it screw up potty mouth? Nope.
Detecting very long sequences of non-breaking characters and inserting a soft hyphen (­) character that will cause natural text wrapping is planned for a future release.
PottyMouth identifies sequences of lines beginning with one or more
> and groups them into nested sequences of
<p> tags. In other words, input like this:
A reply to a reply More of the reply to the reply > A reply to a message > More of the reply to the message >> The original message >> More of the original message > Last line of the reply Last line of the reply to the reply
is rendered like this:
A reply to a reply
More of the reply to the reply
A reply to a message
More of the reply to the message
The original message
More of the original message
Last line of the reply
Last line of the reply to the reply
As with ordinary paragraphs, sequences of one or more blank lines are treated as paragraph breaks, even if those blank lines are prefixed with one or more
You may turn off block quote detection by initializing PottyMouth with
Literal list syntax
PottyMouth identifies literal lists denoted by lines beginning with
1., or any number of digits followed by a period, for ordered lists, and
• (bullet, •), for unordered lists. The first item in the list determines whether the entire list is ordered or unordered. This:
# science fiction # devil ducks # raspberries And an unordered list: * raspberries - pink hair # devil ducks • point-set topology And a mis-numbered one: 1. the unit 1. binary 413. ternary
- science fiction
- devil ducks
And an unordered list:
- pink hair
- devil ducks
- point-set topology
And a mis-numbered one:
- the unit
An indented line immediately following a list item is treated as a continuation of that list item.
Nested lists are not supported. Nested lists are an important feature in documents with heavily structured content deliberately created by careful editors who want to take the time to learn syntax and structure their content appropriately. PottyMouth is for displaying ad-hoc text input quickly by non-technical users, where flat literal lists are occasional and nested lists are vanishingly rare.
Just as with the other block-level items (paragraphs and block quotes), sequences of one or more blank lines terminate a list.
You may turn off all list support by initializing PottyMouth with
all_lists=False. You may turn off just ordered lists, or just unordered lists, by initializing PottyMouth with
unordered_list=False=False. And you may turn off just numbered lists (list items beginning with a sequence of digits and a period) with
Definition list syntax
PottyMouth identifies term/definition lists denoted by lines beginning with a few words (two to twenty characters) followed by a
: and whitespace. This:
Host: Craig Location: Craig's Pad, 666 Marchaunt Ave., Apt. 6, Spokane, CA 94616 US When: Saturday, November 7, 4:30PM Phone: 123-555-1212
- Craig’s Pad, 666 Marchaunt Ave., Apt. 6, Spokane, CA 94616 US
- Saturday, November 7, 4:30PM
As with paragraphs, block quotes, and lists, sequences of one or more blank lines terminate a definition list. And, as with lists, an indented line immediately following a definition list line will be treated as a continuation of that definition item.
You may turn off definition list support by initializing PottyMouth with
definition_list=False. Definition lists were added in PottyMouth 1.2.
PottyMouth identifies hyperlinks beginning with these protocols:
nntp, and ending in a valid URL. Adding new protocols is trivial. It also identifies URLs beginning with
www. and prepends
When using PottyMouth to generate content for a web application, it expects you to provide it with a list of one or more domain names for the site. Unless you explicitly leave this name blank, PottyMouth will only hyperlink links that point to other sites.
If you want PottyMouth to hyperlink site-internal links, you must also provide it with a white-list of regular expressions that match allowed site-internal links. This allows you to denote the site-internal URLs that users can include that will become hyperlinked, and other URLs will remain as text.
For example, if you were using PottyMouth on
http://www.mysite.com, and chose to allow links to posts, you would use a whitelist like
https?://(www\.)?mysite\.com/viewpost\?id=\d+. Then, these URLs would get hyperlinked:
But these URLs, which might just be mis-typed, mis-encoded, or might be malicious URLs, would not get hyperlinked:
http://www.mysite.com/viewpost=3Fid=3D1234(Whoops, encoding problem)
http://static.mysite.com/randomimage.gif(Whoops, disallowed host name on the same domain)
While PottyMouth should not be considered a substitute for correctly protecting against the latter two types of malicious links in your software, preventing them from being automatically hyperlinked on your site raises the bar significantly for these types of attacks.
You may turn off all hyperlinking by initializing PottyMouth with
all_links=False, and you may turn off just email address hyperlinking with
PottyMouth optionally allows embedded media. URLs ending in .JPG, .JPEG, .GIF, and .PNG are considered to be embedded images, and are included as
<img> tags. It also detects links to YouTube videos and embeds them using YouTube’s standard embedding syntax.
The embedded media feature is disabled by default, because it does somewhat compromise the safety of the generated HTML. Embedded media could be used to launch cross-site scripting attacks on another site, if an attacker can generate a malicious URL to the remote site that ends in JPG, GIF, or PNG. However, protecting against cross-site scripting attacks is really the responsibility of the target site, not you.
Embedded media could also be used as web bugs by a third party to collect IP addresses of visitors to your site. This could only be mitigated by running a cache which served the third party content to your site visitors, and appending the target URL onto the cache service. Adding configuration options for this is planned for a future release.
Embedded media is still relatively safe, for the following reasons:
- The URL white-listing of hyperlinks is applied before identifying hyperlinks to media, so linking to malicious site-internal URLs, or random images on the site is still not possible.
srcattribute of an
<img>tag, so linking to malicious content is still not possible.
- By correctly setting the CSS
overflowand size properties of the HTML element containing PottyMouth generated HTML, large embedded images will not interfere with page layout.
- By only allowing embedded Flash widgets from a set of sites known to produce (relatively) trustworthy Flash, the possibility of including malicious Flash is low.
You may turn off image tag creation and YouTube embedding by initializing PottyMouth with
youtube=False. Image and YouTube URLs are then treated as ordinary hyperlinks (see above).
Bold and italic
PottyMouth identifies balanced sets of
_ and turns them into bold (
<b>) and italic (
<i>) tags. This support was added because this shorthand is extremely common in text input, even from non-technical users. Bold and italic can be nested; however, they cannot be overlapped and neither can be nested, at any depth, inside itself. Un-balanced
_ are rendered literally.
this is *bold _and italic_* or _italic *and bold*_ or just *one* or the _other_ but *I dunno _what* this_ is *supposed to* be.
this is bold and italic or italic and bold or just one or the other but I dunno _ what this _ is supposed to be.
Support for other shorthands, such as
- for strikeout and
= for monospaced text is a possibility, but unlikely as it requires some user knowledge, is much rarer than
_, and would likely interfere with the normal use of those characters.
You may turn off bold and italic creation by initializing PottyMouth with
PottyMouth renders single and double quotes, backticks, ellipsis and double-dashes into the appropriate HTML entities:
foo's ball⇒ foo’s ball
foo...⇒ foo… (ellipsis)
foo--bar⇒ foo—bar (emdash)
Single dashes are not converted into dash, hyphen, minus or emdash, as it is not possible to reliably detect what is the correct character to use from context. See The Trouble With EM ’n EN for more information. Because PottyMouth is intended for non-technical, novice users, there is no syntax for distinguishing these characters.
All characters that are not valid HTML, including
&, are escaped in the output.
Support for smilies and additional special characters is a future possibility.
You may turn off smart quotes, ellipsis, and emdash detection by initializing PottyMouth with
To use PottyMouth's Python implementation, first instantiate a parser and tell it what domain it’s going to be used on:
from pottymouth import PottyMouth pm = PottyMouth(url_check_domains=('www.mysite.com', 'mysite.com'), url_white_lists=('https?://www\.mysite\.com/allowed/url\?id=\d+',), )
parse() method returns a
PottyMouth.Node object representing a
<div> node, and containing
div_node = pm.parse(string_to_parse)
You can then stringify them with
str() or just
PottyMouth.Node objects inherit from native Python
lists, so you may also iterate over their contents and convert them to whatever native XHTML objects that your application requires.
The Ruby version uses an identical interface.
Python module configuration
You may disable specific components of PottyMouth's syntax by passing in any combination of the following key-word arguments when initializing a new PottyMouth instance. (This feature is only available in the Python module.)
- disables all URL hyperlinking
- disables <img> tags for image URLs
- disables YouTube embedding
- disables mailto:email@example.com URLs
- disables all lists (<ol> and <ul>)
- disables all unordered lists (<ul>)
- disables all ordered lists (<ol>)
- disables '\d+\.' list elements
- disables '>' <blockquote>s
- disables all definition lists (<dl>)
- disables *bold*
- disables _italics_
- disables -- emdash
- disables ... ellipsis
- disables smart quotes
All of these options are enabled by default. You only need to pass
foo=False if you wish to disable one.
By default PottyMouth generates UTF-8 encoded xHTML fragments. If you want a different encoding, set the module-level
encoding configuration variable:
PottyMouth.encoding = 'ascii'
Any characters that cannot be encoded using the configured encoding will be replaced with numeric HTML entities.
Then pass some text to PottyMouth's
toString() method to convert the object to a HTML string.
<script> var output = pottymouth.parse("Some *text* to parse!") output = output.toString(); document.getElementById('potty_output').innerHTML = output; </script>
You can also download Python packages of the latest stable release, 2.2.1, released 9 September 2012:
- From pypi with
- older versions
An experimental (obsolete) port of PottyMouth 1.0.2 to Ruby 1.9.0 is also available:
If you have any suggestions or problems with PottyMouth, please feel free to email me at matt dash pottymouth at theory dot org or create an issue on GitHub.
If you use PottyMouth and like it, please consider donating via Flattr:
Potty input: (1000 characters maximum)