File indexing completed on 2024-05-12 06:02:04

0001 <?php
0002 
0003 class HTMLPurifier_Filter_YouTube extends HTMLPurifier_Filter
0004 {
0005 
0006     /**
0007      * @type string
0008      */
0009     public $name = 'YouTube';
0010 
0011     /**
0012      * @param string $html
0013      * @param HTMLPurifier_Config $config
0014      * @param HTMLPurifier_Context $context
0015      * @return string
0016      */
0017     public function preFilter($html, $config, $context)
0018     {
0019         $pre_regex = '#<object[^>]+>.+?' .
0020             '(?:http:)?//www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s';
0021         $pre_replace = '<span class="youtube-embed">\1</span>';
0022         return preg_replace($pre_regex, $pre_replace, $html);
0023     }
0024 
0025     /**
0026      * @param string $html
0027      * @param HTMLPurifier_Config $config
0028      * @param HTMLPurifier_Context $context
0029      * @return string
0030      */
0031     public function postFilter($html, $config, $context)
0032     {
0033         $post_regex = '#<span class="youtube-embed">((?:v|cp)/[A-Za-z0-9\-_=]+)</span>#';
0034         return preg_replace_callback($post_regex, array($this, 'postFilterCallback'), $html);
0035     }
0036 
0037     /**
0038      * @param $url
0039      * @return string
0040      */
0041     protected function armorUrl($url)
0042     {
0043         return str_replace('--', '-&#45;', $url);
0044     }
0045 
0046     /**
0047      * @param array $matches
0048      * @return string
0049      */
0050     protected function postFilterCallback($matches)
0051     {
0052         $url = $this->armorUrl($matches[1]);
0053         return '<object width="425" height="350" type="application/x-shockwave-flash" ' .
0054         'data="//www.youtube.com/' . $url . '">' .
0055         '<param name="movie" value="//www.youtube.com/' . $url . '"></param>' .
0056         '<!--[if IE]>' .
0057         '<embed src="//www.youtube.com/' . $url . '"' .
0058         'type="application/x-shockwave-flash"' .
0059         'wmode="transparent" width="425" height="350" />' .
0060         '<![endif]-->' .
0061         '</object>';
0062     }
0063 }
0064 
0065 // vim: et sw=4 sts=4