Implement CSS.AllowedFonts.
[htmlpurifier/bfroehle.git] / library / HTMLPurifier / AttrDef / CSS / FontFamily.php
blobc29834b686d0daabb20cb8e263d22deea9a47755
1 <?php
3 /**
4 * Validates a font family list according to CSS spec
5 */
6 class HTMLPurifier_AttrDef_CSS_FontFamily extends HTMLPurifier_AttrDef
9 public function validate($string, $config, $context) {
10 static $generic_names = array(
11 'serif' => true,
12 'sans-serif' => true,
13 'monospace' => true,
14 'fantasy' => true,
15 'cursive' => true
17 $allowed_fonts = $config->get('CSS.AllowedFonts');
19 // assume that no font names contain commas in them
20 $fonts = explode(',', $string);
21 $final = '';
22 foreach($fonts as $font) {
23 $font = trim($font);
24 if ($font === '') continue;
25 // match a generic name
26 if (isset($generic_names[$font])) {
27 if ($allowed_fonts === null || isset($allowed_fonts[$font])) {
28 $final .= $font . ', ';
30 continue;
32 // match a quoted name
33 if ($font[0] === '"' || $font[0] === "'") {
34 $length = strlen($font);
35 if ($length <= 2) continue;
36 $quote = $font[0];
37 if ($font[$length - 1] !== $quote) continue;
38 $font = substr($font, 1, $length - 2);
41 $font = $this->expandCSSEscape($font);
43 // $font is a pure representation of the font name
45 if ($allowed_fonts !== null && !isset($allowed_fonts[$font])) {
46 continue;
49 if (ctype_alnum($font) && $font !== '') {
50 // very simple font, allow it in unharmed
51 $final .= $font . ', ';
52 continue;
55 // bugger out on whitespace. form feed (0C) really
56 // shouldn't show up regardless
57 $font = str_replace(array("\n", "\t", "\r", "\x0C"), ' ', $font);
59 // These ugly transforms don't pose a security
60 // risk (as \\ and \" might). We could try to be clever and
61 // use single-quote wrapping when there is a double quote
62 // present, but I have choosen not to implement that.
63 // (warning: this code relies on the selection of quotation
64 // mark below)
65 $font = str_replace('\\', '\\5C ', $font);
66 $font = str_replace('"', '\\22 ', $font);
68 // complicated font, requires quoting
69 $final .= "\"$font\", "; // note that this will later get turned into &quot;
71 $final = rtrim($final, ', ');
72 if ($final === '') return false;
73 return $final;
78 // vim: et sw=4 sts=4