Don't add nofollow for matching hosts, generalize this code.
[htmlpurifier.git] / library / HTMLPurifier / URIFilter / Munge.php
blob448f76463e552828856006b16f12e9f9ddfd11ef
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 (!$scheme_obj->browsable) return true; // ignore non-browseable schemes
25 // don't redirect if target host is our host
26 if ($uri->isLocal($config, $context)) {
27 $uri_definition = $config->getDefinition('URI');
28 // but do redirect if we're currently on a secure scheme,
29 // and the target scheme is insecure
30 $current_scheme_obj = HTMLPurifier_URISchemeRegistry::instance()->getScheme($uri_definition->defaultScheme, $config, $context);
31 if ($scheme_obj->secure || !$current_scheme_obj->secure) {
32 return true;
34 // target scheme was not secure, but we were secure
37 $this->makeReplace($uri, $config, $context);
38 $this->replace = array_map('rawurlencode', $this->replace);
40 $new_uri = strtr($this->target, $this->replace);
41 $new_uri = $this->parser->parse($new_uri);
42 // don't redirect if the target host is the same as the
43 // starting host
44 if ($uri->host === $new_uri->host) return true;
45 $uri = $new_uri; // overwrite
46 return true;
49 protected function makeReplace($uri, $config, $context) {
50 $string = $uri->toString();
51 // always available
52 $this->replace['%s'] = $string;
53 $this->replace['%r'] = $context->get('EmbeddedURI', true);
54 $token = $context->get('CurrentToken', true);
55 $this->replace['%n'] = $token ? $token->name : null;
56 $this->replace['%m'] = $context->get('CurrentAttr', true);
57 $this->replace['%p'] = $context->get('CurrentCSSProperty', true);
58 // not always available
59 if ($this->secretKey) $this->replace['%t'] = sha1($this->secretKey . ':' . $string);
64 // vim: et sw=4 sts=4