Linkify.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. if ($bits === false) {
  38. return;
  39. }
  40. $token = array();
  41. // $i = index
  42. // $c = count
  43. // $l = is link
  44. for ($i = 0, $c = count($bits), $l = false; $i < $c; $i++, $l = !$l) {
  45. if (!$l) {
  46. if ($bits[$i] === '') {
  47. continue;
  48. }
  49. $token[] = new HTMLPurifier_Token_Text($bits[$i]);
  50. } else {
  51. $token[] = new HTMLPurifier_Token_Start('a', array('href' => $bits[$i]));
  52. $token[] = new HTMLPurifier_Token_Text($bits[$i]);
  53. $token[] = new HTMLPurifier_Token_End('a');
  54. }
  55. }
  56. }
  57. }
  58. // vim: et sw=4 sts=4