Linkify.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. // We use this regex:
  31. // https://gist.github.com/gruber/249502
  32. // but with @cscott's backtracking fix and also
  33. // the Unicode characters un-Unicodified.
  34. $bits = preg_split(
  35. '/\\b((?:[a-z][\\w\\-]+:(?:\\/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}\\/)(?:[^\\s()<>]|\\((?:[^\\s()<>]|(?:\\([^\\s()<>]+\\)))*\\))+(?:\\((?:[^\\s()<>]|(?:\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:\'".,<>?\x{00ab}\x{00bb}\x{201c}\x{201d}\x{2018}\x{2019}]))/iu',
  36. $token->data, -1, PREG_SPLIT_DELIM_CAPTURE);
  37. $token = array();
  38. // $i = index
  39. // $c = count
  40. // $l = is link
  41. for ($i = 0, $c = count($bits), $l = false; $i < $c; $i++, $l = !$l) {
  42. if (!$l) {
  43. if ($bits[$i] === '') {
  44. continue;
  45. }
  46. $token[] = new HTMLPurifier_Token_Text($bits[$i]);
  47. } else {
  48. $token[] = new HTMLPurifier_Token_Start('a', array('href' => $bits[$i]));
  49. $token[] = new HTMLPurifier_Token_Text($bits[$i]);
  50. $token[] = new HTMLPurifier_Token_End('a');
  51. }
  52. }
  53. }
  54. }
  55. // vim: et sw=4 sts=4