BxDolHTMLPurifierFilterYoutubeIframe.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. <?php
  2. class BxDolHTMLPurifierFilterYoutubeIframe extends HTMLPurifier_Filter
  3. {
  4. public $name = 'YouTubeIframe';
  5. public function preFilter($html, $config, $context)
  6. {
  7. if (strstr($html, '<iframe') && (strstr($html, 'youtube.com') || strstr($html, 'youtu.be') || strstr($html, 'youtube-nocookie.com'))) {
  8. $html = str_ireplace("</iframe>", "", $html);
  9. if (preg_match_all("/<iframe(.*?)>/si", $html, $result)) {
  10. foreach ($result[1] as $key => $item) {
  11. preg_match('/width="([0-9]+)"/', $item, $width);
  12. $width = $width[1];
  13. preg_match('/height="([0-9]+)"/', $item, $height);
  14. $height = $height[1];
  15. if (preg_match('/((\/\/www\.youtube\.com\/embed\/)|(\/\/www\.youtube-nocookie\.com\/embed\/)|(\/\/www.youtube.com\/v\/))([a-zA-Z0-9_-]+)/', $item, $id)) {
  16. $id = $id[5];
  17. $sProto = 0 == strncmp('https', BX_DOL_URL_ROOT, 5) ? 'https' : 'http';
  18. $html = str_replace($result[0][$key], '<img class="YouTubeIframe" width="' . $width . '" height="' . $height . '" src="' . $sProto . '://www.youtube-nocookie.com/embed/' . $id . '?rel=0">', $html);
  19. }
  20. }
  21. }
  22. }
  23. return $html;
  24. }
  25. public function postFilter($html, $config, $context)
  26. {
  27. $post_regex = '#<img class="YouTubeIframe" ([^>]+)>#';
  28. $html = preg_replace_callback($post_regex, array($this, 'postFilterCallback'), $html);
  29. return $html;
  30. }
  31. protected function postFilterCallback($matches)
  32. {
  33. return '<iframe frameborder="0" allowfullscreen ' . $matches[1] . '></iframe>';
  34. }
  35. }