]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - extlib/htmLawed/htmLawed_README.txt
5e19605e5a1c7f0c1ba8cab40a7db44fe6674e08
[quix0rs-gnu-social.git] / extlib / htmLawed / htmLawed_README.txt
1 /*\r
2 htmLawed_README.txt, 29 August 2013\r
3 htmLawed 1.1.16, 29 August 2013\r
4 Copyright Santosh Patnaik\r
5 Dual licensed with LGPL 3 and GPL 2+\r
6 A PHP Labware internal utility - http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed\r
7 */\r
8 \r
9 \r
10 == Content ==========================================================\r
11 \r
12 \r
13 1  About htmLawed\r
14   1.1  Example uses\r
15   1.2  Features\r
16   1.3  History\r
17   1.4  License & copyright\r
18   1.5  Terms used here\r
19 2  Usage\r
20   2.1  Simple\r
21   2.2  Configuring htmLawed using the '$config' parameter\r
22   2.3  Extra HTML specifications using the '$spec' parameter\r
23   2.4  Performance time & memory usage\r
24   2.5  Some security risks to keep in mind\r
25   2.6  Use without modifying old 'kses()' code\r
26   2.7  Tolerance for ill-written HTML\r
27   2.8  Limitations & work-arounds\r
28   2.9  Examples of usage\r
29 3  Details\r
30   3.1  Invalid/dangerous characters\r
31   3.2  Character references/entities\r
32   3.3  HTML elements\r
33     3.3.1  HTML comments and 'CDATA' sections\r
34     3.3.2  Tag-transformation for better XHTML-Strict\r
35     3.3.3  Tag balancing and proper nesting\r
36     3.3.4  Elements requiring child elements\r
37     3.3.5  Beautify or compact HTML\r
38   3.4  Attributes\r
39     3.4.1  Auto-addition of XHTML-required attributes\r
40     3.4.2  Duplicate/invalid 'id' values\r
41     3.4.3  URL schemes (protocols) and scripts in attribute values\r
42     3.4.4  Absolute & relative URLs\r
43     3.4.5  Lower-cased, standard attribute values\r
44     3.4.6  Transformation of deprecated attributes\r
45     3.4.7  Anti-spam & 'href'\r
46     3.4.8  Inline style properties\r
47     3.4.9  Hook function for tag content\r
48   3.5  Simple configuration directive for most valid XHTML\r
49   3.6  Simple configuration directive for most `safe` HTML\r
50   3.7  Using a hook function\r
51   3.8  Obtaining `finalized` parameter values\r
52   3.9  Retaining non-HTML tags in input with mixed markup\r
53 4  Other\r
54   4.1  Support\r
55   4.2  Known issues\r
56   4.3  Change-log\r
57   4.4  Testing\r
58   4.5  Upgrade, & old versions\r
59   4.6  Comparison with 'HTMLPurifier'\r
60   4.7  Use through application plug-ins/modules\r
61   4.8  Use in non-PHP applications\r
62   4.9  Donate\r
63   4.10  Acknowledgements\r
64 5  Appendices\r
65   5.1  Characters discouraged in HTML\r
66   5.2  Valid attribute-element combinations\r
67   5.3  CSS 2.1 properties accepting URLs\r
68   5.4  Microsoft Windows 1252 character replacements\r
69   5.5  URL format\r
70   5.6  Brief on htmLawed code\r
71 \r
72 \r
73 == 1  About htmLawed ================================================\r
74 \r
75 \r
76   htmLawed is a PHP script to process text with HTML markup to make it more compliant with HTML standards and administrative policies. It works by making HTML well-formed with balanced and properly nested tags, neutralizing code that may be used for cross-site scripting (XSS) attacks, allowing only specified HTML tags and attributes, and so on. Such `lawing in` of HTML in text used in (X)HTML or XML documents ensures that it is in accordance with the aesthetics, safety and usability requirements set by administrators.\r
77   \r
78   htmLawed is highly customizable, and fast with low memory usage. Its free and open-source code is in one small file, does not require extensions or libraries, and works in older versions of PHP as well. It is a good alternative to the HTML Tidy:- http://tidy.sourceforge.net application.\r
79 \r
80 \r
81 -- 1.1  Example uses ------------------------------------------------\r
82 \r
83 \r
84   *  Filtering of text submitted as comments on blogs to allow only certain HTML elements\r
85 \r
86   *  Making RSS/Atom newsfeed item-content standard-compliant: often one uses an excerpt from an HTML document for the content, and with unbalanced tags, non-numerical entities, etc., such excerpts may not be XML-compliant\r
87 \r
88   *  Text processing for stricter XML standard-compliance: e.g., to have lowercased 'x' in hexadecimal numeric entities becomes necessary if an XHTML document with MathML content needs to be served as 'application/xml'\r
89 \r
90   *  Scraping text or data from web-pages\r
91 \r
92   *  Pretty-printing HTML code\r
93 \r
94 \r
95 -- 1.2  Features ---------------------------------------------------o\r
96 \r
97 \r
98   Key: '*' security feature, '^' standard compliance, '~' requires setting right options, '`' different from 'Kses'\r
99 \r
100   *  make input more *secure* and *standard-compliant*\r
101   *  use for HTML 4, XHTML 1.0 or 1.1, or even generic *XML* documents  ^~`\r
102 \r
103   *  *beautify* or *compact* HTML  ^~`\r
104 \r
105   *  can *restrict elements*  ^~`\r
106   *  ensures proper closure of empty elements like 'img'  ^`\r
107   *  *transform deprecated elements* like 'u'  ^~`\r
108   *  HTML *comments* and 'CDATA' sections can be permitted  ^~`\r
109   *  elements like 'script', 'object' and 'form' can be permitted  ~\r
110 \r
111   *  *restrict attributes*, including *element-specifically*  ^~`\r
112   *  remove *invalid attributes*  ^`\r
113   *  element and attribute names are *lower-cased*  ^\r
114   *  provide *required attributes*, like 'alt' for 'image'  ^`\r
115   *  *transforms deprecated attributes*  ^~`\r
116   *  attributes *declared only once*  ^`\r
117 \r
118   *  *restrict attribute values*, including *element-specifically*  ^~`\r
119   *  a value is declared for `empty` (`minimized`) attributes like 'checked'  ^\r
120   *  check for potentially dangerous attribute values  *~\r
121   *  ensure *unique* 'id' attribute values  ^~`\r
122   *  *double-quote* attribute values  ^\r
123   *  lower-case *standard attribute values* like 'password'  ^`\r
124   *  permit custom, non-standard attributes as well as custom rules for standard attributes  ~`\r
125 \r
126   *  *attribute-specific URL protocol/scheme restriction*  *~`\r
127   *  disable *dynamic expressions* in 'style' values  *~`\r
128 \r
129   *  neutralize invalid named character entities  ^`\r
130   *  *convert* hexadecimal numeric entities to decimal ones, or vice versa  ^~`\r
131   *  convert named entities to numeric ones for generic XML use  ^~`\r
132 \r
133   *  remove *null* characters  *\r
134   *  neutralize potentially dangerous proprietary Netscape *Javascript entities*  *\r
135   *  replace potentially dangerous *soft-hyphen* character in URL-accepting attribute values with spaces  *\r
136 \r
137   *  remove common *invalid characters* not allowed in HTML or XML  ^`\r
138   *  replace *characters from Microsoft applications* like 'Word' that are discouraged in HTML or XML  ^~`\r
139   *  neutralize entities for characters invalid or discouraged in HTML or XML  ^`\r
140   *  appropriately neutralize '<', '&', '"', and '>' characters  ^*`\r
141 \r
142   *  understands improperly spaced tag content (like, spread over more than a line) and properly spaces them  `\r
143   *  attempts to *balance tags* for well-formedness  ^~`\r
144   *  understands when *omitable closing tags* like '</p>' (allowed in HTML 4, transitional, e.g.) are missing  ^~`\r
145   *  attempts to permit only *validly nested tags*  ^~`\r
146   *  option to *remove or neutralize bad content* ^~`\r
147   *  attempts to *rectify common errors of plain-text misplacement* (e.g., directly inside 'blockquote') ^~`\r
148 \r
149   *  fast, *non-OOP* code of ~45 kb incurring peak basal memory usage of ~0.5 MB\r
150   *  *compatible* with pre-existing code using 'Kses' (the filter used by 'WordPress')\r
151 \r
152   *  optional *anti-spam* measures such as addition of 'rel="nofollow"' and link-disabling  ~`\r
153   *  optionally makes *relative URLs absolute*, and vice versa  ~`\r
154 \r
155   *  optionally mark '&' to identify the entities for '&', '<' and '>' introduced by htmLawed  ~`\r
156 \r
157   *  allows deployment of powerful *hook functions* to *inject* HTML, *consolidate* 'style' attributes to 'class', finely check attribute values, etc.  ~`\r
158 \r
159   *  *independent of character encoding* of input and does not affect it\r
160 \r
161   *  *tolerance for ill-written HTML* to a certain degree\r
162 \r
163 \r
164 -- 1.3  History ----------------------------------------------------o\r
165 \r
166 \r
167   htmLawed was created in 2007 for use with 'LabWiki', a wiki software developed at PHP Labware, as a suitable software could not be found. Existing PHP software like 'Kses' and 'HTMLPurifier' were deemed inadequate, slow, resource-intensive, or dependent on an extension or external application like 'HTML Tidy'. The core logic of htmLawed, that of identifying HTML elements and attributes, was based on the 'Kses' (version 0.2.2) HTML filter software of Ulf Harnhammar (it can still be used with code that uses 'Kses'; see section:- #2.6.).\r
168   \r
169   See section:- #4.3 for a detailed log of changes in htmLawed over the years, and section:- #4.10 for acknowledgements.\r
170 \r
171 \r
172 -- 1.4  License & copyright ----------------------------------------o\r
173 \r
174 \r
175   htmLawed is free and open-source software dual copyrighted by Santosh Patnaik, MD, PhD, and licensed under LGPL license version 3:- http://www.gnu.org/licenses/lgpl-3.0.txt, and GPL license version 2:- http://www.gnu.org/licenses/gpl-2.0.txt (or later).\r
176 \r
177 \r
178 -- 1.5  Terms used here --------------------------------------------o\r
179 \r
180 \r
181   In this document, only HTML body-level elements are considered. htmLawed does not have support for head-level elements, 'body', and the frame-level elements, 'frameset', 'frame' and 'noframes', and these elements are ignored here.\r
182 \r
183   *  `administrator` - or admin; person setting up the code that utilizes htmLawed; also, `user`\r
184   *  `attributes` - name-value pairs like 'href="http://x.com"' in opening tags\r
185   *  `author` - see `writer`\r
186   *  `character` - atomic unit of text; internally represented by a numeric `code-point` as specified by the `encoding` or `charset` in use\r
187   *  `entity` - markup like '&gt;' and '&#160;' used to refer to a character\r
188   *  `element` - HTML element like 'a' and 'img'\r
189   *  `element content` -  content between the opening and closing tags of an element, like 'click' of the '<a href="x">click</a>' element\r
190   *  `HTML` - implies XHTML unless specified otherwise\r
191   *  `HTML body` - Complete HTML documents typically have a `head` and a `body` container. Information in `head` specifies title of the document, etc., whereas that in the body informs what is to be displayed on a web-page; it is only the elements for `body`, except 'frames', 'frameset' and 'noframes' that htmLawed is concerned with\r
192   *  `input` - text given to htmLawed to process\r
193   *  `processing` - involves filtering, correction, etc., of input\r
194   *  `safe` - absence or reduction of certain characters and HTML elements and attributes in HTML of text that can otherwise potentially, and circumstantially, expose text readers to security vulnerabilities like cross-site scripting attacks (XSS)\r
195   *  `scheme` - a URL protocol like 'http' and 'ftp'\r
196   *  `specifications` - standard specifications, for HTML4, HTML5, Ruby, etc.\r
197   *  `style property` - terms like 'border' and 'height' for which declarations are made in values for the 'style' attribute of elements\r
198   *  `tag` - markers like '<a href="x">' and '</a>' delineating element content; the opening tag can contain attributes\r
199   *  `tag content` - consists of tag markers '<' and '>', element names like 'div', and possibly attributes\r
200   *  `user` - administrator\r
201   *  `writer` - end-user like a blog commenter providing the input that is to be processed; also, `author`\r
202 \r
203 \r
204 -- 1.6  Availability ------------------------------------------------o\r
205 \r
206 \r
207   htmLawed can be downloaded for free at its website:- http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed. Besides the 'htmLawed.php' file, the download has the htmLawed documentation (this document) in plain text:- htmLawed_README.txt and HTML:- htmLawed_README.htm formats, a script for testing:- htmLawedTest.php, and a text file for test-cases:- htmLawed_TESTCASE.txt. htmLawed is also available as a PHP class (OOP code) on its website.\r
208 \r
209 \r
210 == 2  Usage ========================================================oo\r
211 \r
212 \r
213   htmLawed works in PHP version 4.4 or higher. Either 'include()' the 'htmLawed.php' file, or copy-paste the entire code. To use with PHP 4.3, have the following code included:\r
214 \r
215     if(!function_exists('ctype_digit')){\r
216      function ctype_digit($var){\r
217       return ((int) $var == $var);\r
218      }\r
219     }\r
220 \r
221 \r
222 -- 2.1  Simple ------------------------------------------------------\r
223 \r
224 \r
225   The input text to be processed, '$text', is passed as an argument of type string; 'htmLawed()' returns the processed string:\r
226 \r
227     $processed = htmLawed($text);\r
228     \r
229   With the 'htmLawed class' (section:- #1.6), usage is:\r
230   \r
231     $processed = htmLawed::hl($text);\r
232 \r
233   *Notes*: (1) If input is from a '$_GET' or '$_POST' value, and 'magic quotes' are enabled on the PHP setup, run 'stripslashes()' on the input before passing to htmLawed. (2) htmLawed does not have support for head-level elements, 'body', and the frame-level elements, 'frameset', 'frame' and 'noframes'.\r
234 \r
235   By default, htmLawed will process the text allowing all valid HTML elements/tags, secure URL scheme/CSS style properties, etc. It will allow 'CDATA' sections and HTML comments, balance tags, and ensure proper nesting of elements. Such actions can be configured using two other optional arguments -- '$config' and '$spec':\r
236 \r
237     $processed = htmLawed($text, $config, $spec); \r
238 \r
239   The '$config' and '$spec' arguments are detailed below. Some examples are shown in section:- #2.9. For maximum protection against 'XSS' and other scripting attacks (e.g., by disallowing Javascript code), consider using the 'safe' parameter; see section:- #3.6.\r
240 \r
241 \r
242 -- 2.2  Configuring htmLawed using the '$config' parameter ---------o\r
243 \r
244 \r
245   '$config' instructs htmLawed on how to tackle certain tasks. When '$config' is not specified, or not set as an array (e.g., '$config = 1'), htmLawed will take default actions. One or many of the task-action or value-specification pairs can be specified in '$config' as array key-value pairs. If a parameter is not specified, htmLawed will use the default value/action indicated further below.\r
246 \r
247     $config = array('comment'=>0, 'cdata'=>1);\r
248     $processed = htmLawed($text, $config);\r
249 \r
250   Or,\r
251 \r
252     $processed = htmLawed($text, array('comment'=>0, 'cdata'=>1));\r
253 \r
254   Below are the possible value-specification combinations. In PHP code, values that are integers should not be quoted and should be used as numeric types (unless meant as string/text).\r
255 \r
256   Key: '*' default, '^' different default when htmLawed is used in the Kses-compatible mode (see section:- #2.6), '~' different default when 'valid_xhtml' is set to '1' (see section:- #3.5), '"' different default when 'safe' is set to '1' (see section:- #3.6)\r
257 \r
258   *abs_url*\r
259   Make URLs absolute or relative; '$config["base_url"]' needs to be set; see section:- #3.4.4\r
260 \r
261   '-1' - make relative\r
262   '0' - no action  *\r
263   '1' - make absolute\r
264 \r
265   *and_mark*\r
266   Mark '&' characters in the original input; see section:- #3.2\r
267 \r
268   *anti_link_spam*\r
269   Anti-link-spam measure; see section:- #3.4.7\r
270       \r
271   '0' - no measure taken  *\r
272   `array("regex1", "regex2")` - will ensure a 'rel' attribute with 'nofollow' in its value in case the 'href' attribute value matches the regular expression pattern 'regex1', and/or will remove 'href' if its value matches the regular expression pattern 'regex2'. E.g., 'array("/./", "/://\W*(?!(abc\.com|xyz\.org))/")'; see section:- #3.4.7 for more.\r
273 \r
274   *anti_mail_spam*\r
275   Anti-mail-spam measure; see section:- #3.4.7\r
276 \r
277   '0' - no measure taken  *\r
278   `word` - '@' in mail address in 'href' attribute value is replaced with specified `word`\r
279 \r
280   *balance*\r
281   Balance tags for well-formedness and proper nesting; see section:- #3.3.3\r
282 \r
283   '0' - no\r
284   '1' - yes  *\r
285 \r
286   *base_url*\r
287   Base URL value that needs to be set if '$config["abs_url"]' is not '0'; see section:- #3.4.4\r
288 \r
289   *cdata*\r
290   Handling of 'CDATA' sections; see section:- #3.3.1\r
291 \r
292   '0' - don't consider 'CDATA' sections as markup and proceed as if plain text  ^"\r
293   '1' - remove\r
294   '2' - allow, but neutralize any '<', '>', and '&' inside by converting them to named entities\r
295   '3' - allow  *\r
296 \r
297   *clean_ms_char*\r
298   Replace discouraged characters introduced by Microsoft Word, etc.; see section:- #3.1\r
299 \r
300   '0' - no  *\r
301   '1' - yes\r
302   '2' - yes, but replace special single & double quotes with ordinary ones\r
303 \r
304   *comment*\r
305   Handling of HTML comments; see section:- #3.3.1\r
306 \r
307   '0' - don't consider comments as markup and proceed as if plain text  ^"\r
308   '1' - remove\r
309   '2' - allow, but neutralize any '<', '>', and '&' inside by converting to named entities\r
310   '3' - allow  *\r
311 \r
312   *css_expression*\r
313   Allow dynamic CSS expression by not removing the expression from CSS property values in 'style' attributes; see section:- #3.4.8\r
314 \r
315   '0' - remove  *\r
316   '1' - allow\r
317 \r
318   *deny_attribute*\r
319   Denied HTML attributes; see section:- #3.4\r
320 \r
321   '0' - none  *\r
322   `string` - dictated by values in `string`\r
323   'on*' (like 'onfocus') attributes not allowed - "\r
324   \r
325   *direct_nest_list*\r
326   Allow direct nesting of a list within another without requiring it to be a list item; see section:- #3.3.4\r
327 \r
328   '0' - no  *\r
329   '1' - yes\r
330 \r
331   *elements*\r
332   Allowed HTML elements; see section:- #3.3\r
333 \r
334   '* -center -dir -font -isindex -menu -s -strike -u' -  ~\r
335   'applet, embed, iframe, object, script' not allowed - "\r
336 \r
337   *hexdec_entity*\r
338   Allow hexadecimal numeric entities and do not convert to the more widely accepted decimal ones, or convert decimal to hexadecimal ones; see section:- #3.2\r
339 \r
340   '0' - no\r
341   '1' - yes  *\r
342   '2' - convert decimal to hexadecimal ones\r
343 \r
344   *hook*\r
345   Name of an optional hook function to alter the input string, '$config' or '$spec' before htmLawed starts its main work; see section:- #3.7\r
346 \r
347   '0' - no hook function  *\r
348   `name` - `name` is name of the hook function ('kses_hook'  ^)\r
349 \r
350   *hook_tag*\r
351   Name of an optional hook function to alter tag content finalized by htmLawed; see section:- #3.4.9\r
352 \r
353   '0' - no hook function  *\r
354   `name` - `name` is name of the hook function\r
355 \r
356   *keep_bad*\r
357   Neutralize bad tags by converting '<' and '>' to entities, or remove them; see section:- #3.3.3\r
358 \r
359   '0' - remove  ^\r
360   '1' - neutralize both tags and element content\r
361   '2' - remove tags but neutralize element content\r
362   '3' and '4' - like '1' and '2' but remove if text ('pcdata') is invalid in parent element\r
363   '5' and '6' * -  like '3' and '4' but line-breaks, tabs and spaces are left\r
364 \r
365   *lc_std_val*\r
366   For XHTML compliance, predefined, standard attribute values, like 'get' for the 'method' attribute of 'form', must be lowercased; see section:- #3.4.5\r
367 \r
368   '0' - no\r
369   '1' - yes  *\r
370 \r
371   *make_tag_strict*\r
372   Transform/remove these non-strict XHTML elements, even if they are allowed by the admin: 'applet' 'center' 'dir' 'embed' 'font' 'isindex' 'menu' 's' 'strike' 'u'; see section:- #3.3.2\r
373 \r
374   '0' - no  ^\r
375   '1' - yes, but leave 'applet', 'embed' and 'isindex' elements that currently can't be transformed  *\r
376   '2' - yes, removing 'applet', 'embed' and 'isindex' elements and their contents (nested elements remain)  ~\r
377 \r
378   *named_entity*\r
379   Allow non-universal named HTML entities, or convert to numeric ones; see section:- #3.2\r
380 \r
381   '0' - convert\r
382   '1' - allow  *\r
383 \r
384   *no_deprecated_attr*\r
385   Allow deprecated attributes or transform them; see section:- #3.4.6\r
386 \r
387   '0' - allow  ^\r
388   '1' - transform, but 'name' attributes for 'a' and 'map' are retained  *\r
389   '2' - transform\r
390 \r
391   *parent*\r
392   Name of the parent element, possibly imagined, that will hold the input; see section:- #3.3\r
393 \r
394   *safe*\r
395   Magic parameter to make input the most secure against XSS without needing to specify other relevant '$config' parameters; see section:- #3.6\r
396 \r
397   '0' - no  *\r
398   '1' - will auto-adjust other relevant '$config' parameters (indicated by '"' in this list)\r
399 \r
400   *schemes*\r
401   Array of attribute-specific, comma-separated, lower-cased list of schemes (protocols) allowed in attributes accepting URLs (or '!' to `deny` any URL); '*' covers all unspecified attributes; see section:- #3.4.3\r
402 \r
403   'href: aim, feed, file, ftp, gopher, http, https, irc, mailto, news, nntp, sftp, ssh, telnet; *:file, http, https'  *\r
404   '*: ftp, gopher, http, https, mailto, news, nntp, telnet'  ^\r
405   'href: aim, feed, file, ftp, gopher, http, https, irc, mailto, news, nntp, sftp, ssh, telnet; style: !; *:file, http, https'  "\r
406 \r
407   *show_setting*\r
408   Name of a PHP variable to assign the `finalized` '$config' and '$spec' values; see section:- #3.8\r
409 \r
410   *style_pass*\r
411   Do not look at 'style' attribute values, letting them through without any alteration\r
412 \r
413   '0' - no *\r
414   '1' - htmLawed will let through any 'style' value; see section:- #3.4.8\r
415 \r
416   *tidy*\r
417   Beautify or compact HTML code; see section:- #3.3.5\r
418 \r
419   '-1' - compact\r
420   '0' - no  *\r
421   '1' or 'string' - beautify (custom format specified by 'string')\r
422 \r
423   *unique_ids*\r
424   'id' attribute value checks; see section:- #3.4.2\r
425 \r
426   '0' - no  ^\r
427   '1' - remove duplicate and/or invalid ones  *\r
428   `word` - remove invalid ones and replace duplicate ones with new and unique ones based on the `word`; the admin-specified `word`, like 'my_', should begin with a letter (a-z) and can contain letters, digits, '.', '_', '-', and ':'.\r
429 \r
430   *valid_xhtml*\r
431   Magic parameter to make input the most valid XHTML without needing to specify other relevant '$config' parameters; see section:- #3.5\r
432 \r
433   '0' - no  *\r
434   '1' - will auto-adjust other relevant '$config' parameters (indicated by '~' in this list)\r
435 \r
436   *xml:lang*\r
437   Auto-adding 'xml:lang' attribute; see section:- #3.4.1\r
438 \r
439   '0' - no  *\r
440   '1' - add if 'lang' attribute is present\r
441   '2' - add if 'lang' attribute is present, and remove 'lang'  ~\r
442 \r
443 \r
444 -- 2.3  Extra HTML specifications using the $spec parameter --------o\r
445 \r
446 \r
447   The '$spec' argument of htmLawed can be used to disallow an otherwise legal attribute for an element, or to restrict the attribute's values. This can also be helpful as a security measure (e.g., in certain versions of browsers, certain values can cause buffer overflows and denial of service attacks), or in enforcing admin policies. '$spec' is specified as a string of text containing one or more `rules`, with multiple rules separated from each other by a semi-colon (';'). E.g.,\r
448 \r
449     $spec = 'i=-*; td, tr=style, id, -*; a=id(match="/[a-z][a-z\d.:\-`"]*/i"/minval=2), href(maxlen=100/minlen=34); img=-width,-alt';\r
450     $processed = htmLawed($text, $config, $spec);\r
451 \r
452   Or,\r
453 \r
454     $processed = htmLawed($text, $config, 'i=-*; td, tr=style, id, -*; a=id(match="/[a-z][a-z\d.:\-`"]*/i"/minval=2), href(maxlen=100/minlen=34); img=-width,-alt');\r
455 \r
456   A rule begins with an HTML *element* name(s) (`rule-element`), for which the rule applies, followed by an equal ('=') sign. A rule-element may represent multiple elements if comma (,)-separated element names are used. E.g., 'th,td,tr='.\r
457 \r
458   Rest of the rule consists of comma-separated HTML *attribute names*. A minus ('-') character before an attribute means that the attribute is not permitted inside the rule-element. E.g., '-width'. To deny all attributes, '-*' can be used.\r
459 \r
460   Following shows examples of rule excerpts with rule-element 'a' and the attributes that are being permitted:\r
461 \r
462   *  'a=' - all\r
463   *  'a=id' - all\r
464   *  'a=href, title, -id, -onclick' - all except 'id' and 'onclick'\r
465   *  'a=*, id, -id' - all except 'id'\r
466   *  'a=-*' - none\r
467   *  'a=-*, href, title' - none except 'href' and 'title'\r
468   *  'a=-*, -id, href, title' - none except 'href' and 'title'\r
469 \r
470   Rules regarding *attribute values* are optionally specified inside round brackets after attribute names in slash ('/')-separated `parameter = value` pairs. E.g., 'title(maxlen=30/minlen=5)'. None or one or more of the following parameters may be specified:\r
471 \r
472   *  'oneof' - one or more choices separated by '|' that the value should match; if only one choice is provided, then the value must match that choice\r
473 \r
474   *  'noneof' - one or more choices separated by '|' that the value should not match\r
475 \r
476   *  'maxlen' and 'minlen' - upper and lower limits for the number of characters in the attribute value; specified in numbers\r
477 \r
478   *  'maxval' and 'minval' - upper and lower limits for the numerical value specified in the attribute value; specified in numbers\r
479 \r
480   *  'match' and 'nomatch' - pattern that the attribute value should or should not match; specified as PHP/PCRE-compatible regular expressions with delimiters and possibly modifiers\r
481 \r
482   *  'default' - a value to force on the attribute if the value provided by the writer does not fit any of the specified parameters\r
483 \r
484   If 'default' is not set and the attribute value does not satisfy any of the specified parameters, then the attribute is removed. The 'default' value can also be used to force all attribute declarations to take the same value (by getting the values declared illegal by setting, e.g., 'maxlen' to '-1').\r
485 \r
486   Examples with `input` '<input title="WIDTH" value="10em" /><input title="length" value="5" />' are shown below.\r
487 \r
488   `Rule`: 'input=title(maxlen=60/minlen=6), value'\r
489   `Output`: '<input value="10em" /><input title="length" value="5" />'\r
490 \r
491   `Rule`: 'input=title(), value(maxval=8/default=6)'\r
492   `Output`: '<input title="WIDTH" value="6" /><input title="length" value="5" />'\r
493 \r
494   `Rule`: 'input=title(nomatch=%w.d%i), value(match=%em%/default=6em)'\r
495   `Output`: '<input value="10em" /><input title="length" value="6em" />'\r
496 \r
497   `Rule`: 'input=title(oneof=height|depth/default=depth), value(noneof=5|6)'\r
498   `Output`: '<input title="depth" value="10em" /><input title="depth" />'\r
499 \r
500   *Special characters*: The characters ';', ',', '/', '(', ')', '|', '~' and space have special meanings in the rules. Words in the rules that use such characters, or the characters themselves, should be `escaped` by enclosing in pairs of double-quotes ('"'). A back-tick ('`') can be used to escape a literal '"'. An example rule illustrating this is 'input=value(maxlen=30/match="/^\w/"/default="your `"ID`"")'.\r
501    \r
502   *Note*: To deny an attribute for all elements for which it is legal, '$config["deny_attribute"]' (see section:- #3.4) can be used instead of '$spec'. Also, attributes can be allowed element-specifically through '$spec' while being denied globally through '$config["deny_attribute"]'. The 'hook_tag' parameter (section:- #3.4.9) can also be possibly used to implement a functionality like that achieved using '$spec' functionality.\r
503   \r
504   '$spec' can also be used to permit custom, non-standard attributes as well as custom rules for standard attributes. Thus, the following value of '$spec' will permit the custom uses of the standard 'rel' attribute in 'input' (not permitted as per standards) and of a non-standard attribute, 'vFlag', in 'img'.\r
505   \r
506     $spec = 'img=vFlag; input=rel'\r
507 \r
508   The attribute names can contain alphabets, colons (:) and hyphens (-), but they must start with an alphabet.\r
509 \r
510 \r
511 -- 2.4  Performance time & memory usage ----------------------------o\r
512 \r
513 \r
514   The time and memory consumed during text processing by htmLawed depends on its configuration, the size of the input, and the amount, nestedness and well-formedness of the HTML markup within the input. In particular, tag balancing and beautification each can increase the processing time by about a quarter.\r
515 \r
516   The htmLawed demo:- htmLawedTest.php can be used to evaluate the performance and effects of different types of input and '$config'.\r
517 \r
518 \r
519 -- 2.5  Some security risks to keep in mind ------------------------o\r
520 \r
521 \r
522   When setting the parameters/arguments (like those to allow certain HTML elements) for use with htmLawed, one should bear in mind that the setting may let through potentially `dangerous` HTML code which is meant to steal user-data, deface a website, render a page non-functional, etc. Unless end-users, either people or software, supplying the content are completely trusted, security issues arising from the degree of HTML usage permitted through htmLawed's setting should be considered. For example, following increase security risks:\r
523 \r
524   *  Allowing 'script', 'applet', 'embed', 'iframe' or 'object' elements, or certain of their attributes like 'allowscriptaccess'\r
525 \r
526   *  Allowing HTML comments (some Internet Explorer versions are vulnerable with, e.g., '<!--[if gte IE 4]><script>alert("xss");</script><![endif]-->'\r
527   \r
528   *  Allowing dynamic CSS expressions (some Internet Explorer versions are vulnerable)\r
529   \r
530   *  Allowing the 'style' attribute\r
531 \r
532   To remove `unsecure` HTML, code-developers using htmLawed must set '$config' appropriately. E.g., '$config["elements"] = "* -script"' to deny the 'script' element (section:- #3.3), '$config["safe"] = 1' to auto-configure ceratin htmLawed parameters for maximizing security (section:- #3.6), etc. \r
533   \r
534   Permitting the '*style*' attribute brings in risks of `click-jacking`, `phishing`, web-page overlays, etc., `even` when the 'safe' parameter is enabled (see section:- #3.6). Except for URLs and a few other things like CSS dynamic expressions, htmLawed currently does not check every CSS style property. It does provide ways for the code-developer implementing htmLawed to do such checks through htmLawed's '$spec' argument, and through the 'hook_tag' parameter (see section:- #3.4.8 for more). Disallowing 'style' completely and relying on CSS classes and stylesheet files is recommended.\r
535   \r
536   htmLawed does not check or correct the character *encoding* of the input it receives. In conjunction with permissive circumstances, such as when the character encoding is left undefined through HTTP headers or HTML 'meta' tags, this can allow for an exploit (like Google's `UTF-7/XSS` vulnerability of the past).\r
537 \r
538 \r
539 -- 2.6  Use without modifying old 'kses()' code --------------------o\r
540 \r
541 \r
542   The 'Kses' PHP script is used by many applications (like 'WordPress'). It is possible to have such applications use htmLawed instead, since it is compatible with code that calls the 'kses()' function declared in the 'Kses' file (usually named 'kses.php'). E.g., application code like this will continue to work after replacing 'Kses' with htmLawed:\r
543 \r
544     $comment_filtered = kses($comment_input, array('a'=>array(), 'b'=>array(), 'i'=>array()));\r
545 \r
546   For some of the '$config' parameters, htmLawed will use values other than the default ones. These are indicated by '^' in section:- #2.2. To force htmLawed to use other values, function 'kses()' in the htmLawed code should be edited -- a few configurable parameters/variables need to be changed.\r
547 \r
548   If the application uses a 'Kses' file that has the 'kses()' function declared, then, to have the application use htmLawed instead of 'Kses', simply rename 'htmLawed.php' (to 'kses.php', e.g.) and replace the 'Kses' file (or just replace the code in the 'Kses' file with the htmLawed code). If the 'kses()' function in the 'Kses' file had been renamed by the application developer (e.g., in 'WordPress', it is named 'wp_kses()'), then appropriately rename the 'kses()' function in the htmLawed code.\r
549 \r
550   If the 'Kses' file used by the application has been highly altered by the application developers, then one may need a different approach. E.g., with 'WordPress', it is best to copy the htmLawed code to 'wp_includes/kses.php', rename the newly added function 'kses()' to 'wp_kses()', and delete the code for the original 'wp_kses()' function.\r
551 \r
552   If the 'Kses' code has a non-empty hook function (e.g., 'wp_kses_hook()' in case of 'WordPress'), then the code for htmLawed's 'kses_hook()' function should be appropriately edited. However, the requirement of the hook function should be re-evaluated considering that htmLawed has extra capabilities. With 'WordPress', the hook function is an essential one. The following code is suggested for the htmLawed 'kses_hook()' in case of 'WordPress':\r
553 \r
554     function kses_hook($string, &$cf, &$spec){\r
555     // kses compatibility\r
556     $allowed_html = $spec;\r
557     $allowed_protocols = array();\r
558     foreach($cf['schemes'] as $v){\r
559      foreach($v as $k2=>$v2){\r
560       if(!in_array($k2, $allowed_protocols)){\r
561        $allowed_protocols[] = $k2;\r
562       }\r
563      }\r
564     }\r
565     return wp_kses_hook($string, $allowed_html, $allowed_protocols);\r
566     // eof\r
567     }\r
568 \r
569 \r
570 -- 2.7  Tolerance for ill-written HTML -----------------------------o\r
571 \r
572 \r
573   htmLawed can work with ill-written HTML code in the input. However, HTML that is too ill-written may not be `read` as HTML, and may therefore get identified as mere plain text. Following statements indicate the degree of `looseness` that htmLawed can work with, and can be provided in instructions to writers:\r
574 \r
575   *  Tags must be flanked by '<' and '>' with no '>' inside -- any needed '>' should be put in as '&gt;'. It is possible for tag content (element name and attributes) to be spread over many lines instead of being on one. A space may be present between the tag content and '>', like '<div >' and '<img / >', but not after the '<'.\r
576 \r
577   *  Element and attribute names need not be lower-cased.\r
578 \r
579   *  Attribute string of elements may be liberally spaced with tabs, line-breaks, etc.\r
580 \r
581   *  Attribute values may be single- and not double-quoted.\r
582 \r
583   *  Left-padding of numeric entities (like, '&#0160;', '&x07ff;') with '0' is okay as long as the number of characters between between the '&' and the ';' does not exceed 8. All entities must end with ';' though. \r
584 \r
585   *  Named character entities must be properly cased. Thus, '&Lt;' or '&TILDE;' will not be recognized as entities and will be `neutralized`.\r
586 \r
587   *  HTML comments should not be inside element tags (they can be between tags), and should begin with '<!--' and end with '-->'. Characters like '<', '>', and '&' may be allowed inside depending on '$config', but any '-->' inside should be put in as '--&gt;'. Any '--' inside will be automatically converted to '-', and a space will be added before the comment delimiter '-->'.\r
588 \r
589   *  'CDATA' sections should not be inside element tags, and can be in element content only if plain text is allowed for that element. They should begin with '<[CDATA[' and end with ']]>'. Characters like '<', '>', and '&' may be allowed inside depending on '$config', but any ']]>' inside should be put in as ']]&gt;'.\r
590 \r
591   *  For attribute values, character entities '&lt;', '&gt;' and '&amp;' should be used instead of characters '<' and '>', and '&' (when '&' is not part of a character entity). This applies even for Javascript code in values of attributes like 'onclick'.\r
592 \r
593   *  Characters '<', '>', '&' and '"' that are part of actual Javascript, etc., code in 'script' elements should be used as such and not be put in as entities like '&gt;'. Otherwise, though the HTML will be valid, the code may fail to work. Further, if such characters have to be used, then they should be put inside 'CDATA' sections.\r
594 \r
595   *  Simple instructions like "an opening tag cannot be present between two closing tags" and "nested elements should be closed in the reverse order of how they were opened" can help authors write balanced HTML. If tags are imbalanced, htmLawed will try to balance them, but in the process, depending on '$config["keep_bad"]', some code/text may be lost.\r
596 \r
597   *  Input authors should be notified of admin-specified allowed elements, attributes, configuration values (like conversion of named entities to numeric ones), etc.\r
598 \r
599   *  With '$config["unique_ids"]' not '0' and the 'id' attribute being permitted, writers should carefully avoid using duplicate or invalid 'id' values as even though htmLawed will correct/remove the values, the final output may not be the one desired. E.g., when '<a id="home"></a><input id="home" /><label for="home"></label>' is processed into \r
600 '<a id="home"></a><input id="prefix_home" /><label for="home"></label>'.\r
601 \r
602   *  Even if intended HTML is lost from an ill-written input, the processed output will be more secure and standard-compliant.\r
603 \r
604   *  For URLs, unless '$config["scheme"]' is appropriately set, writers should avoid using escape characters or entities in schemes. E.g., 'htt&#112;' (which many browsers will read as the harmless 'http') may be considered bad by htmLawed.\r
605 \r
606   *  htmLawed will attempt to put plain text present directly inside 'blockquote', 'form', 'map' and 'noscript' elements (illegal as per the specifications) inside auto-generated 'div' elements.\r
607 \r
608 \r
609 -- 2.8  Limitations & work-arounds ---------------------------------o\r
610 \r
611 \r
612   htmLawed's main objective is to make the input text `more` standard-compliant, secure for readers, and free of HTML elements and attributes considered undesirable by the administrator. Some of its current limitations, regardless of this objective, are noted below along with work-arounds.\r
613 \r
614   It should be borne in mind that no browser application is 100% standard-compliant, and that some of the standard specifications (like asking for normalization of white-spacing within 'textarea' elements) are clearly wrong. Regarding security, note that `unsafe` HTML code is not legally invalid per se.\r
615 \r
616   *  htmLawed is meant for input that goes into the 'body' of HTML documents. HTML's head-level elements are not supported, nor are the frameset elements 'frameset', 'frame' and 'noframes'. Content of the latter elements can, however, be individually filtered through htmLawed.\r
617 \r
618   *  It cannot transform the non-standard 'embed' elements to the standard-compliant 'object' elements. Yet, it can allow 'embed' elements if permitted ('embed' is widely used and supported). Admins can certainly use the 'hook_tag' parameter (section:- #3.4.9) to deploy a custom embed-to-object converter function.\r
619 \r
620   *  The only non-standard element that may be permitted is 'embed'; others like 'noembed' and 'nobr' cannot be permitted without modifying the htmLawed code.\r
621 \r
622   *  It cannot handle input that has non-HTML code like 'SVG' and 'MathML'. One way around is to break the input into pieces and passing only those without non-HTML code to htmLawed. Another is described in section:- #3.9. A third way may be to some how take advantage of the '$config["and_mark"]' parameter (see section:- #3.2).\r
623 \r
624   *  By default, htmLawed won't check many attribute values for standard compliance. E.g., 'width="20m"' with the dimension in non-standard 'm' is let through. Implementing universal and strict attribute value checks can make htmLawed slow and resource-intensive. Admins should look at the 'hook_tag' parameter (section:- #3.4.9) or '$spec' to enforce finer checks.\r
625 \r
626   *  The attributes, deprecated (which can be transformed too) or not, that it supports are largely those that are in the specifications. Only a few of the proprietary attributes are supported.\r
627 \r
628   *  Except for contained URLs and dynamic expressions (also optional), htmLawed does not check CSS style property values. Admins should look at using the 'hook_tag' parameter (section:- #3.4.9) or '$spec' for finer checks. Perhaps the best option is to disallow 'style' but allow 'class' attributes with the right 'oneof' or 'match' values for 'class', and have the various class style properties in '.css' CSS stylesheet files.\r
629 \r
630   *  htmLawed does not parse emoticons, decode `BBcode`, or `wikify`, auto-converting text to proper HTML. Similarly, it won't convert line-breaks to 'br' elements. Such functions are beyond its purview. Admins should use other code to pre- or post-process the input for such purposes.\r
631 \r
632   *  htmLawed cannot be used to have links force-opened in new windows (by auto-adding appropriate 'target' and 'onclick' attributes to 'a'). Admins should look at Javascript-based DOM-modifying solutions for this. Admins may also be able to use a custom hook function to enforce such checks ('hook_tag' parameter; see section:- #3.4.9).\r
633 \r
634   *  Nesting-based checks are not possible. E.g., one cannot disallow 'p' elements specifically inside 'td' while permitting it elsewhere. Admins may be able to use a custom hook function to enforce such checks ('hook_tag' parameter; see section:- #3.4.9).\r
635 \r
636   *  Except for optionally converting absolute or relative URLs to the other type, htmLawed will not alter URLs (e.g., to change the value of query strings or to convert 'http' to 'https'. Having absolute URLs may be a standard-requirement, e.g., when HTML is embedded in email messages, whereas altering URLs for other purposes is beyond htmLawed's goals. Admins may be able to use a custom hook function to enforce such checks ('hook_tag' parameter; see section:- #3.4.9).\r
637 \r
638   *  Pairs of opening and closing tags that do not enclose any content (like '<em></em>') are not removed. This may be against the standard specifications for certain elements (e.g., 'table'). However, presence of such standard-incompliant code will not break the display or layout of content. Admins can also use simple regex-based code to filter out such code.\r
639 \r
640   *  htmLawed does not check for certain element orderings described in the standard specifications (e.g., in a 'table', 'tbody' is allowed before 'tfoot'). Admins may be able to use a custom hook function to enforce such checks ('hook_tag' parameter; see section:- #3.4.9).\r
641 \r
642   *  htmLawed does not check the number of nested elements. E.g., it will allow two 'caption' elements in a 'table' element, illegal as per the specifications. Admins may be able to use a custom hook function to enforce such checks ('hook_tag' parameter; see section:- #3.4.9).\r
643 \r
644   *  htmLawed might convert certain entities to actual characters and remove backslashes and CSS comment-markers ('/*') in 'style' attribute values in order to detect malicious HTML like crafted IE-specific dynamic expressions like '&#101;xpression...'. If this is too harsh, admins can allow CSS expressions through htmLawed core but then use a custom function through the 'hook_tag' parameter (section:- #3.4.9) to more specifically identify CSS expressions in the 'style' attribute values. Also, using '$config["style_pass"]', it is possible to have htmLawed pass 'style' attribute values without even looking at them (section:- #3.4.8).\r
645 \r
646   *  htmLawed does not correct certain possible attribute-based security vulnerabilities (e.g., '<a href="http://x%22+style=%22background-image:xss">x</a>'). These arise when browsers mis-identify markup in `escaped` text, defeating the very purpose of escaping text (a bad browser will read the given example as '<a href="http://x" style="background-image:xss">x</a>').\r
647   \r
648   *  Because of poor Unicode support in PHP, htmLawed does not remove the `high value` HTML-invalid characters with multi-byte code-points. Such characters however are extremely unlikely to be in the input. (see section:- #3.1).\r
649   \r
650   *  htmLawed does not check or correct the character encoding of the input it receives. In conjunction with permitting circumstances such as when the character encoding is left undefined through HTTP headers or HTML 'meta' tags, this can permit an exploit (like Google's `UTF-7/XSS` vulnerability of the past). Also, htmLawed can mangle input text if it is not well-formed in terms of character encoding. Administrators can consider using code available elsewhere to check well-formedness of input text characters to correct any defect.\r
651   \r
652   *  htmLawed is expected to work with input texts in ASCII-compatible single byte encodings such as national variants of ASCII (like ISO-646-DE/German of the ISO 646 standard), extended ASCII variants (like ISO 8859-10/Turkish of the ISO 8859/ISO Latin standard), ISO 8859-based Windows variants (like Windows 1252), EBCDIC, Shift JIS (Japanese), GB-Roman (Chinese), and KS-Roman (Korean). It should also properly handle texts with variable byte encodings like UTF-7 (Unicode) and UTF-8 (Unicode). However, htmLawed may mangle input texts with double byte encodings like UTF-16 (Unicode), JIS X 0208:1997 (Japanese) and K SX 1001:1992 (Korean), or the UTF-32 (Unicode) quadruple byte encoding. If an input text has such an encoding, administrators can use PHP's iconv:- http://php.net/manual/en/book.iconv.php functions, or some other mean, to convert text to UTF-8 before passing it to htmLawed.\r
653 \r
654   *  Like any script using PHP's PCRE regex functions, PHP setup-specific low PCRE limit values can cause htmLawed to at least partially fail with very long input texts.\r
655         \r
656 \r
657 -- 2.9  Examples of usage -------------------------------------------o\r
658 \r
659 \r
660   Safest, allowing only `safe` HTML markup --\r
661   \r
662     $config = array('safe'=>1);\r
663     $out = htmLawed($in);\r
664     \r
665   Simplest, allowing all valid HTML markup except 'javascript:' --\r
666   \r
667     $out = htmLawed($in);\r
668     \r
669   Allowing all valid HTML markup including 'javascript:' --\r
670   \r
671     $config = array('schemes'=>'*:*');\r
672     $out = htmLawed($in, $config);\r
673     \r
674   Allowing only 'safe' HTML and the elements 'a', 'em', and 'strong' --\r
675   \r
676     $config = array('safe'=>1, 'elements'=>'a, em, strong');\r
677     $out = htmLawed($in, $config);\r
678     \r
679   Not allowing elements 'script' and 'object' --\r
680   \r
681     $config = array('elements'=>'* -script -object');\r
682     $out = htmLawed($in, $config);\r
683     \r
684   Not allowing attributes 'id' and 'style' --\r
685   \r
686     $config = array('deny_attribute'=>'id, style');\r
687     $out = htmLawed($in, $config);\r
688     \r
689   Permitting only attributes 'title' and 'href' --\r
690   \r
691     $config = array('deny_attribute'=>'* -title -href');\r
692     $out = htmLawed($in, $config);\r
693     \r
694   Remove bad/disallowed tags altogether instead of converting them to entities --\r
695   \r
696     $config = array('keep_bad'=>0);\r
697     $out = htmLawed($in, $config);\r
698     \r
699   Allowing attribute 'title' only in 'a' and not allowing attributes 'id', 'style', or scriptable `on*` attributes like 'onclick' --\r
700   \r
701     $config = array('deny_attribute'=>'title, id, style, on*');\r
702     $spec = 'a=title';\r
703     $out = htmLawed($in, $config, $spec); \r
704 \r
705   Allowing a custom attribute, 'vFlag', in 'img' and permitting custom use of the standard attribute, 'rel', in 'input' --\r
706   \r
707     $spec = 'img=vFlag; input=rel';\r
708     $out = htmLawed($in, $config, $spec);\r
709 \r
710   Some case-studies are presented below.\r
711 \r
712   *1.* A blog administrator wants to allow only 'a', 'em', 'strike', 'strong' and 'u' in comments, but needs 'strike' and 'u' transformed to 'span' for better XHTML 1-strict compliance, and, he wants the 'a' links to point only to 'http' or 'https' resources:\r
713 \r
714     $processed = htmLawed($in, array('elements'=>'a, em, strike, strong, u', 'make_tag_strict'=>1, 'safe'=>1, 'schemes'=>'*:http, https'), 'a=href');\r
715 \r
716   *2.* An author uses a custom-made web application to load content on his web-site. He is the only one using that application and the content he generates has all types of HTML, including scripts. The web application uses htmLawed primarily as a tool to correct errors that creep in while writing HTML and to take care of the occasional `bad` characters in copy-paste text introduced by Microsoft Office. The web application provides a preview before submitted input is added to the content. For the previewing process, htmLawed is set up as follows:\r
717 \r
718     $processed = htmLawed($in, array('css_expression'=>1, 'keep_bad'=>1, 'make_tag_strict'=>1, 'schemes'=>'*:*', 'valid_xhtml'=>1));\r
719 \r
720   For the final submission process, 'keep_bad' is set to '6'. A value of '1' for the preview process allows the author to note and correct any HTML mistake without losing any of the typed text.\r
721 \r
722   *3.* A data-miner is scraping information in a specific table of similar web-pages and is collating the data rows, and uses htmLawed to reduce unnecessary markup and white-spaces:\r
723 \r
724     $processed = htmLawed($in, array('elements'=>'tr, td', 'tidy'=>-1), 'tr, td =');\r
725 \r
726 \r
727 == 3  Details =====================================================oo\r
728 \r
729 \r
730 -- 3.1  Invalid/dangerous characters --------------------------------\r
731 \r
732 \r
733   Valid characters (more correctly, their code-points) in HTML or XML are, hexadecimally, '9', 'a', 'd', '20' to 'd7ff', and 'e000' to '10ffff', except 'fffe' and 'ffff' (decimally, '9', '10', '13', '32' to '55295', and '57344' to '1114111', except '65534' and '65535'). htmLawed removes the invalid characters '0' to '8', 'b', 'c', and 'e' to '1f'.\r
734 \r
735   Because of PHP's poor native support for multi-byte characters, htmLawed cannot check for the remaining invalid code-points. However, for various reasons, it is very unlikely for any of those characters to be in the input.\r
736 \r
737   Characters that are discouraged (see section:- #5.1) but not invalid are not removed by htmLawed.\r
738 \r
739   It (function 'hl_tag()') also replaces the potentially dangerous (in some Mozilla [Firefox] and Opera browsers) soft-hyphen character (code-point, hexadecimally, 'ad', or decimally, '173') in attribute values with spaces. Where required, the characters '<', '>', '&', and '"' are converted to entities.\r
740 \r
741   With '$config["clean_ms_char"]' set as '1' or '2', many of the discouraged characters (decimal code-points '127' to '159' except '133') that many Microsoft applications incorrectly use (as per the 'Windows 1252' ['Cp-1252'] or a similar encoding system), and the character for decimal code-point '133', are converted to appropriate decimal numerical entities (or removed for a few cases)-- see appendix in section:- #5.4. This can help avoid some display issues arising from copying-pasting of content.\r
742 \r
743   With '$config["clean_ms_char"]' set as '2', characters for the hexadecimal code-points '82', '91', and '92' (for special single-quotes), and '84', '93', and '94' (for special double-quotes) are converted to ordinary single and double quotes respectively and not to entities.\r
744 \r
745   The character values are replaced with entities/characters and not character values referred to by the entities/characters to keep this task independent of the character-encoding of input text.\r
746 \r
747   The '$config["clean_ms_char"]' parameter should not be used if authors do not copy-paste Microsoft-created text, or if the input text is not believed to use the 'Windows 1252' ('Cp-1252') or a similar encoding like 'Cp-1251' (otherwise, for example when UTF-8 encoding is in use, Japanese or Korean characters can get mangled). Further, the input form and the web-pages displaying it or its content should have the character encoding appropriately marked-up.\r
748 \r
749 \r
750 -- 3.2  Character references/entities ------------------------------o\r
751 \r
752 \r
753   Valid character entities take the form '&*;' where '*' is '#x' followed by a hexadecimal number (hexadecimal numeric entity; like '&#xA0;' for non-breaking space), or alphanumeric like 'gt' (external or named entity; like '&nbsp;' for non-breaking space), or '#' followed by a number (decimal numeric entity; like '&#160;' for non-breaking space). Character entities referring to the soft-hyphen character (the '&shy;' or '\xad' character; hexadecimal code-point 'ad' [decimal '173']) in URL-accepting attribute values are always replaced with spaces; soft-hyphens in attribute values introduce vulnerabilities in some older versions of the Opera and Mozilla [Firefox] browsers.\r
754 \r
755   htmLawed (function 'hl_ent()'):\r
756 \r
757   *  Neutralizes entities with multiple leading zeroes or missing semi-colons (potentially dangerous)\r
758 \r
759   *  Lowercases the 'X' (for XML-compliance) and 'A-F' of hexadecimal numeric entities\r
760 \r
761   *  Neutralizes entities referring to characters that are HTML-invalid (see section:- #3.1)\r
762 \r
763   *  Neutralizes entities referring to characters that are HTML-discouraged (code-points, hexadecimally, '7f' to '84', '86' to '9f', and 'fdd0' to 'fddf', or decimally, '127' to '132', '134' to '159', and '64991' to '64976'). Entities referring to the remaining discouraged characters (see section:- #5.1 for a full list) are let through.\r
764 \r
765   *  Neutralizes named entities that are not in the specs.\r
766 \r
767   *  Optionally converts valid HTML-specific named entities except '&gt;', '&lt;', '&quot;', and '&amp;' to decimal numeric ones (hexadecimal if $config["hexdec_entity"] is '2') for generic XML-compliance. For this, '$config["named_entity"]' should be '1'.\r
768 \r
769   *  Optionally converts hexadecimal numeric entities to the more widely supported decimal ones. For this, '$config["hexdec_entity"]' should be '0'.\r
770 \r
771   *  Optionally converts decimal numeric entities to the hexadecimal ones. For this, '$config["hexdec_entity"]' should be '2'.\r
772 \r
773   `Neutralization` refers to the `entitification` of '&' to '&amp;'.\r
774 \r
775   *Note*: htmLawed does not convert entities to the actual characters represented by them; one can pass the htmLawed output through PHP's 'html_entity_decode' function:- http://www.php.net/html_entity_decode for that.\r
776 \r
777   *Note*: If '$config["and_mark"]' is set, and set to a value other than '0', then the '&' characters in the original input are replaced with the control character for the hexadecimal code-point '6' ('\x06'; '&' characters introduced by htmLawed, e.g., after converting '<' to '&lt;', are not affected). This allows one to distinguish, say, an '&gt;' introduced by htmLawed and an '&gt;' put in by the input writer, and can be helpful in further processing of the htmLawed-processed text (e.g., to identify the character sequence 'o(><)o' to generate an emoticon image). When this feature is active, admins should ensure that the htmLawed output is not directly used in web pages or XML documents as the presence of the '\x06' can break documents. Before use in such documents, and preferably before any storage, any remaining '\x06' should be changed back to '&', e.g., with:\r
778 \r
779     $final = str_replace("\x06", '&', $prelim);\r
780 \r
781   Also, see section:- #3.9.\r
782 \r
783 \r
784 -- 3.3  HTML elements ----------------------------------------------o\r
785 \r
786 \r
787   htmLawed can be configured to allow only certain HTML elements (tags) in the input. Disallowed elements (just tag-content, and not element-content), based on '$config["keep_bad"]', are either `neutralized` (converted to plain text by entitification of '<' and '>') or removed.\r
788 \r
789   E.g., with only 'em' permitted:\r
790 \r
791   Input:\r
792 \r
793       <em>My</em> website is <a href="http://a.com>a.com</a>.\r
794 \r
795   Output, with '$config["keep_bad"] = 0':\r
796 \r
797       <em>My</em> website is a.com.\r
798 \r
799   Output, with '$config["keep_bad"]' not '0':\r
800 \r
801       <em>My</em> website is &lt;a href=""&gt;a.com&lt;/a&gt;.\r
802 \r
803   See section:- #3.3.3 for differences between the various non-zero '$config["keep_bad"]' values.\r
804 \r
805   htmLawed by default permits these 86 elements:\r
806 \r
807     a, abbr, acronym, address, applet, area, b, bdo, big, blockquote, br, button, caption, center, cite, code, col, colgroup, dd, del, dfn, dir, div, dl, dt, em, embed, fieldset, font, form, h1, h2, h3, h4, h5, h6, hr, i, iframe, img, input, ins, isindex, kbd, label, legend, li, map, menu, noscript, object, ol, optgroup, option, p, param, pre, q, rb, rbc, rp, rt, rtc, ruby, s, samp, script, select, small, span, strike, strong, sub, sup, table, tbody, td, textarea, tfoot, th, thead, tr, tt, u, ul, var\r
808 \r
809   Except for 'embed' (included because of its wide-spread use) and the Ruby elements ('rb', 'rbc', 'rp', 'rt', 'rtc', 'ruby'; part of XHTML 1.1), these are all the elements in the HTML 4/XHTML 1 specs. Strict-specific specs. exclude 'center', 'dir', 'font', 'isindex', 'menu', 's', 'strike', and 'u'.\r
810 \r
811   With '$config["safe"] = 1', the default set will exclude 'applet', 'embed', 'iframe', 'object' and 'script'; see section:- #3.6.\r
812 \r
813   When '$config["elements"]', which specifies allowed elements, is `properly` defined, and neither empty nor set to '0' or '*', the default set is not used. To have elements added to or removed from the default set, a '+/-' notation is used. E.g., '*-script-object' implies that only 'script' and 'object' are disallowed, whereas '*+embed' means that 'noembed' is also allowed. Elements can also be specified as comma separated names. E.g., 'a, b, i' means only 'a', 'b' and 'i' are permitted. In this notation, '*', '+' and '-' have no significance and can actually cause a mis-reading.\r
814 \r
815   Some more examples of '$config["elements"]' values indicating permitted elements (note that empty spaces are liberally allowed for clarity):\r
816 \r
817   *  'a, blockquote, code, em, strong' -- only 'a', 'blockquote', 'code', 'em', and 'strong'\r
818   *  '*-script' -- all excluding 'script'\r
819   *  '* -center -dir -font -isindex -menu -s -strike -u' -- only XHTML-Strict elements\r
820   *  '*+noembed-script' -- all including 'noembed' excluding 'script'\r
821 \r
822   Some mis-usages (and the resulting permitted elements) that can be avoided:\r
823 \r
824   *  '-*' -- none; instead of htmLawed, one might just use, e.g., the 'htmlspecialchars()' PHP function\r
825   *  '*, -script' -- all except 'script'; admin probably meant '*-script'\r
826   *  '-*, a, em, strong' -- all; admin probably meant 'a, em, strong'\r
827   *  '*' -- all; admin need not have set 'elements'\r
828   *  '*-form+form' -- all; a '+' will always over-ride any '-'\r
829   *  '*, noembed' -- only 'noembed'; admin probably meant '*+noembed'\r
830   *  'a, +b, i' -- only 'a' and 'i'; admin probably meant 'a, b, i'\r
831 \r
832   Basically, when using the '+/-' notation, commas (',') should not be used, and vice versa, and '*' should be used with the former but not the latter.\r
833 \r
834   *Note*: Even if an element that is not in the default set is allowed through '$config["elements"]', like 'noembed' in the last example, it will eventually be removed during tag balancing unless such balancing is turned off ('$config["balance"]' set to '0'). Currently, the only way around this, which actually is simple, is to edit the various arrays in the function 'hl_bal()' to accommodate the element and its nesting properties.\r
835 \r
836   *A possibly second way to specify allowed elements* is to set '$config["parent"]' to an element name that supposedly will hold the input, and to set '$config["balance"]' to '1'. During tag balancing (see section:- #3.3.3), all elements that cannot legally nest inside the parent element will be removed. The parent element is auto-reset to 'div' if '$config["parent"]' is empty, 'body', or an element not in htmLawed's default set of 86 elements.\r
837 \r
838   `Tag transformation` is possible for improving XHTML-Strict compliance -- most of the deprecated elements are removed or converted to valid XHTML-Strict ones; see section:- #3.3.2.\r
839 \r
840 \r
841 .. 3.3.1  Handling of comments and CDATA sections ...................\r
842 \r
843 \r
844   'CDATA' sections have the format '<![CDATA[...anything but not "]]>"...]]>', and HTML comments, '<!--...anything but not "-->"... -->'. Neither HTML comments nor 'CDATA' sections can reside inside tags. HTML comments can exist anywhere else, but 'CDATA' sections can exist only where plain text is allowed (e.g., immediately inside 'td' element content but not immediately inside 'tr' element content).\r
845 \r
846   htmLawed (function 'hl_cmtcd()') handles HTML comments or 'CDATA' sections depending on the values of '$config["comment"]' or '$config["cdata"]'. If '0', such markup is not looked for and the text is processed like plain text. If '1', it is removed completely. If '2', it is preserved but any '<', '>' and '&' inside are changed to entities. If '3', they are left as such.\r
847 \r
848   Note that for the last two cases, HTML comments and 'CDATA' sections will always be removed from tag content (function 'hl_tag()').\r
849 \r
850   Examples:\r
851 \r
852   Input:\r
853     <!-- home link --><a href="home.htm"><![CDATA[x=&y]]>Home</a>\r
854   Output ('$config["comment"] = 0, $config["cdata"] = 2'):\r
855     &lt;-- home link --&gt;<a href="home.htm"><![CDATA[x=&amp;y]]>Home</a>\r
856   Output ('$config["comment"] = 1, $config["cdata"] = 2'):\r
857     <a href="home.htm"><![CDATA[x=&amp;y]]>Home</a>\r
858   Output ('$config["comment"] = 2, $config["cdata"] = 2'):\r
859     <!-- home link --><a href="home.htm"><![CDATA[x=&amp;y]]>Home</a>\r
860   Output ('$config["comment"] = 2, $config["cdata"] = 1'):\r
861     <!-- home link --><a href="home.htm">Home</a>\r
862   Output ('$config["comment"] = 3, $config["cdata"] = 3'):\r
863     <!-- home link --><a href="home.htm"><![CDATA[x=&y]]>Home</a>\r
864 \r
865   For standard-compliance, comments are given the form '<!--comment -->', and any '--' in the content is made '-'.\r
866 \r
867   When '$config["safe"] = 1', CDATA sections and comments are considered plain text unless '$config["comment"]' or '$config["cdata"]' is explicitly specified; see section:- #3.6.\r
868 \r
869 \r
870 .. 3.3.2  Tag-transformation for better XHTML-Strict ................o\r
871 \r
872 \r
873   If '$config["make_tag_strict"]' is set and not '0', following non-XHTML-Strict elements (and attributes), even if admin-permitted, are mutated as indicated (element content remains intact; function 'hl_tag2()'):\r
874 \r
875   *  applet - (based on '$config["make_tag_strict"]', unchanged ('1') or removed ('2'))\r
876   *  center - 'div style="text-align: center;"'\r
877   *  dir - 'ul'\r
878   *  embed - (based on '$config["make_tag_strict"]', unchanged ('1') or removed ('2'))\r
879   *  font (face, size, color) - 'span style="font-family: ; font-size: ; color: ;"' (size transformation reference:- http://style.cleverchimp.com/font_size_intervals/altintervals.html)\r
880   *  isindex - (based on '$config["make_tag_strict"]', unchanged ('1') or removed ('2'))\r
881   *  menu - 'ul'\r
882   *  s - 'span style="text-decoration: line-through;"'\r
883   *  strike - 'span style="text-decoration: line-through;"'\r
884   *  u - 'span style="text-decoration: underline;"'\r
885 \r
886   For an element with a pre-existing 'style' attribute value, the extra style properties are appended.\r
887 \r
888   Example input:\r
889 \r
890     <center>\r
891      The PHP <s>software</s> script used for this <strike>web-page</strike> web-page is <font style="font-weight: bold " face=arial size='+3' color   =  "red  ">htmLawedTest.php</font>, from <u style= 'color:green'>PHP Labware</u>.\r
892     </center>\r
893 \r
894   The output:\r
895 \r
896     <div style="text-align: center;">\r
897      The PHP <span style="text-decoration: line-through;">software</span> script used for this <span style="text-decoration: line-through;">web-page</span> web-page is <span style="font-weight: bold; font-family: arial; color: red; font-size: 200%;">htmLawedTest.php</span>, from <span style="color:green; text-decoration: underline;">PHP Labware</span>.\r
898     </div>\r
899 \r
900 \r
901 -- 3.3.3  Tag balancing and proper nesting -------------------------o\r
902 \r
903 \r
904   If '$config["balance"]' is set to '1', htmLawed (function 'hl_bal()') checks and corrects the input to have properly balanced tags and legal element content (i.e., any element nesting should be valid, and plain text may be present only in the content of elements that allow them).\r
905 \r
906   Depending on the value of '$config["keep_bad"]' (see section:- #2.2 and section:- #3.3), illegal content may be removed or neutralized to plain text by converting < and > to entities:\r
907 \r
908   '0' - remove; this option is available only to maintain Kses-compatibility and should not be used otherwise (see section:- #2.6)\r
909   '1' - neutralize tags and keep element content\r
910   '2' - remove tags but keep element content\r
911   '3' and '4' - like '1' and '2', but keep element content only if text ('pcdata') is valid in parent element as per specs\r
912   '5' and '6' -  like '3' and '4', but line-breaks, tabs and spaces are left\r
913 \r
914   Example input (disallowing the 'p' element):\r
915 \r
916     <*> Pseudo-tags <*>\r
917     <xml>Non-HTML tag xml</xml>\r
918     <p>\r
919     Disallowed tag p\r
920     </p>\r
921     <ul>Bad<li>OK</li></ul>\r
922 \r
923   The output with '$config["keep_bad"] = 1':\r
924 \r
925     &lt;*&gt; Pseudo-tags &lt;*&gt;\r
926     &lt;xml&gt;Non-HTML tag xml&lt;/xml&gt;\r
927     &lt;p&gt;\r
928     Disallowed tag p\r
929     &lt;/p&gt;\r
930     <ul>Bad<li>OK</li></ul>\r
931 \r
932   The output with '$config["keep_bad"] = 3':\r
933 \r
934     &lt;*&gt; Pseudo-tags &lt;*&gt;\r
935     &lt;xml&gt;Non-HTML tag xml&lt;/xml&gt;\r
936     &lt;p&gt;\r
937     Disallowed tag p\r
938     &lt;/p&gt;\r
939     <ul><li>OK</li></ul>\r
940 \r
941   The output with '$config["keep_bad"] = 6':\r
942 \r
943     &lt;*&gt; Pseudo-tags &lt;*&gt;\r
944     Non-HTML tag xml\r
945     \r
946     Disallowed tag p\r
947     \r
948     <ul><li>OK</li></ul>\r
949 \r
950   An option like '1' is useful, e.g., when a writer previews his submission, whereas one like '3' is useful before content is finalized and made available to all.\r
951 \r
952   *Note:* In the example above, unlike '<*>', '<xml>' gets considered as a tag (even though there is no HTML element named 'xml'). Thus, the 'keep_bad' parameter's value affects '<xml>' but not '<*>'. In general, text matching the regular expression pattern '<(/?)([a-zA-Z][a-zA-Z1-6]*)([^>]*?)\s?>' is considered a tag (phrase enclosed by the angled brackets '<' and '>', and starting [with an optional slash preceding] with an alphanumeric word that starts with an alphabet...), and is subjected to the 'keep_bad' value.\r
953 \r
954   Nesting/content rules for each of the 86 elements in htmLawed's default set (see section:- #3.3) are defined in function 'hl_bal()'. This means that if a non-standard element besides 'embed' is being permitted through '$config["elements"]', the element's tag content will end up getting removed if '$config["balance"]' is set to '1'.\r
955 \r
956   Plain text and/or certain elements nested inside 'blockquote', 'form', 'map' and 'noscript' need to be in block-level elements. This point is often missed during manual writing of HTML code. htmLawed attempts to address this during balancing. E.g., if the parent container is set as 'form', the input 'B:<input type="text" value="b" />C:<input type="text" value="c" />' is converted to '<div>B:<input type="text" value="b" />C:<input type="text" value="c" /></div>'.\r
957 \r
958 \r
959 -- 3.3.4  Elements requiring child elements ------------------------o\r
960 \r
961 \r
962   As per specs, the following elements require legal child elements nested inside them:\r
963 \r
964     blockquote, dir, dl, form, map, menu, noscript, ol, optgroup, rbc, rtc, ruby, select, table, tbody, tfoot, thead, tr, ul\r
965 \r
966   In some cases, the specs stipulate the number and/or the ordering of the child elements. A 'table' can have 0 or 1 'caption', 'tbody', 'tfoot', and 'thead', but they must be in this order: 'caption', 'thead', 'tfoot', 'tbody'.\r
967 \r
968   htmLawed currently does not check for conformance to these rules. Note that any non-compliance in this regard will not introduce security vulnerabilities, crash browser applications, or affect the rendering of web-pages.\r
969   \r
970   With '$config["direct_list_nest"]' set to '1', htmLawed will allow direct nesting of an 'ol' or 'ul' list within another 'ol' or 'ul' without requiring the child list to be within an 'li' of the parent list. While this is not standard-compliant, directly nested lists are rendered properly by almost all browsers. The parameter '$config["direct_list_nest"]' has no effect if tag-balancing (section:- #3.3.3) is turned off.\r
971 \r
972 \r
973 -- 3.3.5  Beautify or compact HTML ---------------------------------o\r
974 \r
975 \r
976   By default, htmLawed will neither `beautify` HTML code by formatting it with indentations, etc., nor will it make it compact by removing un-needed white-space.(It does always properly white-space tag content.)\r
977 \r
978   As per the HTML standards, spaces, tabs and line-breaks in web-pages (except those inside 'pre' elements) are all considered equivalent, and referred to as `white-spaces`. Browser applications are supposed to consider contiguous white-spaces as just a single space, and to disregard white-spaces trailing opening tags or preceding closing tags. This white-space `normalization` allows the use of text/code beautifully formatted with indentations and line-spacings for readability. Such `pretty` HTML can, however, increase the size of web-pages, or make the extraction or scraping of plain text cumbersome.\r
979 \r
980   With the '$config' parameter 'tidy', htmLawed can be used to beautify or compact the input text. Input with just plain text and no HTML markup is also subject to this. Besides 'pre', the 'script' and 'textarea' elements, CDATA sections, and HTML comments are not subjected to the tidying process.\r
981 \r
982   To `compact`, use '$config["tidy"] = -1'; single instances or runs of white-spaces are replaced with a single space, and white-spaces trailing and leading open and closing tags, respectively, are removed.\r
983 \r
984   To `beautify`, '$config["tidy"]' is set as '1', or for customized tidying, as a string like '2s2n'. The 's' or 't' character specifies the use of spaces or tabs for indentation. The first and third characters, any of the digits 0-9, specify the number of spaces or tabs per indentation, and any parental lead spacing (extra indenting of the whole block of input text). The 'r' and 'n' characters are used to specify line-break characters: 'n' for '\n' (Unix/Mac OS X line-breaks), 'rn' or 'nr' for '\r\n' (Windows/DOS line-breaks), or 'r' for '\r'.\r
985 \r
986   The '$config["tidy"]' value of '1' is equivalent to '2s0n'. Other '$config["tidy"]' values are read loosely: a value of '4' is equivalent to '4s0n'; 't2', to '1t2n'; 's', to '2s0n'; '2TR', to '2t0r'; 'T1', to '1t1n'; 'nr3', to '3s0nr', and so on. Except in the indentations and line-spacings, runs of white-spaces are replaced with a single space during beautification.\r
987 \r
988   Input formatting using '$config["tidy"]' is not recommended when input text has mixed markup (like HTML + PHP).\r
989 \r
990 \r
991 -- 3.4  Attributes ------------------------------------------------oo\r
992 \r
993 \r
994   htmLawed will only permit attributes described in the HTML specs (including deprecated ones). It also permits some attributes for use with the 'embed' element (the non-standard 'embed' element is supported in htmLawed because of its widespread use), and the the 'xml:space' attribute (valid only in XHTML 1.1). A list of such 111 attributes and the elements they are allowed in is in section:- #5.2. Using the '$spec' argument, htmLawed can be forced to permit custom, non-standard attributes as well as custom rules for standard attributes (section:- #2.3).\r
995 \r
996   When '$config["deny_attribute"]' is not set, or set to '0', or empty ('""'), all the 111 attributes are permitted. Otherwise, '$config["deny_attribute"]' can be set as a list of comma-separated names of the denied attributes. 'on*' can be used to refer to the group of potentially dangerous, script-accepting attributes: 'onblur', 'onchange', 'onclick', 'ondblclick', 'onfocus', 'onkeydown', 'onkeypress', 'onkeyup', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onreset', 'onselect' and 'onsubmit'.\r
997 \r
998   Note that attributes specified in '$config["deny_attribute"]' are denied globally, for all elements. To deny attributes for only specific elements, '$spec' (see section:- #2.3) can be used. '$spec' can also be used to element-specifically permit an attribute otherwise denied through '$config["deny_attribute"]'.\r
999 \r
1000   With '$config["safe"] = 1' (section:- #3.6), the 'on*' attributes are automatically disallowed.\r
1001 \r
1002   *Note*: To deny all but a few attributes globally, a simpler way to specify '$config["deny_attribute"]' would be to use the notation '* -attribute1 -attribute2 ...'. Thus, a value of '* -title -href' implies that except 'href' and 'title' (where allowed as per standards) all other attributes are to be removed. With this notation, the value for the parameter 'safe' (section:- #3.6) will have no effect on 'deny_attribute'.\r
1003 \r
1004   htmLawed (function 'hl_tag()') also:\r
1005 \r
1006   *  Lower-cases attribute names\r
1007   *  Removes duplicate attributes (last one stays)\r
1008   *  Gives attributes the form 'name="value"' and single-spaces them, removing unnecessary white-spacing\r
1009   *  Provides `required` attributes (see section:- #3.4.1)\r
1010   *  Double-quotes values and escapes any '"' inside them\r
1011   *  Replaces the possibly dangerous soft-hyphen characters (hexadecimal code-point 'ad') in the values with spaces\r
1012   *  Allows custom function to additionally filter/modify attribute values (see section:- #3.4.9)\r
1013 \r
1014 \r
1015 .. 3.4.1  Auto-addition of XHTML-required attributes ................\r
1016 \r
1017 \r
1018   If indicated attributes for the following elements are found missing, htmLawed (function 'hl_tag()') will add them (with values same as attribute names unless indicated otherwise below):\r
1019 \r
1020   *  area - alt ('area')\r
1021   *  area, img - src, alt ('image')\r
1022   *  bdo - dir ('ltr')\r
1023   *  form - action\r
1024   *  map - name\r
1025   *  optgroup - label\r
1026   *  param - name\r
1027   *  script - type ('text/javascript')\r
1028   *  textarea - rows ('10'), cols ('50')\r
1029 \r
1030   Additionally, with '$config["xml:lang"]' set to '1' or '2', if the 'lang' but not the 'xml:lang' attribute is declared, then the latter is added too, with a value copied from that of 'lang'. This is for better standard-compliance. With '$config["xml:lang"]' set to '2', the 'lang' attribute is removed (XHTML 1.1 specs).\r
1031 \r
1032   Note that the 'name' attribute for 'map', invalid in XHTML 1.1, is also transformed if required -- see section:- #3.4.6.\r
1033 \r
1034 \r
1035 .. 3.4.2  Duplicate/invalid 'id' values ............................o\r
1036 \r
1037 \r
1038   If '$config["unique_ids"]' is '1', htmLawed (function 'hl_tag()') removes 'id' attributes with values that are not XHTML-compliant (must begin with a letter and can contain letters, digits, ':', '.', '-' and '_') or duplicate. If '$config["unique_ids"]' is a word, any duplicate but otherwise valid value will be appropriately prefixed with the word to ensure its uniqueness. The word should begin with a letter and should contain only letters, numbers, ':', '.', '_' and '-'.\r
1039 \r
1040   Even if multiple inputs need to be filtered (through multiple calls to htmLawed), htmLawed ensures uniqueness of 'id' values as it uses a global variable ('$GLOBALS["hl_Ids"]' array). Further, an admin can restrict the use of certain 'id' values by presetting this variable before htmLawed is called into use. E.g.:\r
1041 \r
1042     $GLOBALS['hl_Ids'] = array('top'=>1, 'bottom'=>1, 'myform'=>1); // id values not allowed in input\r
1043     $processed = htmLawed($text); // filter input\r
1044 \r
1045 \r
1046 .. 3.4.3  URL schemes (protocols) and scripts in attribute values ............o\r
1047 \r
1048 \r
1049   htmLawed edits attributes that take URLs as values if they are found to contain un-permitted schemes. E.g., if the 'afp' scheme is not permitted, then '<a href="afp://domain.org">' becomes '<a href="denied:afp://domain.org">', and if Javascript is not permitted '<a onclick="javascript:xss();">' becomes '<a onclick="denied:javascript:xss();">'.\r
1050 \r
1051   By default htmLawed permits these schemes in URLs for the 'href' attribute:\r
1052 \r
1053     aim, feed, file, ftp, gopher, http, https, irc, mailto, news, nntp, sftp, ssh, telnet\r
1054 \r
1055   Also, only 'file', 'http' and 'https' are permitted in attributes whose names start with 'o' (like 'onmouseover'), and in these attributes that accept URLs:\r
1056 \r
1057     action, cite, classid, codebase, data, href, longdesc, model, pluginspage, pluginurl, src, style, usemap\r
1058 \r
1059   These default sets are used when '$config["schemes"]' is not set (see section:- #2.2). To over-ride the defaults, '$config["schemes"]' is defined as a string of semi-colon-separated sub-strings of type 'attribute: comma-separated schemes'. E.g., 'href: mailto, http, https; onclick: javascript; src: http, https'. For unspecified attributes, 'file', 'http' and 'https' are permitted. This can be changed by passing schemes for '*' in '$config["schemes"]'. E.g., 'href: mailto, http, https; *: https, https'.\r
1060 \r
1061   '*' can be put in the list of schemes to permit all protocols. E.g., 'style: *; img: http, https' results in protocols not being checked in 'style' attribute values. However, in such cases, any relative-to-absolute URL conversion, or vice versa, (section:- #3.4.4) is not done.\r
1062 \r
1063   Thus, `to allow Javascript`, one can set '$config["schemes"]' as 'href: mailto, http, https; *: http, https, javascript', or 'href: mailto, http, https, javascript; *: http, https, javascript', or '*: *', and so on.\r
1064 \r
1065   As a side-note, one may find 'style: *' useful as URLs in 'style' attributes can be specified in a variety of ways, and the patterns that htmLawed uses to identify URLs may mistakenly identify non-URL text.\r
1066   \r
1067   '!' can be put in the list of schemes to disallow all protocols as well as `local` URLs. Thus, with 'href: http, style: !', '<a href="http://cnn.com" style="background-image: url('local.jpg');">CNN</a>' will become '<a href="http://cnn.com" style="background-image: url('denied:local.jpg');">CNN</a>'.\r
1068 \r
1069   *Note*: If URL-accepting attributes other than those listed above are being allowed, then the scheme will not be checked unless the attribute name contains the string 'src' (e.g., 'dynsrc') or starts with 'o' (e.g., 'onbeforecopy').\r
1070 \r
1071   With '$config["safe"] = 1', all URLs are disallowed in the 'style' attribute values.\r
1072 \r
1073 \r
1074 .. 3.4.4  Absolute & relative URLs in attribute values .............o\r
1075 \r
1076 \r
1077   htmLawed can make absolute URLs in attributes like 'href' relative ('$config["abs_url"]' is '-1'), and vice versa ('$config["abs_url"]' is '1'). URLs in scripts are not considered for this, and so are URLs like '#section_6' (fragment), '?name=Tim#show' (starting with query string), and ';var=1?name=Tim#show' (starting with parameters). Further, this requires that '$config["base_url"]' be set properly, with the '://' and a trailing slash ('/'), with no query string, etc. E.g., 'file:///D:/page/', 'https://abc.com/x/y/', or 'http://localhost/demo/' are okay, but 'file:///D:/page/?help=1', 'abc.com/x/y/' and 'http://localhost/demo/index.htm' are not.\r
1078 \r
1079   For making absolute URLs relative, only those URLs that have the '$config["base_url"]' string at the beginning are converted. E.g., with '$config["base_url"] = "https://abc.com/x/y/"', 'https://abc.com/x/y/a.gif' and 'https://abc.com/x/y/z/b.gif' become 'a.gif' and 'z/b.gif' respectively, while 'https://abc.com/x/c.gif' is not changed.\r
1080 \r
1081   When making relative URLs absolute, only values for scheme, network location (host-name) and path values in the base URL are inherited. See section:- #5.5 for more about the URL specification as per RFC 1808:- http://www.ietf.org/rfc/rfc1808.txt.\r
1082 \r
1083 \r
1084 .. 3.4.5  Lower-cased, standard attribute values ....................o\r
1085 \r
1086 \r
1087   Optionally, for standard-compliance, htmLawed (function 'hl_tag()') lower-cases standard attribute values to give, e.g., 'input type="password"' instead of 'input type="Password"', if '$config["lc_std_val"]' is '1'. Attribute values matching those listed below for any of the elements (plus those for the 'type' attribute of 'button' or 'input') are lower-cased:\r
1088 \r
1089     all, baseline, bottom, button, center, char, checkbox, circle, col, colgroup, cols, data, default, file, get, groups, hidden, image, justify, left, ltr, middle, none, object, password, poly, post, preserve, radio, rect, ref, reset, right, row, rowgroup, rows, rtl, submit, text, top\r
1090 \r
1091     a, area, bdo, button, col, form, img, input, object, option, optgroup, param, script, select, table, td, tfoot, th, thead, tr, xml:space\r
1092 \r
1093   The following `empty` (`minimized`) attributes are always assigned lower-cased values (same as the names):\r
1094 \r
1095     checked, compact, declare, defer, disabled, ismap, multiple, nohref, noresize, noshade, nowrap, readonly, selected\r
1096 \r
1097 \r
1098 .. 3.4.6  Transformation of deprecated attributes ..................o\r
1099 \r
1100 \r
1101   If '$config["no_deprecated_attr"]' is '0', then deprecated attributes (see appendix in section:- #5.2) are removed and, in most cases, their values are transformed to CSS style properties and added to the 'style' attributes (function 'hl_tag()'). Except for 'bordercolor' for 'table', 'tr' and 'td', the scores of proprietary attributes that were never part of any cross-browser standard are not supported.\r
1102 \r
1103   *Note*: The attribute 'target' for 'a' is allowed even though it is not in XHTML 1.0 specs. This is because of the attribute's wide-spread use and browser-support, and because the attribute is valid in XHTML 1.1 onwards.\r
1104 \r
1105   *  align - for 'img' with value of 'left' or 'right', becomes, e.g., 'float: left'; for 'div' and 'table' with value 'center', becomes 'margin: auto'; all others become, e.g., 'text-align: right'\r
1106 \r
1107   *  bgcolor - E.g., 'bgcolor="#ffffff"' becomes 'background-color: #ffffff'\r
1108   *  border - E.g., 'height= "10"' becomes 'height: 10px'\r
1109   *  bordercolor - E.g., 'bordercolor=#999999' becomes 'border-color: #999999;'\r
1110   *  compact - 'font-size: 85%'\r
1111   *  clear - E.g., 'clear="all" becomes 'clear: both'\r
1112 \r
1113   *  height - E.g., 'height= "10"' becomes 'height: 10px' and 'height="*"' becomes 'height: auto'\r
1114 \r
1115   *  hspace - E.g., 'hspace="10"' becomes 'margin-left: 10px; margin-right: 10px'\r
1116   *  language - 'language="VBScript"' becomes 'type="text/vbscript"'\r
1117   *  name - E.g., 'name="xx"' becomes 'id="xx"'\r
1118   *  noshade - 'border-style: none; border: 0; background-color: gray; color: gray'\r
1119   *  nowrap - 'white-space: nowrap'\r
1120   *  size - E.g., 'size="10"' becomes 'height: 10px'\r
1121   *  start - removed\r
1122   *  type - E.g., 'type="i"' becomes 'list-style-type: lower-roman'\r
1123   *  value - removed\r
1124   *  vspace - E.g., 'vspace="10"' becomes 'margin-top: 10px; margin-bottom: 10px'\r
1125   *  width - like 'height'\r
1126 \r
1127   Example input:\r
1128 \r
1129     <img src="j.gif" alt="image" name="dad's" /><img src="k.gif" alt="image" id="dad_off" name="dad" />\r
1130     <br clear="left" />\r
1131     <hr noshade size="1" />\r
1132     <img name="img" src="i.gif" align="left" alt="image" hspace="10" vspace="10" width="10em" height="20" border="1" style="padding:5px;" />\r
1133     <table width="50em" align="center" bgcolor="red">\r
1134      <tr>\r
1135       <td width="20%">\r
1136        <div align="center">\r
1137         <h3 align="right">Section</h3>\r
1138         <p align="right">Para</p>\r
1139         <ol type="a" start="e"><li value="x">First item</li></ol>\r
1140        </div>\r
1141       </td>\r
1142       <td width="*">\r
1143        <ol type="1"><li>First item</li></ol>\r
1144       </td>\r
1145      </tr>\r
1146     </table>\r
1147     <br clear="all" />\r
1148 \r
1149   And the output with '$config["no_deprecated_attr"] = 1':\r
1150 \r
1151     <img src="j.gif" alt="image" /><img src="k.gif" alt="image" id="dad_off" />\r
1152     <br style="clear: left;" />\r
1153     <hr style="border-style: none; border: 0; background-color: gray; color: gray; size: 1px;" />\r
1154     <img src="i.gif" alt="image" width="10em" height="20" style="padding:5px; float: left; margin-left: 10px; margin-right: 10px; margin-top: 10px; margin-bottom: 10px; border: 1px;" id="img" />\r
1155     <table width="50em" style="margin: auto; background-color: red;">\r
1156      <tr>\r
1157       <td style="width: 20%;">\r
1158        <div style="margin: auto;">\r
1159         <h3 style="text-align: right;">Section</h3>\r
1160         <p style="text-align: right;">Para</p>\r
1161         <ol style="list-style-type: lower-latin;"><li>First item</li></ol>\r
1162        </div>\r
1163       </td>\r
1164       <td style="width: auto;">\r
1165        <ol style="list-style-type: decimal;"><li>First item</li></ol>\r
1166       </td>\r
1167      </tr>\r
1168     </table>\r
1169     <br style="clear: both;" />\r
1170 \r
1171   For 'lang', deprecated in XHTML 1.1, transformation is taken care of through '$config["xml:lang"]'; see section:- #3.4.1.\r
1172 \r
1173   The attribute 'name' is deprecated in 'form', 'iframe', and 'img', and is replaced with 'id' if an 'id' attribute doesn't exist and if the 'name' value is appropriate for 'id'. For such replacements for 'a' and 'map', for which the 'name' attribute is deprecated in XHTML 1.1, '$config["no_deprecated_attr"]' should be set to '2' (when set to '1', for these two elements, the 'name' attribute is retained).\r
1174 \r
1175 \r
1176 -- 3.4.7  Anti-spam & 'href' ---------------------------------------o\r
1177 \r
1178 \r
1179   htmLawed (function 'hl_tag()') can check the 'href' attribute values (link addresses) as an anti-spam (email or link spam) measure.\r
1180 \r
1181   If '$config["anti_mail_spam"]' is not '0', the '@' of email addresses in 'href' values like 'mailto:a@b.com' is replaced with text specified by '$config["anti_mail_spam"]'. The text should be of a form that makes it clear to others that the address needs to be edited before a mail is sent; e.g., '<remove_this_antispam>@' (makes the example address 'a<remove_this_antispam>@b.com').\r
1182 \r
1183   For regular links, one can choose to have a 'rel' attribute with 'nofollow' in its value (which tells some search engines to not follow a link). This can discourage link spammers. Additionally, or as an alternative, one can choose to empty the 'href' value altogether (disable the link).\r
1184 \r
1185   For use of these options, '$config["anti_link_spam"]' should be set as an array with values 'regex1' and 'regex2', both or one of which can be empty (like 'array("", "regex2")') to indicate that that option is not to be used. Otherwise, 'regex1' or 'regex2' should be PHP- and PCRE-compatible regular expression patterns: 'href' values will be matched against them and those matching the pattern will accordingly be treated.\r
1186 \r
1187   Note that the regular expressions should have `delimiters`, and be well-formed and preferably fast. Absolute efficiency/accuracy is often not needed.\r
1188 \r
1189   An example, to have a 'rel' attribute with 'nofollow' for all links, and to disable links that do not point to domains 'abc.com' and 'xyz.org':\r
1190 \r
1191     $config["anti_link_spam"] = array('`.`', '`://\W*(?!(abc\.com|xyz\.org))`');\r
1192 \r
1193 \r
1194 -- 3.4.8  Inline style properties ----------------------------------o\r
1195 \r
1196 \r
1197   htmLawed can check URL schemes and dynamic expressions (to guard against Javascript, etc., script-based insecurities) in inline CSS style property values in the 'style' attributes. (CSS properties like 'background-image' that accept URLs in their values are noted in section:- #5.3.) Dynamic CSS expressions that allow scripting in the IE browser, and can be a vulnerability, can be removed from property values by setting '$config["css_expression"]' to '1' (default setting). Note that when '$config["css_expression"]' is set to '1', htmLawed will remove '/*' from the 'style' values.\r
1198 \r
1199   *Note*: Because of the various ways of representing characters in attribute values (URL-escapement, entitification, etc.), htmLawed might alter the values of the 'style' attribute values, and may even falsely identify dynamic CSS expressions and URL schemes in them. If this is an important issue, checking of URLs and dynamic expressions can be turned off ('$config["schemes"] = "...style:*..."', see section:- #3.4.3, and '$config["css_expression"] = 0'). Alternately, admins can use their own custom function for finer handling of 'style' values through the 'hook_tag' parameter (see section:- #3.4.9).\r
1200 \r
1201   It is also possible to have htmLawed let through any 'style' value by setting '$config["style_pass"]' to '1'.\r
1202 \r
1203   As such, it is better to set up a CSS file with class declarations, disallow the 'style' attribute, set a '$spec' rule (see section:- #2.3) for 'class' for the 'oneof' or 'match' parameter, and ask writers to make use of the 'class' attribute.\r
1204 \r
1205 \r
1206 -- 3.4.9  Hook function for tag content ----------------------------o\r
1207 \r
1208 \r
1209   It is possible to utilize a custom hook function to alter the tag content htmLawed has finalized (i.e., after it has checked/corrected for required attributes, transformed attributes, lower-cased attribute names, etc.).\r
1210 \r
1211   When '$config' parameter 'hook_tag' is set to the name of a function, htmLawed (function 'hl_tag()') will pass on the element name, and, in the case of an opening tag, the `finalized` attribute name-value pairs as array elements to the function. The function, after completing a task such as filtering or tag transformation, will typically return an empty string, the full opening tag string like '<element_name attribute_1_name="attribute_1_value"...>' (for empty elements like 'img' and 'input', the element-closing slash '/' should also be included), etc.\r
1212   \r
1213   Any 'hook_tag' function, since htmLawed version 1.1.11, also receives names of elements in closing tags, such as 'a' in the closing '</a>' tag of the element '<a href="http://cnn.com">CNN</a>'. Unlike for opening tags, no other value (i.e., the attribute name-value array) is passed to the function since a closing tag contains only element names. Typically, the function will return an empty string or a full closing tag (like '</a>'). \r
1214 \r
1215   This is a *powerful functionality* that can be exploited for various objectives: consolidate-and-convert inline 'style' attributes to 'class', convert 'embed' elements to 'object', permit only one 'caption' element in a 'table' element, disallow embedding of certain types of media, *inject HTML*, use CSSTidy:- http://csstidy.sourceforge.net to sanitize 'style' attribute values, etc.\r
1216 \r
1217   As an example, the custom hook code below can be used to force a series of specifically ordered 'id' attributes on all elements, and a specific 'param' element inside all 'object' elements:\r
1218 \r
1219     function my_tag_function($element, $attribute_array=0){\r
1220     \r
1221       // If second argument is not received, it means a closing tag is being handled\r
1222       if(is_numeric($attribute_array)){\r
1223         return "</$element>";\r
1224       }\r
1225       \r
1226       static $id = 0;\r
1227       // Remove any duplicate element\r
1228       if($element == 'param' && isset($attribute_array['allowscriptaccess'])){\r
1229         return '';\r
1230       }\r
1231 \r
1232       $new_element = '';\r
1233 \r
1234       // Force a serialized ID number\r
1235       $attribute_array['id'] = 'my_'. $id;\r
1236       ++$id;\r
1237 \r
1238       // Inject param for allowscriptaccess\r
1239       if($element == 'object'){\r
1240         $new_element = '<param id='my_'. $id; allowscriptaccess="never" />';\r
1241         ++$id;\r
1242       }\r
1243 \r
1244       $string = '';\r
1245       foreach($attribute_array as $k=>$v){\r
1246         $string .= " {$k}=\"{$v}\"";\r
1247       }\r
1248       \r
1249       static $empty_elements = array('area'=>1, 'br'=>1, 'col'=>1, 'embed'=>1, 'hr'=>1, 'img'=>1, 'input'=>1, 'isindex'=>1, 'param'=>1);\r
1250 \r
1251       return "<{$element}{$string}". (isset($in_array($element, $empty_elements) ? ' /' : ''). '>'. $new_element;\r
1252     }\r
1253 \r
1254   The 'hook_tag' parameter is different from the 'hook' parameter (section:- #3.7).\r
1255 \r
1256   Snippets of hook function code developed by others may be available on the htmLawed:- http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed website.\r
1257 \r
1258 \r
1259 -- 3.5  Simple configuration directive for most valid XHTML -------oo\r
1260 \r
1261 \r
1262   If '$config["valid_xhtml"]' is set to '1', some relevant '$config' parameters (indicated by '~' in section:- #2.2) are auto-adjusted. This allows one to pass the '$config' argument with a simpler value. If a value for a parameter auto-set through 'valid_xhtml' is still manually provided, then that value will over-ride the auto-set value.\r
1263 \r
1264 \r
1265 -- 3.6  Simple configuration directive for most `safe` HTML --------o\r
1266 \r
1267 \r
1268   `Safe` HTML refers to HTML that is restricted to reduce the vulnerability for scripting attacks (such as XSS) based on HTML code which otherwise may still be legal and compliant with the HTML standard specs. When elements such as 'script' and 'object', and attributes such as 'onmouseover' and 'style' are allowed in the input text, an input writer can introduce malevolent HTML code. Note that what is considered 'safe' depends on the nature of the web application and the trust-level accorded to its users.\r
1269 \r
1270   htmLawed allows an admin to use '$config["safe"]' to auto-adjust multiple '$config' parameters (such as 'elements' which declares the allowed element-set), which otherwise would have to be manually set. The relevant parameters are indicated by '"' in section:- #2.2). Thus, one can pass the '$config' argument with a simpler value.\r
1271 \r
1272   With the value of '1', htmLawed considers 'CDATA' sections and HTML comments as plain text, and prohibits the 'applet', 'embed', 'iframe', 'object' and 'script' elements, and the 'on*' attributes like 'onclick'. ( There are '$config' parameters like 'css_expression' that are not affected by the value set for 'safe' but whose default values still contribute towards a more `safe` output.) Further, URLs with schemes (see section:- #3.4.3) are neutralized so that, e.g., 'style="moz-binding:url(http://danger)"' becomes 'style="moz-binding:url(denied:http://danger)"'.\r
1273 \r
1274   Admins, however, may still want to completely deny the 'style' attribute, e.g., with code like\r
1275 \r
1276     $processed = htmLawed($text, array('safe'=>1, 'deny_attribute'=>'style'));\r
1277 \r
1278   Permitting the 'style' attribute brings in risks of `click-jacking`, etc. CSS property values can render a page non-functional or be used to deface it. Except for URLs, dynamic expressions, and some other things, htmLawed does not completely check 'style' values. It does provide ways for the code-developer implementing htmLawed to do such checks through the '$spec' argument, and through the 'hook_tag' parameter (see section:- #3.4.8 for more). Disallowing style completely and relying on CSS classes and stylesheet files is recommended. \r
1279   \r
1280   If a value for a parameter auto-set through 'safe' is still manually provided, then that value can over-ride the auto-set value. E.g., with '$config["safe"] = 1' and '$config["elements"] = "*+script"', 'script', but not 'applet', is allowed.\r
1281 \r
1282   A page illustrating the efficacy of htmLawed's anti-XSS abilities with 'safe' set to '1' against XSS vectors listed by RSnake:- http://ha.ckers.org/xss.html may be available here:- http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed/rsnake/RSnakeXSSTest.htm.\r
1283 \r
1284 \r
1285 -- 3.7  Using a hook function --------------------------------------o\r
1286 \r
1287 \r
1288   If '$config["hook"]' is not set to '0', then htmLawed will allow preliminarily processed input to be altered by a hook function named by '$config["hook"]' before starting the main work (but after handling of characters, entities, HTML comments and 'CDATA' sections -- see code for function 'htmLawed()').\r
1289 \r
1290   The hook function also allows one to alter the `finalized` values of '$config' and '$spec'.\r
1291 \r
1292   Note that the 'hook' parameter is different from the 'hook_tag' parameter (section:- #3.4.9).\r
1293 \r
1294   Snippets of hook function code developed by others may be available on the htmLawed:- http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed website.\r
1295 \r
1296 \r
1297 -- 3.8  Obtaining `finalized` parameter values ---------------------o\r
1298 \r
1299 \r
1300   htmLawed can assign the `finalized` '$config' and '$spec' values to a variable named by '$config["show_setting"]'. The variable, made global by htmLawed, is set as an array with three keys: 'config', with the '$config' value, 'spec', with the '$spec' value, and 'time', with a value that is the Unix time (the output of PHP's 'microtime()' function) when the value was assigned. Admins should use a PHP-compliant variable name (e.g., one that does not begin with a numerical digit) that does not conflict with variable names in their non-htmLawed code.\r
1301 \r
1302   The values, which are also post-hook function (if any), can be used to auto-generate information (on, e.g., the elements that are permitted) for input writers.\r
1303 \r
1304 \r
1305 -- 3.9  Retaining non-HTML tags in input with mixed markup ---------o\r
1306 \r
1307 \r
1308   htmLawed does not remove certain characters that, though invalid, are nevertheless `discouraged` in HTML documents as per the specifications (see section:- #5.1). This can be utilized to deal with input that contains mixed markup. Input that may have HTML markup as well as some other markup that is based on the '<', '>' and '&' characters is considered to have mixed markup. The non-HTML markup can be rather proprietary (like markup for emoticons/smileys), or standard (like MathML or SVG). Or it can be programming code meant for execution/evaluation (such as embedded PHP code).\r
1309 \r
1310   To deal with such mixed markup, the input text can be pre-processed to hide the non-HTML markup by specifically replacing the '<', '>' and '&' characters with some of the HTML-discouraged characters (see section:- #3.1.2). Post-htmLawed processing, the replacements are reverted.\r
1311 \r
1312   An example (mixed HTML and PHP code in input text):\r
1313 \r
1314     $text = preg_replace('`<\?php(.+?)\?>`sm', "\x83?php\\1?\x84", $text);\r
1315     $processed = htmLawed($text);\r
1316     $processed = preg_replace('`\x83\?php(.+?)\?\x84`sm', '<?php$1?>', $processed);\r
1317 \r
1318   This code will not work if '$config["clean_ms_char"]' is set to '1' (section:- #3.1), in which case one should instead deploy a hook function (section:- #3.7). (htmLawed internally uses certain control characters, code-points '1' to '7', and use of these characters as markers in the logic of hook functions may cause issues.)\r
1319 \r
1320   Admins may also be able to use '$config["and_mark"]' to deal with such mixed markup; see section:- #3.2.\r
1321  \r
1322 \r
1323 == 4  Other =======================================================oo\r
1324 \r
1325 \r
1326 -- 4.1  Support -----------------------------------------------------\r
1327 \r
1328 \r
1329   A careful reading of this documentation may provide an answer.\r
1330 \r
1331   Software updates and forum-based community-support may be found at http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed. For general PHP issues (not htmLawed-specific), support may be found through internet searches and at http://php.net.\r
1332 \r
1333 \r
1334 -- 4.2  Known issues -----------------------------------------------o\r
1335 \r
1336 \r
1337   See section:- #2.8.\r
1338 \r
1339 \r
1340 -- 4.3  Change-log -------------------------------------------------o\r
1341 \r
1342 \r
1343   (The release date for the downloadable package of files containing documentation, demo script, test-cases, etc., besides the 'htmLawed.php' file, may be updated without a change-log entry if the secondary files, but not htmLawed per se, are revised.)\r
1344 \r
1345   `Version number - Release date. Notes`\r
1346   \r
1347   1.1.16 - 29 August 2013. Fix for a potential security vulnerability arising from specialy encoded space characters in URL schemes/protocols\r
1348     \r
1349   1.1.15 - 11 August 2013. Improved tidying/prettifying functionality\r
1350     \r
1351   1.1.14 - 8 August 2012. Fix for possible segmental loss of incremental indentation during 'tidying' when 'balance' is disabled; fix for non-effectuation under some circumstances of a corrective behavior to preserve plain text within elements like 'blockquote'.\r
1352   \r
1353   1.1.13 - 22 July 2012. Added feature allowing use of custom, non-standard attributes or custom rules for standard attributes\r
1354   \r
1355   1.1.12 - 5 July 2012. Fix for a bug in identifying an unquoted value of the 'face' attribute \r
1356   \r
1357   1.1.11 - 5 June 2012. Fix for possible problem with handling of multi-byte characters in attribute values in an mbstring.func_overload enviroment. '$config["hook_tag"]', if specified, now receives names of elements in closing tags.\r
1358   \r
1359   1.1.10 - 22 October 2011. Fix for a bug in the 'tidy' functionality that caused the entire input to be replaced with a single space; new parameter, '$config["direct_list_nest"]' to allow direct descendance of a list in a list. (5 April 2012. Dual licensing from LGPLv3 to LGPLv3 and GPLv2+.)\r
1360   \r
1361   1.1.9.5 - 6 July 2011. Minor correction of a rule for nesting of 'li' within 'dir'\r
1362   \r
1363   1.1.9.4 - 3 July 2010. Parameter 'schemes' now accepts '!' so any URL, even a local one, can be `denied`. An issue in which a second URL value in 'style' properties was not checked was fixed.\r
1364   \r
1365   1.1.9.3 - 17 May 2010. Checks for correct nesting of 'param'\r
1366   \r
1367   1.1.9.2 - 26 April 2010. Minor fix regarding rendering of denied URL schemes\r
1368   \r
1369   1.1.9.1 - 26 February 2010. htmLawed now uses the LGPL version 3 license; support for 'flashvars' attribute for 'embed'\r
1370   \r
1371   1.1.9 - 22 December 2009. Soft-hyphens are now removed only from URL-accepting attribute values\r
1372 \r
1373   1.1.8.1 - 16 July 2009. Minor code-change to fix a PHP error notice\r
1374 \r
1375   1.1.8 - 23 April 2009. Parameter 'deny_attribute' now accepts the wild-card '*', making it simpler to specify its value when all but a few attributes are being denied; fixed a bug in interpreting '$spec'\r
1376 \r
1377   1.1.7 - 11-12 March 2009. Attributes globally denied through 'deny_attribute' can be allowed element-specifically through '$spec'; '$config["style_pass"]' allowing letting through any 'style' value introduced; altered logic to catch certain types of dynamic crafted CSS expressions\r
1378 \r
1379   1.1.3-6 - 28-31 January - 4 February 2009. Altered logic to catch certain types of dynamic crafted CSS expressions\r
1380 \r
1381   1.1.2 - 22 January 2009. Fixed bug in parsing of 'font' attributes during tag transformation\r
1382   \r
1383   1.1.1 - 27 September 2008. Better nesting correction when omitable closing tags are absent\r
1384 \r
1385   1.1 - 29 June 2008. '$config["hook_tag"]' and '$config["tidy"]' introduced for custom tag/attribute check/modification/injection and output compaction/beautification; fixed a regex-in-$spec parsing bug\r
1386 \r
1387   1.0.9 - 11 June 2008. Fix for a bug in checks for invalid HTML code-point entities\r
1388 \r
1389   1.0.8 - 15 May 2008. Permit 'bordercolor' attribute for 'table', 'td' and 'tr'\r
1390 \r
1391   1.0.7 - 1 May 2008. Support for 'wmode' attribute for 'embed'; '$config["show_setting"]' introduced; improved '$config["elements"]' evaluation\r
1392 \r
1393   1.0.6 - 20 April 2008. '$config["and_mark"]' introduced\r
1394 \r
1395   1.0.5 - 12 March 2008. 'style' URL schemes essentially disallowed when $config 'safe' is on; improved regex for CSS expression search\r
1396 \r
1397   1.0.4 - 10 March 2008. Improved corrections for 'blockquote', 'form', 'map' and 'noscript'\r
1398 \r
1399   1.0.3 - 3 March 2008. Character entities for soft-hyphens are now replaced with spaces (instead of being removed); fix for a bug allowing 'td' directly inside 'table'; '$config["safe"]' introduced\r
1400 \r
1401   1.0.2 - 13 February 2008. Improved implementation of '$config["keep_bad"]'\r
1402 \r
1403   1.0.1 - 7 November 2007. Improved regex for identifying URLs, protocols and dynamic expressions ('hl_tag()' and 'hl_prot()'); no error display with 'hl_regex()'\r
1404 \r
1405   1.0 - 2 November 2007. First release\r
1406 \r
1407 \r
1408 -- 4.4  Testing ----------------------------------------------------o\r
1409 \r
1410 \r
1411   To test htmLawed using a form interface, a demo:- htmLawedTest.php web-page is provided with the htmLawed distribution ('htmLawed.php' and 'htmLawedTest.php' should be in the same directory on the web-server). A file with test-cases:- htmLawed_TESTCASE.txt is also provided.\r
1412 \r
1413 \r
1414 -- 4.5  Upgrade, & old versions ------------------------------------o\r
1415 \r
1416 \r
1417   Upgrading is as simple as replacing the previous version of 'htmLawed.php' (assuming it was not modified for customized features). As htmLawed output is almost always used in static documents, upgrading should not affect old, finalized content.\r
1418 \r
1419   *Important*  The following upgrades may affect the functionality of a specific htmLawed installation:\r
1420 \r
1421   (1) From version 1.1-1.1.10 to 1.1.11 (or later), if a 'hook_tag' function is in use: In version 1.1.11, elements in closing tags (and not just the opening tags) are also passed to the function. There are no attribute names/values to pass, so a 'hook_tag' function receives only the element name. The 'hook_tag' function therefore may have to be edited. See section:- #3.4.9.\r
1422 \r
1423   Old versions of htmLawed may be available online. E.g., for version 1.0, check http://www.bioinformatics.org/phplabware/downloads/htmLawed1.zip, for 1.1.1, htmLawed111.zip, and for 1.1.10, htmLawed1110.zip.\r
1424 \r
1425 \r
1426 -- 4.6  Comparison with 'HTMLPurifier' -----------------------------o\r
1427 \r
1428 \r
1429   The HTMLPurifier PHP library by Edward Yang is a very good HTML filtering script that uses object oriented PHP code. Compared to htmLawed, it (as of year 2010):\r
1430 \r
1431   *  does not support PHP versions older than 5.0 (HTMLPurifier dropped PHP 4 support after version 2)\r
1432 \r
1433   *  is 15-20 times bigger (scores of files totalling more than 750 kb)\r
1434 \r
1435   *  consumes 10-15 times more RAM memory (just including the HTMLPurifier files without calling the filter requires a few MBs of memory)\r
1436 \r
1437   *  is expectedly slower\r
1438 \r
1439   *  does not allow admins to fully allow all valid HTML (because of incomplete HTML support, it always considers elements like 'script' illegal)\r
1440 \r
1441   *  lacks many of the extra features of htmLawed (like entity conversions and code compaction/beautification)\r
1442 \r
1443   *  has poor documentation\r
1444 \r
1445   However, HTMLPurifier has finer checks for character encodings and attribute values, and can log warnings and errors. Visit the HTMLPurifier website:- http://htmlpurifier.org for updated information.\r
1446 \r
1447 \r
1448 -- 4.7  Use through application plug-ins/modules -------------------o\r
1449 \r
1450 \r
1451   Plug-ins/modules to implement htmLawed in applications such as Drupal and DokuWiki may have been developed. Please check the application websites and the forum on the htmLawed site:- http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed.\r
1452 \r
1453 \r
1454 -- 4.8  Use in non-PHP applications --------------------------------o\r
1455 \r
1456 \r
1457   Non-PHP applications written in Python, Ruby, etc., may be able to use htmLawed through system calls to the PHP engine. Such code may have been documented on the internet. Also check the forum on the htmLawed site:- http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed.\r
1458 \r
1459 \r
1460 -- 4.9  Donate -----------------------------------------------------o\r
1461 \r
1462 \r
1463   A donation in any currency and amount to appreciate or support this software can be sent by PayPal:- http://paypal.com to this email address: drpatnaik at yahoo dot com.\r
1464 \r
1465 \r
1466 -- 4.10  Acknowledgements ------------------------------------------o\r
1467 \r
1468 \r
1469   Nicholas Alipaz, Bryan Blakey, Pádraic Brady, Dac Chartrand, Ulf Harnhammer, Gareth Heyes, Klaus Leithoff, Lukasz Pilorz, Shelley Powers, Harro Verton, Edward Yang, and many anonymous users.\r
1470 \r
1471   Thank you!\r
1472 \r
1473 \r
1474 == 5  Appendices ==================================================oo\r
1475 \r
1476 \r
1477 -- 5.1  Characters discouraged in XHTML -----------------------------\r
1478 \r
1479 \r
1480   Characters represented by the following hexadecimal code-points are `not` invalid, even though some validators may issue messages stating otherwise.\r
1481 \r
1482   '7f' to '84', '86' to '9f', 'fdd0' to 'fddf', '1fffe', '1ffff', '2fffe', '2ffff', '3fffe', '3ffff', '4fffe', '4ffff', '5fffe', '5ffff', '6fffe', '6ffff', '7fffe', '7ffff', '8fffe', '8ffff', '9fffe', '9ffff', 'afffe', 'affff', 'bfffe', 'bffff', 'cfffe', 'cffff', 'dfffe', 'dffff', 'efffe', 'effff', 'ffffe', 'fffff', '10fffe' and '10ffff'\r
1483 \r
1484 \r
1485 -- 5.2  Valid attribute-element combinations -----------------------o\r
1486 \r
1487 \r
1488   Valid attribute-element combinations as per W3C:- http://www.w3c.org specs.\r
1489 \r
1490   *  includes deprecated attributes (marked '^'), attributes for the non-standard 'embed' element (marked '*'), and the proprietary 'bordercolor' (marked '~')\r
1491   *  only non-frameset, HTML body elements\r
1492   *  'name' for 'a' and 'map', and 'lang' are invalid in XHTML 1.1\r
1493   *  'target' is valid for 'a' in XHTML 1.1 and higher\r
1494   *  'xml:space' is only for XHTML 1.1\r
1495 \r
1496   abbr - td, th\r
1497   accept - form, input\r
1498   accept-charset - form\r
1499   accesskey - a, area, button, input, label, legend, textarea\r
1500   action - form\r
1501   align - caption^, embed, applet, iframe, img^, input^, object^, legend^, table^, hr^, div^, h1^, h2^, h3^, h4^, h5^, h6^, p^, col, colgroup, tbody, td, tfoot, th, thead, tr\r
1502   alt - applet, area, img, input\r
1503   archive - applet, object\r
1504   axis - td, th\r
1505   bgcolor - embed, table^, tr^, td^, th^\r
1506   border - table, img^, object^\r
1507   bordercolor~ - table, td, tr\r
1508   cellpadding - table\r
1509   cellspacing - table\r
1510   char - col, colgroup, tbody, td, tfoot, th, thead, tr\r
1511   charoff - col, colgroup, tbody, td, tfoot, th, thead, tr\r
1512   charset - a, script\r
1513   checked - input\r
1514   cite - blockquote, q, del, ins\r
1515   classid - object\r
1516   clear - br^\r
1517   code - applet\r
1518   codebase - object, applet\r
1519   codetype - object\r
1520   color - font\r
1521   cols - textarea\r
1522   colspan - td, th\r
1523   compact - dir, dl^, menu, ol^, ul^\r
1524   coords - area, a\r
1525   data - object\r
1526   datetime - del, ins\r
1527   declare - object\r
1528   defer - script\r
1529   dir - bdo\r
1530   disabled - button, input, optgroup, option, select, textarea\r
1531   enctype - form\r
1532   face - font\r
1533   flashvars* - embed\r
1534   for - label\r
1535   frame - table\r
1536   frameborder - iframe\r
1537   headers - td, th\r
1538   height - embed, iframe, td^, th^, img, object, applet\r
1539   href - a, area\r
1540   hreflang - a\r
1541   hspace - applet, img^, object^\r
1542   ismap - img, input\r
1543   label - option, optgroup\r
1544   language - script^\r
1545   longdesc - img, iframe\r
1546   marginheight - iframe\r
1547   marginwidth - iframe\r
1548   maxlength - input\r
1549   method - form\r
1550   model* - embed\r
1551   multiple - select\r
1552   name - button, embed, textarea, applet^, select, form^, iframe^, img^, a^, input, object, map^, param\r
1553   nohref - area\r
1554   noshade - hr^\r
1555   nowrap - td^, th^\r
1556   object - applet\r
1557   onblur - a, area, button, input, label, select, textarea\r
1558   onchange - input, select, textarea\r
1559   onfocus - a, area, button, input, label, select, textarea\r
1560   onreset - form\r
1561   onselect - input, textarea\r
1562   onsubmit - form\r
1563   pluginspage* - embed\r
1564   pluginurl* - embed\r
1565   prompt - isindex\r
1566   readonly - textarea, input\r
1567   rel - a\r
1568   rev - a\r
1569   rows - textarea\r
1570   rowspan - td, th\r
1571   rules - table\r
1572   scope - td, th\r
1573   scrolling - iframe\r
1574   selected - option\r
1575   shape - area, a\r
1576   size - hr^, font, input, select\r
1577   span - col, colgroup\r
1578   src - embed, script, input, iframe, img\r
1579   standby - object\r
1580   start - ol^\r
1581   summary - table\r
1582   tabindex - a, area, button, input, object, select, textarea\r
1583   target - a^, area, form\r
1584   type - a, embed, object, param, script, input, li^, ol^, ul^, button\r
1585   usemap - img, input, object\r
1586   valign - col, colgroup, tbody, td, tfoot, th, thead, tr\r
1587   value - input, option, param, button, li^\r
1588   valuetype - param\r
1589   vspace - applet, img^, object^\r
1590   width - embed, hr^, iframe, img, object, table, td^, th^, applet, col, colgroup, pre^\r
1591   wmode - embed\r
1592   xml:space - pre, script, style\r
1593 \r
1594   These are allowed in all but the shown elements:\r
1595 \r
1596   class - param, script\r
1597   dir - applet, bdo, br, iframe, param, script\r
1598   id - script\r
1599   lang - applet, br, iframe, param, script\r
1600   onclick - applet, bdo, br, font, iframe, isindex, param, script\r
1601   ondblclick - applet, bdo, br, font, iframe, isindex, param, script\r
1602   onkeydown - applet, bdo, br, font, iframe, isindex, param, script\r
1603   onkeypress - applet, bdo, br, font, iframe, isindex, param, script\r
1604   onkeyup - applet, bdo, br, font, iframe, isindex, param, script\r
1605   onmousedown - applet, bdo, br, font, iframe, isindex, param, script\r
1606   onmousemove - applet, bdo, br, font, iframe, isindex, param, script\r
1607   onmouseout - applet, bdo, br, font, iframe, isindex, param, script\r
1608   onmouseover - applet, bdo, br, font, iframe, isindex, param, script\r
1609   onmouseup - applet, bdo, br, font, iframe, isindex, param, script\r
1610   style - param, script\r
1611   title - param, script\r
1612   xml:lang - applet, br, iframe, param, script\r
1613 \r
1614 \r
1615 -- 5.3  CSS 2.1 properties accepting URLs ------------------------o\r
1616 \r
1617 \r
1618   background\r
1619   background-image\r
1620   content\r
1621   cue-after\r
1622   cue-before\r
1623   cursor\r
1624   list-style\r
1625   list-style-image\r
1626   play-during\r
1627 \r
1628 \r
1629 -- 5.4  Microsoft Windows 1252 character replacements --------------o\r
1630 \r
1631 \r
1632   Key: 'd' double, 'l' left, 'q' quote, 'r' right, 's.' single\r
1633 \r
1634   Code-point (decimal) - hexadecimal value - replacement entity - represented character\r
1635 \r
1636   127 - 7f - (removed) - (not used)\r
1637   128 - 80 - &#8364; - euro\r
1638   129 - 81 - (removed) - (not used)\r
1639   130 - 82 - &#8218; - baseline s. q\r
1640   131 - 83 - &#402; - florin\r
1641   132 - 84 - &#8222; - baseline d q\r
1642   133 - 85 - &#8230; - ellipsis\r
1643   134 - 86 - &#8224; - dagger\r
1644   135 - 87 - &#8225; - d dagger\r
1645   136 - 88 - &#710; - circumflex accent\r
1646   137 - 89 - &#8240; - permile\r
1647   138 - 8a - &#352; - S Hacek\r
1648   139 - 8b - &#8249; - l s. guillemet\r
1649   140 - 8c - &#338; - OE ligature\r
1650   141 - 8d - (removed) - (not used)\r
1651   142 - 8e - &#381; - Z dieresis\r
1652   143 - 8f - (removed) - (not used)\r
1653   144 - 90 - (removed) - (not used)\r
1654   145 - 91 - &#8216; - l s. q\r
1655   146 - 92 - &#8217; - r s. q\r
1656   147 - 93 - &#8220; - l d q\r
1657   148 - 94 - &#8221; - r d q\r
1658   149 - 95 - &#8226; - bullet\r
1659   150 - 96 - &#8211; - en dash\r
1660   151 - 97 - &#8212; - em dash\r
1661   152 - 98 - &#732; - tilde accent\r
1662   153 - 99 - &#8482; - trademark\r
1663   154 - 9a - &#353; - s Hacek\r
1664   155 - 9b - &#8250; - r s. guillemet\r
1665   156 - 9c - &#339; - oe ligature\r
1666   157 - 9d - (removed) - (not used)\r
1667   158 - 9e - &#382; - z dieresis\r
1668   159 - 9f - &#376; - Y dieresis\r
1669 \r
1670 \r
1671 -- 5.5  URL format -------------------------------------------------o\r
1672 \r
1673 \r
1674   An `absolute` URL has a 'protocol' or 'scheme', a 'network location' or 'hostname', and, optional 'path', 'parameters', 'query' and 'fragment' segments. Thus, an absolute URL has this generic structure:\r
1675 \r
1676     (scheme) : (//network location) /(path) ;(parameters) ?(query) #(fragment)\r
1677 \r
1678   The schemes can only contain letters, digits, '+', '.' and '-'. Hostname is the portion after the '//' and up to the first '/' (if any; else, up to the end) when ':' is followed by a '//' (e.g., 'abc.com' in 'ftp://abc.com/def'); otherwise, it consists of everything after the ':' (e.g., 'def@abc.com' in mailto:def@abc.com').\r
1679 \r
1680   `Relative` URLs do not have explicit schemes and network locations; such values are inherited from a `base` URL.\r
1681 \r
1682 \r
1683 -- 5.6  Brief on htmLawed code -------------------------------------o\r
1684 \r
1685 \r
1686   Much of the code's logic and reasoning can be understood from the documentation above.\r
1687 \r
1688   The *output* of htmLawed is a text string containing the processed input. There is no custom error tracking.\r
1689 \r
1690   *Function arguments* for htmLawed are:\r
1691 \r
1692   *  '$in' - first argument; a text string; the *input text* to be processed. Any extraneous slashes added by PHP when `magic quotes` are enabled should be removed beforehand using PHP's 'stripslashes()' function.\r
1693 \r
1694   *  '$config' - second argument; an associative array; optional; named '$C' within htmLawed code. The array has keys with names like 'balance' and 'keep_bad', and the values, which can be boolean, string, or array, depending on the key, are read to accordingly set the *configurable parameters* (indicated by the keys). All configurable parameters receive some default value if the value to be used is not specified by the user through '$config'. `Finalized` '$config' is thus a filtered and possibly larger array.\r
1695 \r
1696   *  '$spec' - third argument; a text string; optional. The string has rules, written in an htmLawed-designated format, *specifying* element-specific attribute and attribute value restrictions. Function 'hl_spec()' is used to convert the string to an associative-array, named '$S' within htmLawed code, for internal use. `Finalized` '$spec' is thus an array.\r
1697 \r
1698   `Finalized` '$config' and '$spec' are made *global variables* while htmLawed is at work. Values of any pre-existing global variables with same names are noted, and their values are restored after htmLawed finishes processing the input (to capture the `finalized` values, the 'show_settings' parameter of '$config' should be used). Depending on '$config', another global variable 'hl_Ids', to track 'id' attribute values for uniqueness, may be set. Unlike the other two variables, this one is not reset (or unset) post-processing.\r
1699 \r
1700   Except for the main function 'htmLawed()' and the functions 'kses()' and 'kses_hook()', htmLawed's functions are *name-spaced* using the 'hl_' prefix. The *functions* and their roles are:\r
1701 \r
1702   *  'hl_attrval' - checking attribute values against $spec\r
1703   *  'hl_bal' - tag balancing\r
1704   *  'hl_cmtcd' - handling CDATA sections and HTML comments\r
1705   *  'hl_ent' - entity handling\r
1706   *  'hl_prot' - checking a URL scheme/protocol\r
1707   *  'hl_regex' - checking syntax of a regular expression\r
1708   *  'hl_spec' - converting user-supplied $spec value to one used by htmLawed internally\r
1709   *  'hl_tag' - handling tags\r
1710   *  'hl_tag2' - transforming tags\r
1711   *  'hl_tidy' - compact/beautify HTML \r
1712   *  'hl_version' - reporting htmLawed version\r
1713   *  'htmLawed' - main function\r
1714   *  'kses' - main function of 'kses'\r
1715   *  'kses_hook' - hook function of 'kses'\r
1716 \r
1717   The last two are for compatibility with pre-existing code using the 'kses' script. htmLawed's 'kses()' basically passes on the filtering task to 'htmLawed()' function after deciphering '$config' and '$spec' from the argument values supplied to it. 'kses_hook()' is an empty function and is meant for being filled with custom code if the 'kses' script users were using one.\r
1718 \r
1719   'htmLawed()' finalizes '$spec' (with the help of 'hl_spec()') and '$config', and globalizes them. Finalization of '$config' involves setting default values if an inappropriate or invalid one is supplied. This includes calling 'hl_regex()' to check well-formedness of regular expression patterns if such expressions are user-supplied through '$config'. 'htmLawed()' then removes invalid characters like nulls and 'x01' and appropriately handles entities using 'hl_ent()'. HTML comments and CDATA sections are identified and treated as per '$config' with the help of 'hl_cmtcd()'. When retained, the '<' and '>' characters identifying them, and the '<', '>' and '&' characters inside them, are replaced with control characters (code-points '1' to '5') till any tag balancing is completed.\r
1720 \r
1721   After this `initial processing` 'htmLawed()' identifies tags using regex and processes them with the help of 'hl_tag()' --  a large function that analyzes tag content, filtering it as per HTML standards, '$config' and '$spec'. Among other things, 'hl_tag()' transforms deprecated elements using 'hl_tag2()', removes attributes from closing tags, checks attribute values as per '$spec' rules using 'hl_attrval()', and checks URL protocols using 'hl_prot()'. 'htmLawed()' performs tag balancing and nesting checks with a call to 'hl_bal()', and optionally compacts/beautifies the output with proper white-spacing with a call to 'hl_tidy()'. The latter temporarily replaces white-space, and '<', '>' and '&' characters inside 'pre', 'script' and 'textarea' elements, and HTML comments and CDATA sections with control characters (code-points '1' to '5', and '7').\r
1722 \r
1723   htmLawed permits the use of custom code or *hook functions* at two stages. The first, called inside 'htmLawed()', allows the input text as well as the finalized '$config' and '$spec' values to be altered right after the initial processing (see section:- #3.7). The second is called by 'hl_tag()' once the tag content is finalized (see section:- #3.4.9).\r
1724 \r
1725   The functionality of htmLawed is dictated by the external HTML standard. It is thus coded for a clear-cut objective with not much concern for tweakability. The code is only minimally annotated with comments -- it is not meant to instruct; PHP developers familiar with the HTML specifications will see the logic, and others can always refer to the htmLawed documentation. The compact structuring of the statements is meant to aid a quick grasp of the logic.\r
1726 \r
1727 ___________________________________________________________________oo\r
1728 \r
1729 \r
1730 @@description: htmLawed PHP software is a free, open-source, customizable HTML input purifier and filter\r
1731 @@encoding: utf-8\r
1732 @@keywords: htmLawed, HTM, HTML, HTML Tidy, converter, filter, formatter, purifier, sanitizer, XSS, input, PHP, software, code, script, security, cross-site scripting, hack, sanitize, remove, standards, tags, attributes, elements\r
1733 @@language: en\r
1734 @@title: htmLawed documentation