49 lines
1.2KB

  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2014 Carsten Brandt
  4. * @license https://github.com/cebe/markdown/blob/master/LICENSE
  5. * @link https://github.com/cebe/markdown#readme
  6. */
  7. namespace cebe\markdown\inline;
  8. // work around https://github.com/facebook/hhvm/issues/1120
  9. defined('ENT_HTML401') || define('ENT_HTML401', 0);
  10. /**
  11. * Adds auto linking for URLs
  12. */
  13. trait UrlLinkTrait
  14. {
  15. /**
  16. * Parses urls and adds auto linking feature.
  17. * @marker http
  18. * @marker ftp
  19. */
  20. protected function parseUrl($markdown)
  21. {
  22. $pattern = <<<REGEXP
  23. /(?(R) # in case of recursion match parentheses
  24. \(((?>[^\s()]+)|(?R))*\)
  25. | # else match a link with title
  26. ^(https?|ftp):\/\/(([^\s()]+)|(?R))+(?<![\.,:;\'"!\?\s])
  27. )/x
  28. REGEXP;
  29. if (!in_array('parseLink', $this->context) && preg_match($pattern, $markdown, $matches)) {
  30. return [
  31. ['autoUrl', $matches[0]],
  32. strlen($matches[0])
  33. ];
  34. }
  35. return [['text', substr($markdown, 0, 4)], 4];
  36. }
  37. protected function renderAutoUrl($block)
  38. {
  39. $href = htmlspecialchars($block[1], ENT_COMPAT | ENT_HTML401, 'UTF-8');
  40. $text = htmlspecialchars(urldecode($block[1]), ENT_NOQUOTES | ENT_SUBSTITUTE, 'UTF-8');
  41. return "<a href=\"$href\">$text</a>";
  42. }
  43. }