1 : <?php
2 :
3 : /**
4 : * Validates a font family list according to CSS spec
5 : * @todo whitelisting allowed fonts would be nice
6 : */
7 1 : class HTMLPurifier_AttrDef_CSS_FontFamily extends HTMLPurifier_AttrDef
8 : {
9 :
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
17 0 : );
18 :
19 : // assume that no font names contain commas in them
20 0 : $fonts = explode(',', $string);
21 0 : $final = '';
22 0 : foreach($fonts as $font) {
23 0 : $font = trim($font);
24 0 : if ($font === '') continue;
25 : // match a generic name
26 0 : if (isset($generic_names[$font])) {
27 0 : $final .= $font . ', ';
28 0 : continue;
29 0 : }
30 : // match a quoted name
31 0 : if ($font[0] === '"' || $font[0] === "'") {
32 0 : $length = strlen($font);
33 0 : if ($length <= 2) continue;
34 0 : $quote = $font[0];
35 0 : if ($font[$length - 1] !== $quote) continue;
36 0 : $font = substr($font, 1, $length - 2);
37 :
38 0 : $new_font = '';
39 0 : for ($i = 0, $c = strlen($font); $i < $c; $i++) {
40 0 : if ($font[$i] === '\\') {
41 0 : $i++;
42 0 : if ($i >= $c) {
43 0 : $new_font .= '\\';
44 0 : break;
45 0 : }
46 0 : if (ctype_xdigit($font[$i])) {
47 0 : $code = $font[$i];
48 0 : for ($a = 1, $i++; $i < $c && $a < 6; $i++, $a++) {
49 0 : if (!ctype_xdigit($font[$i])) break;
50 0 : $code .= $font[$i];
51 0 : }
52 : // We have to be extremely careful when adding
53 : // new characters, to make sure we're not breaking
54 : // the encoding.
55 0 : $char = HTMLPurifier_Encoder::unichr(hexdec($code));
56 0 : if (HTMLPurifier_Encoder::cleanUTF8($char) === '') continue;
57 0 : $new_font .= $char;
58 0 : if ($i < $c && trim($font[$i]) !== '') $i--;
59 0 : continue;
60 0 : }
61 0 : if ($font[$i] === "\n") continue;
62 0 : }
63 0 : $new_font .= $font[$i];
64 0 : }
65 :
66 0 : $font = $new_font;
67 0 : }
68 : // $font is a pure representation of the font name
69 :
70 0 : if (ctype_alnum($font) && $font !== '') {
71 : // very simple font, allow it in unharmed
72 0 : $final .= $font . ', ';
73 0 : continue;
74 0 : }
75 :
76 : // complicated font, requires quoting
77 :
78 : // armor single quotes and new lines
79 0 : $font = str_replace("\\", "\\\\", $font);
80 0 : $font = str_replace("'", "\\'", $font);
81 0 : $final .= "'$font', ";
82 0 : }
83 0 : $final = rtrim($final, ', ');
84 0 : if ($final === '') return false;
85 0 : return $final;
86 : }
87 :
88 : }
89 :
|