<?php
/*
Plugin Name: Embed YouTube videos
Plugin URI: 
Description: Transforms YouTube URIs into embedded videos
Author: Sam
Version: 0.1
*/

$testing = true;
$start_at = '(^|\s|<p>)';
$end_at = '(\s|</p>|$)';
define('YOUTUBE_EMBED_MATCH', '@'.$start_at.'(http://(www\.)?youtube\.com/watch\?v=(\w+))'.$end_at.'@');
define('YOUTUBE_EMBED_REPLACE', '$1<embed type="application/x-shockwave-flash" src="http://youtube.com/v/$4" width="425" height="340"></embed> <a href="$2">$2</a>$5');

if (! $testing) {
	add_filter( 'pre_post', 'make_embeds' );
	add_filter( 'bb_allowed_tags', 'allow_embeds' );
	add_action( 'post_form', 'print_instructions' );
} else {
	make_embeds( 'Here is my video is already linked! <a href="http://youtube.com/watch?v=NBaPqAV_MYY">video</a>. Here is www: http://www.youtube.com/watch?v=NBaPqAV_MYY But here it is bare: http://youtube.com/watch?v=NBaPqAV_MYY and here is text in <p>http://www.youtube.com/watch?v=NBaPqAV_MYY</p>' );
	die('YouTube Embed testing finished');
}

function allow_embeds($tags) {
	$new_tags = array(
		'embed' => array(
			'height' => array(),
			'src' => array(),
			'title' => array(),
			'type' => array('application/x-shockwave-flash'),
			'width' => array(),
			)
		);
	$tags = array_merge( $tags, $new_tags );
	return $tags;
}

function make_embeds($post_text) {
	global $testing;
	if ($testing) echo "Received $post_text\n\n";
	$post_text = preg_replace( YOUTUBE_EMBED_MATCH, YOUTUBE_EMBED_REPLACE, $post_text );
	if ($testing) echo "Returning $post_text";
	return $post_text;
}

function print_instructions() {
	echo "<p>To embed a YouTube video, paste the URI (like <samp>http://youtube.com/watch?v=NBaPqAV_MYY</samp>.)</p>";
}

/*	YouTube's EMBED code
	<object width="425" height="350"><param name="movie" value="http://www.youtube.com/v/NBaPqAV_MYY"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/NBaPqAV_MYY" type="application/x-shockwave-flash" wmode="transparent" width="425" height="350"></embed></object>
*/

?>