--- /dev/null
+<?php\r
+\r
+class HTMLPurifier_URIFilter_Munge extends HTMLPurifier_URIFilter\r
+{\r
+ /**\r
+ * @type string\r
+ */\r
+ public $name = 'Munge';\r
+\r
+ /**\r
+ * @type bool\r
+ */\r
+ public $post = true;\r
+\r
+ /**\r
+ * @type string\r
+ */\r
+ private $target;\r
+\r
+ /**\r
+ * @type HTMLPurifier_URIParser\r
+ */\r
+ private $parser;\r
+\r
+ /**\r
+ * @type bool\r
+ */\r
+ private $doEmbed;\r
+\r
+ /**\r
+ * @type string\r
+ */\r
+ private $secretKey;\r
+\r
+ /**\r
+ * @type array\r
+ */\r
+ protected $replace = array();\r
+\r
+ /**\r
+ * @param HTMLPurifier_Config $config\r
+ * @return bool\r
+ */\r
+ public function prepare($config)\r
+ {\r
+ $this->target = $config->get('URI.' . $this->name);\r
+ $this->parser = new HTMLPurifier_URIParser();\r
+ $this->doEmbed = $config->get('URI.MungeResources');\r
+ $this->secretKey = $config->get('URI.MungeSecretKey');\r
+ if ($this->secretKey && !function_exists('hash_hmac')) {\r
+ throw new Exception("Cannot use %URI.MungeSecretKey without hash_hmac support.");\r
+ }\r
+ return true;\r
+ }\r
+\r
+ /**\r
+ * @param HTMLPurifier_URI $uri\r
+ * @param HTMLPurifier_Config $config\r
+ * @param HTMLPurifier_Context $context\r
+ * @return bool\r
+ */\r
+ public function filter(&$uri, $config, $context)\r
+ {\r
+ if ($context->get('EmbeddedURI', true) && !$this->doEmbed) {\r
+ return true;\r
+ }\r
+\r
+ $scheme_obj = $uri->getSchemeObj($config, $context);\r
+ if (!$scheme_obj) {\r
+ return true;\r
+ } // ignore unknown schemes, maybe another postfilter did it\r
+ if (!$scheme_obj->browsable) {\r
+ return true;\r
+ } // ignore non-browseable schemes, since we can't munge those in a reasonable way\r
+ if ($uri->isBenign($config, $context)) {\r
+ return true;\r
+ } // don't redirect if a benign URL\r
+\r
+ $this->makeReplace($uri, $config, $context);\r
+ $this->replace = array_map('rawurlencode', $this->replace);\r
+\r
+ $new_uri = strtr($this->target, $this->replace);\r
+ $new_uri = $this->parser->parse($new_uri);\r
+ // don't redirect if the target host is the same as the\r
+ // starting host\r
+ if ($uri->host === $new_uri->host) {\r
+ return true;\r
+ }\r
+ $uri = $new_uri; // overwrite\r
+ return true;\r
+ }\r
+\r
+ /**\r
+ * @param HTMLPurifier_URI $uri\r
+ * @param HTMLPurifier_Config $config\r
+ * @param HTMLPurifier_Context $context\r
+ */\r
+ protected function makeReplace($uri, $config, $context)\r
+ {\r
+ $string = $uri->toString();\r
+ // always available\r
+ $this->replace['%s'] = $string;\r
+ $this->replace['%r'] = $context->get('EmbeddedURI', true);\r
+ $token = $context->get('CurrentToken', true);\r
+ $this->replace['%n'] = $token ? $token->name : null;\r
+ $this->replace['%m'] = $context->get('CurrentAttr', true);\r
+ $this->replace['%p'] = $context->get('CurrentCSSProperty', true);\r
+ // not always available\r
+ if ($this->secretKey) {\r
+ $this->replace['%t'] = hash_hmac("sha256", $string, $this->secretKey);\r
+ }\r
+ }\r
+}\r
+\r
+// vim: et sw=4 sts=4\r