Fix back-compat regressions. Also, compactify configuration code.
[htmlpurifier.git] / library / HTMLPurifier / AttrDef / CSS / FontFamily.php
blob22f4c6de59f23620b94ca241ce3bd0d41ecb879d
1 <?php
3 /**
4 * Validates a font family list according to CSS spec
5 * @todo whitelisting allowed fonts would be nice
6 */
7 class HTMLPurifier_AttrDef_CSS_FontFamily extends HTMLPurifier_AttrDef
10 public function validate($string, $config, $context) {
11 static $generic_names = array(
12 'serif' => true,
13 'sans-serif' => true,
14 'monospace' => true,
15 'fantasy' => true,
16 'cursive' => true
19 // assume that no font names contain commas in them
20 $fonts = explode(',', $string);
21 $final = '';
22 $non_sgml = HTMLPurifier_Encoder::getNonSgmlCharacters();
23 foreach($fonts as $font) {
24 $font = trim($font);
25 if ($font === '') continue;
26 // match a generic name
27 if (isset($generic_names[$font])) {
28 $final .= $font . ', ';
29 continue;
31 // match a quoted name
32 if ($font[0] === '"' || $font[0] === "'") {
33 $length = strlen($font);
34 if ($length <= 2) continue;
35 $quote = $font[0];
36 if ($font[$length - 1] !== $quote) continue;
37 $font = substr($font, 1, $length - 2);
39 $new_font = '';
40 for ($i = 0, $c = strlen($font); $i < $c; $i++) {
41 if ($font[$i] === '\\') {
42 $i++;
43 if ($i >= $c) {
44 $new_font .= '\\';
45 break;
47 if (ctype_xdigit($font[$i])) {
48 $code = $font[$i];
49 for ($a = 1, $i++; $i < $c && $a < 6; $i++, $a++) {
50 if (!ctype_xdigit($font[$i])) break;
51 $code .= $font[$i];
53 $char = HTMLPurifier_Encoder::unichr(hexdec($code));
54 if (isset($non_sgml[$char])) continue;
55 $new_font .= $char;
56 if ($i < $c && trim($font[$i]) !== '') $i--;
57 continue;
59 if ($font[$i] === "\n") continue;
61 $new_font .= $font[$i];
64 $font = $new_font;
66 // $font is a pure representation of the font name
68 if (ctype_alnum($font) && $font !== '') {
69 // very simple font, allow it in unharmed
70 $final .= $font . ', ';
71 continue;
74 // complicated font, requires quoting
76 // armor single quotes and new lines
77 $font = str_replace("\\", "\\\\", $font);
78 $font = str_replace("'", "\\'", $font);
79 $final .= "'$font', ";
81 $final = rtrim($final, ', ');
82 if ($final === '') return false;
83 return $final;