You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
1.6KB

  1. <?php
  2. /**
  3. * Injector that converts http, https and ftp text URLs to actual links.
  4. */
  5. class HTMLPurifier_Injector_Linkify extends HTMLPurifier_Injector
  6. {
  7. /**
  8. * @type string
  9. */
  10. public $name = 'Linkify';
  11. /**
  12. * @type array
  13. */
  14. public $needed = array('a' => array('href'));
  15. /**
  16. * @param HTMLPurifier_Token $token
  17. */
  18. public function handleText(&$token)
  19. {
  20. if (!$this->allowsElement('a')) {
  21. return;
  22. }
  23. if (strpos($token->data, '://') === false) {
  24. // our really quick heuristic failed, abort
  25. // this may not work so well if we want to match things like
  26. // "google.com", but then again, most people don't
  27. return;
  28. }
  29. // there is/are URL(s). Let's split the string:
  30. // Note: this regex is extremely permissive
  31. $bits = preg_split('#((?:https?|ftp)://[^\s\'",<>()]+)#Su', $token->data, -1, PREG_SPLIT_DELIM_CAPTURE);
  32. $token = array();
  33. // $i = index
  34. // $c = count
  35. // $l = is link
  36. for ($i = 0, $c = count($bits), $l = false; $i < $c; $i++, $l = !$l) {
  37. if (!$l) {
  38. if ($bits[$i] === '') {
  39. continue;
  40. }
  41. $token[] = new HTMLPurifier_Token_Text($bits[$i]);
  42. } else {
  43. $token[] = new HTMLPurifier_Token_Start('a', array('href' => $bits[$i]));
  44. $token[] = new HTMLPurifier_Token_Text($bits[$i]);
  45. $token[] = new HTMLPurifier_Token_End('a');
  46. }
  47. }
  48. }
  49. }
  50. // vim: et sw=4 sts=4