1 <?xml version=
"1.0" encoding=
"UTF-8"?>
2 <!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4 <html xmlns=
"http://www.w3.org/1999/xhtml" xml:
lang=
"en" lang=
"en"><head>
5 <meta http-equiv=
"Content-Type" content=
"text/html; charset=UTF-8" />
6 <meta name=
"description" content=
"Tutorial for customizing HTML Purifier's tag and attribute sets." />
7 <link rel=
"stylesheet" type=
"text/css" href=
"style.css" />
9 <title>Customize - HTML Purifier
</title>
13 <h1 class=
"subtitled">Customize!
</h1>
14 <div class=
"subtitle">HTML Purifier is a Swiss-Army Knife
</div>
16 <div id=
"filing">Filed under End-User
</div>
17 <div id=
"index">Return to the
<a href=
"index.html">index
</a>.
</div>
18 <div id=
"home"><a href=
"http://htmlpurifier.org/">HTML Purifier
</a> End-User Documentation
</div>
21 You may have heard of the
<a href=
"dev-advanced-api.html">Advanced API
</a>.
22 If you're interested in reading dry prose and boring functional
23 specifications, feel free to click that link to get a no-nonsense overview
24 on the Advanced API. For the rest of us, there's this tutorial. By the time
25 you're finished reading this, you should have a pretty good idea on
26 how to implement custom tags and attributes that HTML Purifier may not have.
29 <h2>Is it necessary?
</h2>
32 Before we even write any code, it is paramount to consider whether or
33 not the code we're writing is necessary or not. HTML Purifier, by default,
34 contains a large set of elements and attributes: large enough so that
35 <em>any
</em> element or attribute in XHTML
1.0 or
1.1 (and its HTML variants)
36 that can be safely used by the general public is implemented.
40 So what needs to be implemented? (Feel free to skip this section if
41 you know what you want).
47 All of the modules listed below are based off of the
48 <a href=
"http://www.w3.org/TR/2001/REC-xhtml-modularization-20010410/abstract_modules.html#sec_5.2.">modularization of
49 XHTML
</a>, which, while technically for XHTML
1.1, is quite a useful
56 <li>Applets (deprecated)
</li>
62 <li>Meta-information
</li>
64 <li>Link (not hypertext)
</li>
70 If you don't recognize it, you probably don't need it. But the curious
71 can look all of these modules up in the above-mentioned document. Note
72 that inline scripting comes packaged with HTML Purifier (more on this
79 As of HTMLPurifier
2.1.0, we have implemented the
80 <a href=
"http://www.w3.org/TR/2001/REC-ruby-20010531/">Ruby module
</a>,
81 which defines a set of tags
82 for publishing short annotations for text, used mostly in Japanese
83 and Chinese school texts, but applicable for positioning any text (not
84 limited to translations) above or below other corresponding text.
90 <a href=
"http://www.w3.org/TR/xhtml2/">XHTML
2.0</a> is still a
91 working draft, so any elements introduced in the
92 specification have not been implemented and will not be implemented
93 until we get a recommendation or proposal. Because XHTML
2.0 is
94 an entirely new markup language, implementing rules for it will be
101 <a href=
"http://www.whatwg.org/specs/web-apps/current-work/">HTML
5</a>
102 is a fork of HTML
4.01 by WHATWG, who believed that XHTML
2.0 was headed
103 in the wrong direction. It too is a working draft, and may change
104 drastically before publication, but it should be noted that the
105 <code>canvas
</code> tag has been implemented by many browser vendors.
111 There are a number of proprietary tags still in the wild. Many of them
112 have been documented in
<a href=
"ref-proprietary-tags.txt">ref-proprietary-tags.txt
</a>,
113 but there is currently no implementation for any of them.
119 There are also a number of other XML languages out there that can
120 be embedded in HTML documents: two of the most popular are MathML and
121 SVG, and I frequently get requests to implement these. But they are
122 expansive, comprehensive specifications, and it would take far too long
123 to implement them
<em>correctly
</em> (most systems I've seen go as far
124 as whitelisting tags and no further; come on, what about nesting!)
128 Word of warning: HTML Purifier is currently
<em>not
</em> namespace
135 As you may imagine from the details above (don't be abashed if you didn't
136 read it all: a glance over would have done), there's quite a bit that
137 HTML Purifier doesn't implement. Recent architectural changes have
138 allowed HTML Purifier to implement elements and attributes that are not
139 safe! Don't worry, they won't be activated unless you set %HTML.Trusted
140 to true, but they certainly help out users who need to put, say, forms
141 on their page and don't want to go through the trouble of reading this
142 and implementing it themself.
146 So any of the above that you implement for your own application could
147 help out some other poor sap on the other side of the globe. Help us
148 out, and send back code so that it can be hammered into a module and
149 released with the core. Any code would be greatly appreciated!
155 Enough philosophical talk, time for some code:
158 <pre>$config = HTMLPurifier_Config::createDefault();
159 $config-
>set('HTML', 'DefinitionID', 'enduser-customize.html tutorial');
160 $config-
>set('HTML', 'DefinitionRev',
1);
161 $def = $config-
>getHTMLDefinition(true);
</pre>
164 Assuming that HTML Purifier has already been properly loaded (hint:
165 include
<code>HTMLPurifier.auto.php
</code>), this code will set up
166 the environment that you need to start customizing the HTML definition.
172 The first three lines are regular configuration code:
175 %HTML.DefinitionID is set to a unique identifier for your
176 custom HTML definition. This prevents it from clobbering
177 other custom definitions on the same installation.
180 %HTML.DefinitionRev is a revision integer of your HTML
181 definition. Because HTML definitions are cached, you'll need
182 to increment this whenever you make a change in order to flush
188 The fourth line retrieves a raw
<code>HTMLPurifier_HTMLDefinition
</code>
189 object that we will be tweaking. If the parameter was removed, we
190 would be retrieving a fully formed definition object, which is somewhat
191 useless for customization purposes.
195 <h3>Broken backwards-compatibility
</h3>
198 Those of you who have already been twiddling around with the raw
199 HTML definition object, you'll be noticing that you're getting an error
200 when you attempt to retrieve the raw definition object without specifying
201 a DefinitionID. It is vital to caching (see below) that you make a unique
202 name for your customized definition, so make up something right now and
203 things will operate again.
206 <h2>Turn off caching
</h2>
209 To make development easier, we're going to temporarily turn off
213 <pre>$config = HTMLPurifier_Config::createDefault();
214 $config-
>set('HTML', 'DefinitionID', 'enduser-customize.html tutorial');
215 $config-
>set('HTML', 'DefinitionRev',
1);
216 <strong>$config-
>set('Cache', 'DefinitionImpl', null); // remove this later!
</strong>
217 $def = $config-
>getHTMLDefinition(true);
</pre>
220 A few things should be mentioned about the caching mechanism before
221 we move on. For performance reasons, HTML Purifier caches generated
222 <code>HTMLPurifier_Definition
</code> objects in serialized files
223 stored (by default) in
<code>library/HTMLPurifier/DefinitionCache/Serializer
</code>.
224 A lot of processing is done in order to create these objects, so it
225 makes little sense to repeat the same processing over and over again
226 whenever HTML Purifier is called.
230 In order to identify a cache entry, HTML Purifier uses three variables:
231 the library's version number, the value of %HTML.DefinitionRev and
232 a serial of relevant configuration. Whenever any of these changes,
233 a new HTML definition is generated. Notice that there is no way
234 for the definition object to track changes to customizations: here, it
235 is up to you to supply appropriate information to DefinitionID and
239 <h2 id=
"addAttribute">Add an attribute
</h2>
242 For this example, we're going to implement the
<code>target
</code> attribute found
243 on
<code>a
</code> elements. To implement an attribute, we have to
248 <li>What element is it found on?
</li>
249 <li>What is its name?
</li>
250 <li>Is it required or optional?
</li>
251 <li>What are valid values for it?
</li>
255 The first three are easy: the element is
<code>a
</code>, the attribute
256 is
<code>target
</code>, and it is not a required attribute. (If it
257 was required, we'd need to append an asterisk to the attribute name,
258 you'll see an example of this in the addElement() example).
262 The last question is a little trickier.
263 Lets allow the special values: _blank, _self, _target and _top.
264 The form of this is called an
<strong>enumeration
</strong>, a list of
265 valid values, although only one can be used at a time. To translate
266 this into code form, we write:
269 <pre>$config = HTMLPurifier_Config::createDefault();
270 $config-
>set('HTML', 'DefinitionID', 'enduser-customize.html tutorial');
271 $config-
>set('HTML', 'DefinitionRev',
1);
272 $config-
>set('Cache', 'DefinitionImpl', null); // remove this later!
273 $def = $config-
>getHTMLDefinition(true);
274 <strong>$def-
>addAttribute('a', 'target', 'Enum#_blank,_self,_target,_top');
</strong></pre>
277 The
<code>Enum#_blank,_self,_target,_top
</code> does all the magic.
278 The string is split into two parts, separated by a hash mark (#):
282 <li>The first part is the name of what we call an
<code>AttrDef
</code></li>
283 <li>The second part is the parameter of the above-mentioned
<code>AttrDef
</code></li>
287 If that sounds vague and generic, it's because it is! HTML Purifier defines
288 an assortment of different attribute types one can use, and each of these
289 has their own specialized parameter format. Here are some of the more useful
293 <table class=
"table">
304 <td><em>[s:]
</em>value1,value2,...
</td>
306 Attribute with a number of valid values, one of which may be used. When
307 s: is present, the enumeration is case sensitive.
312 <td>attribute_name
</td>
314 Boolean attribute, with only one valid value: the name
322 Attribute of arbitrary text. Can also be referred to as
<strong>Text
</strong>
323 (the specification makes a semantic distinction between the two).
330 Attribute that specifies a unique ID
337 Attribute that specifies an integer pixel length
344 Attribute that specifies a pixel or percentage length
351 Attribute that specifies a number of name tokens, example: the
352 <code>class
</code> attribute
359 Attribute that specifies a URI, example: the
<code>href
</code>
367 Attribute that specifies an positive integer number
374 For a complete list, consult
375 <a href=
"http://repo.or.cz/w/htmlpurifier.git?a=blob;hb=HEAD;f=library/HTMLPurifier/AttrTypes.php"><code>library/HTMLPurifier/AttrTypes.php
</code></a>;
376 more information on attributes that accept parameters can be found on their
377 respective includes in
378 <a href=
"http://repo.or.cz/w/htmlpurifier.git?a=tree;hb=HEAD;f=library/HTMLPurifier/AttrDef"><code>library/HTMLPurifier/AttrDef
</code></a>.
382 Sometimes, the restrictive list in AttrTypes just doesn't cut it. Don't
383 sweat: you can also use a fully instantiated object as the value. The
384 equivalent, verbose form of the above example is:
387 <pre>$config = HTMLPurifier_Config::createDefault();
388 $config-
>set('HTML', 'DefinitionID', 'enduser-customize.html tutorial');
389 $config-
>set('HTML', 'DefinitionRev',
1);
390 $config-
>set('Cache', 'DefinitionImpl', null); // remove this later!
391 $def = $config-
>getHTMLDefinition(true);
392 <strong>$def-
>addAttribute('a', 'target', new HTMLPurifier_AttrDef_Enum(
393 array('_blank','_self','_target','_top')
397 Trust me, you'll learn to love the shorthand.
400 <h2>Add an element
</h2>
403 Adding attributes is really small-fry stuff, though, and it was possible
404 to add them (albeit a bit more wordy) prior to
2.0. The real gem of
405 the Advanced API is adding elements. There are five questions to
406 ask when adding a new element:
410 <li>What is the element's name?
</li>
411 <li>What content set does this element belong to?
</li>
412 <li>What are the allowed children of this element?
</li>
413 <li>What attributes does the element allow that are general?
</li>
414 <li>What attributes does the element allow that are specific to this element?
</li>
418 It's a mouthful, and you'll be slightly lost if your not familiar with
419 the HTML specification, so let's explain them step by step.
425 The HTML specification defines two major content sets: Inline
426 and Block. Each of these
427 content sets contain a list of elements: Inline contains things like
428 <code>span
</code> and
<code>b
</code> while Block contains things like
429 <code>div
</code> and
<code>blockquote
</code>.
433 These content sets amount to a macro mechanism for HTML definition. Most
434 elements in HTML are organized into one of these two sets, and most
435 elements in HTML allow elements from one of these sets. If we had
436 to write each element verbatim into each other element's allowed
437 children, we would have ridiculously large lists; instead we use
438 content sets to compactify the declaration.
442 Practically speaking, there are several useful values you can use here:
445 <table class=
"table">
455 <td>Character level elements, text
</td>
459 <td>Block-like elements, like paragraphs and lists
</td>
462 <th><em>false
</em></th>
464 Any element that doesn't fit into the mold, for example
<code>li
</code>
472 By specifying a valid value here, all other elements that use that
473 content set will also allow your element, without you having to do
474 anything. If you specify
<em>false
</em>, you'll have to register
475 your element manually.
478 <h3>Allowed children
</h3>
481 Allowed children defines the elements that this element can contain.
482 The allowed values may range from none to a complex regexp depending on
487 If you've ever taken a look at the HTML DTD's before, you may have
488 noticed declarations like this:
491 <pre><!ELEMENT LI - O (%flow;)* -- list item --
></pre>
494 The
<code>(%flow;)*
</code> indicates the allowed children of the
495 <code>li
</code> tag:
<code>li
</code> allows any number of flow
496 elements as its children. (The
<code>- O
</code> allows the closing tag to be
497 omitted, though in XML this is not allowed.) In HTML Purifier,
498 we'd write it like
<code>Flow
</code> (here's where the content sets
499 we were discussing earlier come into play). There are three shorthand
500 content models you can specify:
503 <table class=
"table">
506 <th>Content model
</th>
513 <td>No children allowed, like
<code>br
</code> or
<code>hr
</code></td>
517 <td>Any number of inline elements and text, like
<code>span
</code></td>
521 <td>Any number of inline elements, block elements and text, like
<code>div
</code></td>
527 This covers
90% of all the cases out there, but what about elements that
528 break the mold like
<code>ul
</code>? This guy requires at least one
529 child, and the only valid children for it are
<code>li
</code>. The
530 content model is:
<code>Required: li
</code>. There are two parts: the
531 first type determines what
<code>ChildDef
</code> will be used to validate
532 content models. The most common values are:
535 <table class=
"table">
545 <td>Children must be one or more of the valid elements
</td>
549 <td>Children can be any number of the valid elements
</td>
553 <td>Children must follow the DTD-style regex
</td>
559 You can also implement your own
<code>ChildDef
</code>: this was done
560 for a few special cases in HTML Purifier such as
<code>Chameleon
</code>
561 (for
<code>ins
</code> and
<code>del
</code>),
<code>StrictBlockquote
</code>
562 and
<code>Table
</code>.
566 The second part specifies either valid elements or a regular expression.
567 Valid elements are separated with horizontal bars (|), i.e.
568 "<code>a | b | c</code>". Use #PCDATA to represent plain text.
569 Regular expressions are based off of DTD's style:
573 <li>Parentheses () are used for grouping
</li>
574 <li>Commas (,) separate elements that should come one after another
</li>
575 <li>Horizontal bars (|) indicate one or the other elements should be used
</li>
576 <li>Plus signs (+) are used for a one or more match
</li>
577 <li>Asterisks (*) are used for a zero or more match
</li>
578 <li>Question marks (?) are used for a zero or one match
</li>
582 For example,
"<code>a, b?, (c | d), e+, f*</code>" means
"In this order,
583 one <code>a</code> element, at most one <code>b</code> element,
584 one <code>c</code> or <code>d</code> element (but not both), one or more
585 <code>e</code> elements, and any number of <code>f</code> elements."
586 Regex veterans should be able to jump right in, and those not so savvy
587 can always copy-paste W3C's content model definitions into HTML Purifier
588 and hope for the best.
592 A word of warning: while the regex format is extremely flexible on
593 the developer's side, it is
594 quite unforgiving on the user's side. If the user input does not
<em>exactly
</em>
595 match the specification, the entire contents of the element will
596 be nuked. This is why there is are specific content model types like
597 Optional and Required: while they could be implemented as
<code>Custom:
598 (valid | elements)*
</code>, the custom classes contain special recovery
599 measures that make sure as much of the user's original content gets
600 through. HTML Purifier's core, as a rule, does not use Custom.
604 One final note: you can also use Content Sets inside your valid elements
605 lists or regular expressions. In fact, the three shorthand content models
606 mentioned above are just that: abbreviations:
609 <table class=
"table">
612 <th>Content model
</th>
613 <th>Implementation
</th>
619 <td>Optional: Inline | #PCDATA
</td>
623 <td>Optional: Flow | #PCDATA
</td>
629 When the definition is compiled, Inline will be replaced with a
630 horizontal-bar separated list of inline elements. Also, notice that
631 it does not contain text: you have to specify that yourself.
634 <h3>Common attributes
</h3>
637 Congratulations: you have just gotten over the proverbial hump (Allowed
638 children). Common attributes is much simpler, and boils down to
639 one question: does your element have the
<code>id
</code>,
<code>style
</code>,
640 <code>class
</code>,
<code>title
</code> and
<code>lang
</code> attributes?
641 If so, you'll want to specify the
<code>Common
</code> attribute collection,
642 which contains these five attributes that are found on almost every
643 HTML element in the specification.
647 There are a few more collections, but they're really edge cases:
650 <table class=
"table">
660 <td><code>lang
</code>, possibly
<code>xml:lang
</code></td>
664 <td><code>style
</code>,
<code>class
</code>,
<code>id
</code> and
<code>title
</code></td>
670 Common is a combination of the above-mentioned collections.
674 Readers familiar with the modularization may have noticed that the Core
675 attribute collection differs from that specified by the
<a
676 href=
"http://www.w3.org/TR/xhtml-modularization/abstract_modules.html#s_commonatts">abstract
677 modules of the XHTML Modularization
1.1</a>. We believe this section
678 to be in error, as
<code>br
</code> permits the use of the
<code>style
</code>
679 attribute even though it uses the
<code>Core
</code> collection, and
680 the DTD and XML Schemas supplied by W3C support our interpretation.
686 If you didn't read the
<a href=
"#addAttribute">earlier section on
687 adding attributes
</a>, read it now. The last parameter is simply
688 an array of attribute names to attribute implementations, in the exact
689 same format as
<code>addAttribute()
</code>.
692 <h3>Putting it all together
</h3>
695 We're going to implement
<code>form
</code>. Before we embark, lets
696 grab a reference implementation from over at the
697 <a href=
"http://www.w3.org/TR/html4/sgml/loosedtd.html">transitional DTD
</a>:
700 <pre><!ELEMENT FORM - - (%flow;)* -(FORM) -- interactive form --
>
702 %attrs; -- %coreattrs, %i18n, %events --
703 action %URI; #REQUIRED -- server-side form handler --
704 method (GET|POST) GET -- HTTP method used to submit the form--
705 enctype %ContentType;
"application/x-www-form-urlencoded
"
706 accept %ContentTypes; #IMPLIED -- list of MIME types for file upload --
707 name CDATA #IMPLIED -- name of form for scripting --
708 onsubmit %Script; #IMPLIED -- the form was submitted --
709 onreset %Script; #IMPLIED -- the form was reset --
710 target %FrameTarget; #IMPLIED -- render in this frame --
711 accept-charset %Charsets; #IMPLIED -- list of supported charsets --
715 Juicy! With just this, we can answer four of our five questions:
719 <li>What is the element's name?
<strong>form
</strong></li>
720 <li>What content set does this element belong to?
<strong>Block
</strong>
721 (this needs a little sleuthing, I find the easiest way is to search
722 the DTD for
<code>FORM
</code> and determine which set it is in.)
</li>
723 <li>What are the allowed children of this element?
<strong>One
724 or more flow elements, but no nested
<code>form
</code>s
</strong></li>
725 <li>What attributes does the element allow that are general?
<strong>Common
</strong></li>
726 <li>What attributes does the element allow that are specific to this element?
<strong>A whole bunch, see ATTLIST;
727 we're going to the vital ones:
<code>action
</code>,
<code>method
</code> and
<code>name
</code></strong></li>
734 <pre>$config = HTMLPurifier_Config::createDefault();
735 $config-
>set('HTML', 'DefinitionID', 'enduser-customize.html tutorial');
736 $config-
>set('HTML', 'DefinitionRev',
1);
737 $config-
>set('Cache', 'DefinitionImpl', null); // remove this later!
738 $def = $config-
>getHTMLDefinition(true);
739 $def-
>addAttribute('a', 'target', new HTMLPurifier_AttrDef_Enum(
740 array('_blank','_self','_target','_top')
742 <strong>$form = $def-
>addElement(
744 'Block', // content set
745 'Flow', // allowed children
746 'Common', // attribute collection
749 'method' =
> 'Enum#get|post',
753 $form-
>excludes = array('form' =
> true);
</strong></pre>
756 Each of the parameters corresponds to one of the questions we asked.
757 Notice that we added an asterisk to the end of the
<code>action
</code>
758 attribute to indicate that it is required. If someone specifies a
759 <code>form
</code> without that attribute, the tag will be axed.
760 Also, the extra line at the end is a special extra declaration that
761 prevents forms from being nested within each other.
765 And that's all there is to it! Implementing the rest of the form
766 module is left as an exercise to the user; to see more examples
767 check the
<a href=
"http://repo.or.cz/w/htmlpurifier.git?a=tree;hb=HEAD;f=library/HTMLPurifier/HTMLModule"><code>library/HTMLPurifier/HTMLModule/
</code></a> directory
768 in your local HTML Purifier installation.
771 <h2>And beyond...
</h2>
774 Perceptive users may have realized that, to a certain extent, we
775 have simply re-implemented the facilities of XML Schema or the
776 Document Type Definition. What you are seeing here, however, is
777 not just an XML Schema or Document Type Definition: it is a fully
778 expressive method of specifying the definition of HTML that is
779 a portable superset of the capabilities of the two above-mentioned schema
780 languages. What makes HTMLDefinition so powerful is the fact that
781 if we don't have an implementation for a content model or an attribute
782 definition, you can supply it yourself by writing a PHP class.
786 There are many facets of HTMLDefinition beyond the Advanced API I have
787 walked you through today. To find out more about these, you can
788 check out these source files:
792 <li><a href=
"http://repo.or.cz/w/htmlpurifier.git?a=blob;hb=HEAD;f=library/HTMLPurifier/HTMLModule.php"><code>library/HTMLPurifier/HTMLModule.php
</code></a></li>
793 <li><a href=
"http://repo.or.cz/w/htmlpurifier.git?a=blob;hb=HEAD;f=library/HTMLPurifier/ElementDef.php"><code>library/HTMLPurifier/ElementDef.php
</code></a></li>
798 <!-- vim: et sw=4 sts=4 -->