4 * Implements data: URI for base64 encoded images supported by GD.
6 class HTMLPurifier_URIScheme_data extends HTMLPurifier_URIScheme {
8 public $browsable = true;
9 public $allowed_types = array(
10 // you better write validation code for other types if you
11 // decide to allow them
17 public function validate(&$uri, $config, $context) {
18 $result = explode(',', $uri->path, 2);
22 if (count($result) == 2) {
23 list($metadata, $data) = $result;
24 // do some legwork on the metadata
25 $metas = explode(';', $metadata);
26 while(!empty($metas)) {
27 $cur = array_shift($metas);
28 if ($cur == 'base64') {
32 if (substr($cur, 0, 8) == 'charset=') {
33 // doesn't match if there are arbitrary spaces, but
35 if ($charset !== null) continue; // garbage
36 $charset = substr($cur, 8); // not used
38 if ($content_type !== null) continue; // garbage
45 if ($content_type !== null && empty($this->allowed_types[$content_type])) {
48 if ($charset !== null) {
49 // error; we don't allow plaintext stuff
52 $data = rawurldecode($data);
54 $raw_data = base64_decode($data);
58 // XXX probably want to refactor this into a general mechanism
59 // for filtering arbitrary content types
60 $file = tempnam("/tmp", "");
61 file_put_contents($file, $raw_data);
62 if (function_exists('exif_imagetype')) {
63 $image_code = exif_imagetype($file);
64 } elseif (function_exists('getimagesize')) {
65 set_error_handler(array($this, 'muteErrorHandler'));
66 $info = getimagesize($file);
67 restore_error_handler();
68 if ($info == false) return false;
69 $image_code = $info[2];
71 trigger_error("could not find exif_imagetype or getimagesize functions", E_USER_ERROR);
73 $real_content_type = image_type_to_mime_type($image_code);
74 if ($real_content_type != $content_type) {
75 // we're nice guys; if the content type is something else we
76 // support, change it over
77 if (empty($this->allowed_types[$real_content_type])) return false;
78 $content_type = $real_content_type;
80 // ok, it's kosher, rewrite what we need
81 $uri->userinfo = null;
84 $uri->fragment = null;
86 $uri->path = "$content_type;base64," . base64_encode($raw_data);
90 public function muteErrorHandler($errno, $errstr) {}