PottyMouth

© 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.

…layout-safe HTML?

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.

…secure HTML?

Allowing anyone to insert raw or even limited HTML into your site is dangerous. If an attacker can insert JavaScript, media, or malicious links into your site, he or she can cause a user or their browser to perform malicious actions or send spam, on your site or third party sites, or they can insert DHTML id attributes or JavaScript to break your DHTML/JavaScript application. If an attacker can insert CSS into your site, they can hide or override advertisements, warnings, or instructions with their own content.

What does it prevent?

PottyMouth prevents against a wide range of potential problems:

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.

PottyMouth syntax

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.

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.

becomes:

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.

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.

Block quotes

PottyMouth identifies sequences of lines beginning with one or more > and groups them into nested sequences of <blockquote> and <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 > characters.

You may turn off block quote detection by initializing PottyMouth with blockquote=False.

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 *, -, or (bullet, &#8226;), 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

becomes:

  1. science fiction
  2. devil ducks
  3. raspberries

And an unordered list:

And a mis-numbered one:

  1. the unit
  2. binary
  3. ternary

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 ordered_list=False, and/or unordered_list=False=False. And you may turn off just numbered lists (list items beginning with a sequence of digits and a period) with numbered_list=False

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

becomes:

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

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: http, https, webcal, feed, ftp, news, and nntp, and ending in a valid URL. Adding new protocols is trivial. It also identifies URLs beginning with www. and prepends http://.

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:

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 email=False.

Embedded media

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:

You may turn off image tag creation and YouTube embedding by initializing PottyMouth with image=False, and/or youtube=False. Image and YouTube URLs are then treated as ordinary hyperlinks (see above).

Bold and italic

PottyMouth identifies balanced sets of * and _ 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 * and _ 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.

produces:

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 _, and would likely interfere with the normal use of those characters.

You may turn off bold and italic creation by initializing PottyMouth with bold=False, and/or italic=False.

Special characters

PottyMouth renders single and double quotes, backticks, ellipsis and double-dashes into the appropriate HTML entities:

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 <, >, and &, 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 smart_quotes=False, ellipsis=False, and/or emdash=False.

Usage

PottyMouth is implemented as a Python module and as a JavaScript module. (There is also an outdated port to Ruby 1.9.)

Python Usage

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+',),
)

The parse() method returns a PottyMouth.Node object representing a <div> node, and containing <p> nodes.

div_node = pm.parse(string_to_parse)

You can then stringify them with str() or just print them:

print div_node

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.)

all_links=False
disables all URL hyperlinking
image=False
disables <img> tags for image URLs
youtube=False
disables YouTube embedding
email=False
disables mailto:email@site.com URLs
all_lists=False
disables all lists (<ol> and <ul>)
unordered_list=False
disables all unordered lists (<ul>)
ordered_list=False
disables all ordered lists (<ol>)
numbered_list=False
disables '\d+\.' list elements
blockquote=False
disables '>' <blockquote>s
definition_list=False
disables all definition lists (<dl>)
bold=False
disables *bold*
italic=False
disables _italics_
emdash=False
disables -- emdash
ellipsis=False
disables ... ellipsis
smart_quotes=False
disables smart quotes

All of these options are enabled by default. You only need to pass foo=False if you wish to disable one.

Any non-ASCII characters in the input will be replaced with numeric HTML entities in the output.

Javascript Usage

To use PottyMouth's JavaScript implementation, download the latest JavaScript implementation of PottyMouth and include it in your HTML. Then instantiate a parser and tell it what domain it’s going to be used on, and which URLs on that domain the user is allowed to link to:

<script src="pottymouth.js" type="text/javascript">
<script>
  var pottymouth = new PottyMouth(
    ['mysite.com', 'www.mysite.com'],
    ['https?://www\.mysite\.com/allowed/url\?id=\d+']
  );
</script>

Then pass some text to PottyMouth's parse() method. This will return a JavaScript object. Then call that object'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>

Download

PottyMouth is licensed under the BSD License. The Python implementation requires Python, version 2.6, 2.7, or 3.3 and newer. Python versions 3.0 through 3.2 are not supported, due to the lack of support for \u sequences in regular expressions. The last version to support Python 2.4 and 2.5 was 2.1.4.

You can check out the latest development version from GitHub with
git clone git://github.com/glyphobet/pottymouth.git. The BitBucket repository is obsolete as of version 2.2, don't use it.

You can also download Python packages of the latest stable release, 2.2.1, released 9 September 2012:

You can also download the latest JavaScript implementation from github.com:

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:

Demonstration

Potty input: (1000 characters maximum)

Potty output: