URI.Munge munges https to http URIs.
[htmlpurifier.git] / library / HTMLPurifier / URIFilter / Munge.php
blob40d059b24bede57eace4b92d1ec8ecc4d0b3f23f
1 <?php
3 class HTMLPurifier_URIFilter_Munge extends HTMLPurifier_URIFilter
5 public $name = 'Munge';
6 public $post = true;
7 private $target, $parser, $doEmbed, $secretKey;
9 protected $replace = array();
11 public function prepare($config) {
12 $this->target = $config->get('URI.' . $this->name);
13 $this->parser = new HTMLPurifier_URIParser();
14 $this->doEmbed = $config->get('URI.MungeResources');
15 $this->secretKey = $config->get('URI.MungeSecretKey');
16 return true;
18 public function filter(&$uri, $config, $context) {
19 if ($context->get('EmbeddedURI', true) && !$this->doEmbed) return true;
21 $scheme_obj = $uri->getSchemeObj($config, $context);
22 if (!$scheme_obj) return true; // ignore unknown schemes, maybe another postfilter did it
23 if (is_null($uri->host) || empty($scheme_obj->browsable)) {
24 return true;
26 $uri_definition = $config->getDefinition('URI');
27 // don't redirect if target host is our host
28 if ($uri->host === $uri_definition->host) {
29 // but do redirect if we're currently on a secure scheme,
30 // and the target scheme is insecure
31 $current_scheme_obj = HTMLPurifier_URISchemeRegistry::instance()->getScheme($uri_definition->defaultScheme, $config, $context);
32 if ($scheme_obj->secure || !$current_scheme_obj->secure) {
33 return true;
35 // target scheme was not secure, but we were secure
38 $this->makeReplace($uri, $config, $context);
39 $this->replace = array_map('rawurlencode', $this->replace);
41 $new_uri = strtr($this->target, $this->replace);
42 $new_uri = $this->parser->parse($new_uri);
43 // don't redirect if the target host is the same as the
44 // starting host
45 if ($uri->host === $new_uri->host) return true;
46 $uri = $new_uri; // overwrite
47 return true;
50 protected function makeReplace($uri, $config, $context) {
51 $string = $uri->toString();
52 // always available
53 $this->replace['%s'] = $string;
54 $this->replace['%r'] = $context->get('EmbeddedURI', true);
55 $token = $context->get('CurrentToken', true);
56 $this->replace['%n'] = $token ? $token->name : null;
57 $this->replace['%m'] = $context->get('CurrentAttr', true);
58 $this->replace['%p'] = $context->get('CurrentCSSProperty', true);
59 // not always available
60 if ($this->secretKey) $this->replace['%t'] = sha1($this->secretKey . ':' . $string);
65 // vim: et sw=4 sts=4