PurifierLinkify.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /**
  3. * Injector that converts configuration directive syntax %Namespace.Directive
  4. * to links
  5. */
  6. class HTMLPurifier_Injector_PurifierLinkify extends HTMLPurifier_Injector
  7. {
  8. /**
  9. * @type string
  10. */
  11. public $name = 'PurifierLinkify';
  12. /**
  13. * @type string
  14. */
  15. public $docURL;
  16. /**
  17. * @type array
  18. */
  19. public $needed = array('a' => array('href'));
  20. /**
  21. * @param HTMLPurifier_Config $config
  22. * @param HTMLPurifier_Context $context
  23. * @return string
  24. */
  25. public function prepare($config, $context)
  26. {
  27. $this->docURL = $config->get('AutoFormat.PurifierLinkify.DocURL');
  28. return parent::prepare($config, $context);
  29. }
  30. /**
  31. * @param HTMLPurifier_Token $token
  32. */
  33. public function handleText(&$token)
  34. {
  35. if (!$this->allowsElement('a')) {
  36. return;
  37. }
  38. if (strpos($token->data, '%') === false) {
  39. return;
  40. }
  41. $bits = preg_split('#%([a-z0-9]+\.[a-z0-9]+)#Si', $token->data, -1, PREG_SPLIT_DELIM_CAPTURE);
  42. $token = array();
  43. // $i = index
  44. // $c = count
  45. // $l = is link
  46. for ($i = 0, $c = count($bits), $l = false; $i < $c; $i++, $l = !$l) {
  47. if (!$l) {
  48. if ($bits[$i] === '') {
  49. continue;
  50. }
  51. $token[] = new HTMLPurifier_Token_Text($bits[$i]);
  52. } else {
  53. $token[] = new HTMLPurifier_Token_Start(
  54. 'a',
  55. array('href' => str_replace('%s', $bits[$i], $this->docURL))
  56. );
  57. $token[] = new HTMLPurifier_Token_Text('%' . $bits[$i]);
  58. $token[] = new HTMLPurifier_Token_End('a');
  59. }
  60. }
  61. }
  62. }
  63. // vim: et sw=4 sts=4