TargetBlank.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php
  2. // must be called POST validation
  3. /**
  4. * Adds target="blank" to all outbound links. This transform is
  5. * only attached if Attr.TargetBlank is TRUE. This works regardless
  6. * of whether or not Attr.AllowedFrameTargets
  7. */
  8. class HTMLPurifier_AttrTransform_TargetBlank extends HTMLPurifier_AttrTransform
  9. {
  10. /**
  11. * @type HTMLPurifier_URIParser
  12. */
  13. private $parser;
  14. public function __construct()
  15. {
  16. $this->parser = new HTMLPurifier_URIParser();
  17. }
  18. /**
  19. * @param array $attr
  20. * @param HTMLPurifier_Config $config
  21. * @param HTMLPurifier_Context $context
  22. * @return array
  23. */
  24. public function transform($attr, $config, $context)
  25. {
  26. if (!isset($attr['href'])) {
  27. return $attr;
  28. }
  29. // XXX Kind of inefficient
  30. $url = $this->parser->parse($attr['href']);
  31. // Ignore invalid schemes (e.g. `javascript:`)
  32. if (!($scheme = $url->getSchemeObj($config, $context))) {
  33. return $attr;
  34. }
  35. if ($scheme->browsable && !$url->isBenign($config, $context)) {
  36. $attr['target'] = '_blank';
  37. }
  38. return $attr;
  39. }
  40. }
  41. // vim: et sw=4 sts=4