BxDolHTMLPurifierFilterYouTube.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. class BxDolHTMLPurifierFilterYouTube extends HTMLPurifier_Filter
  3. {
  4. /**
  5. * @type string
  6. */
  7. public $name = 'YouTube';
  8. /**
  9. * @param string $html
  10. * @param HTMLPurifier_Config $config
  11. * @param HTMLPurifier_Context $context
  12. * @return string
  13. */
  14. public function preFilter($html, $config, $context)
  15. {
  16. $pre_regex = '#<object[^>]+>.+?' .
  17. '(?:http:)?//www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s';
  18. $pre_replace = '<span class="youtube-embed">\1</span>';
  19. return preg_replace($pre_regex, $pre_replace, $html);
  20. }
  21. /**
  22. * @param string $html
  23. * @param HTMLPurifier_Config $config
  24. * @param HTMLPurifier_Context $context
  25. * @return string
  26. */
  27. public function postFilter($html, $config, $context)
  28. {
  29. $post_regex = '#<span class="youtube-embed">((?:v|cp)/[A-Za-z0-9\-_=]+)</span>#';
  30. return preg_replace_callback($post_regex, array($this, 'postFilterCallback'), $html);
  31. }
  32. /**
  33. * @param $url
  34. * @return string
  35. */
  36. protected function armorUrl($url)
  37. {
  38. return str_replace('--', '-&#45;', $url);
  39. }
  40. /**
  41. * @param array $matches
  42. * @return string
  43. */
  44. protected function postFilterCallback($matches)
  45. {
  46. $url = $this->armorUrl($matches[1]);
  47. return '<object width="425" height="350" type="application/x-shockwave-flash" ' .
  48. 'data="//www.youtube.com/' . $url . '">' .
  49. '<param name="movie" value="//www.youtube.com/' . $url . '"></param>' .
  50. '<!--[if IE]>' .
  51. '<embed src="//www.youtube.com/' . $url . '"' .
  52. 'type="application/x-shockwave-flash"' .
  53. 'wmode="transparent" width="425" height="350" />' .
  54. '<![endif]-->' .
  55. '</object>';
  56. }
  57. }
  58. // vim: et sw=4 sts=4