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
16 // this is actually irrelevant since we only write out the path
18 public $may_omit_host = true;
20 public function doValidate(&$uri, $config, $context) {
21 $result = explode(',', $uri->path
, 2);
25 if (count($result) == 2) {
26 list($metadata, $data) = $result;
27 // do some legwork on the metadata
28 $metas = explode(';', $metadata);
29 while(!empty($metas)) {
30 $cur = array_shift($metas);
31 if ($cur == 'base64') {
35 if (substr($cur, 0, 8) == 'charset=') {
36 // doesn't match if there are arbitrary spaces, but
38 if ($charset !== null) continue; // garbage
39 $charset = substr($cur, 8); // not used
41 if ($content_type !== null) continue; // garbage
48 if ($content_type !== null && empty($this->allowed_types
[$content_type])) {
51 if ($charset !== null) {
52 // error; we don't allow plaintext stuff
55 $data = rawurldecode($data);
57 $raw_data = base64_decode($data);
61 // XXX probably want to refactor this into a general mechanism
62 // for filtering arbitrary content types
63 $file = tempnam("/tmp", "");
64 file_put_contents($file, $raw_data);
65 if (function_exists('exif_imagetype')) {
66 $image_code = exif_imagetype($file);
67 } elseif (function_exists('getimagesize')) {
68 set_error_handler(array($this, 'muteErrorHandler'));
69 $info = getimagesize($file);
70 restore_error_handler();
71 if ($info == false) return false;
72 $image_code = $info[2];
74 trigger_error("could not find exif_imagetype or getimagesize functions", E_USER_ERROR
);
76 $real_content_type = image_type_to_mime_type($image_code);
77 if ($real_content_type != $content_type) {
78 // we're nice guys; if the content type is something else we
79 // support, change it over
80 if (empty($this->allowed_types
[$real_content_type])) return false;
81 $content_type = $real_content_type;
83 // ok, it's kosher, rewrite what we need
84 $uri->userinfo
= null;
87 $uri->fragment
= null;
89 $uri->path
= "$content_type;base64," . base64_encode($raw_data);
93 public function muteErrorHandler($errno, $errstr) {}