<?php
/* REGISTER FLASH GAME ACTIVATION
Name: swfObject Reloaded
Plugin URI: http://www.codeandreload.com/wp-plugins/swfobjectreloaded
Description: This plugin allows easy embedding of swf files and better media management for swf files, allowing swf files to have a height, width, and their own minimum flash version.  This plugin adds a swfobject shortcode that can be inserted via the "Add media" button while editing a post.  SWF files are now also automatically embedded on their respective attachment pages.
Author: Robert Wise
Version: 1.5
Author URI: http://www.codeandreload.com */
/* http://www.adobe.com/devnet/flashplayer/articles/swfobject.html */
/* http://code.google.com/p/swfobject/wiki/documentation */

    register_activation_hook( __FILE__, 'tigu_swf_activate' );

    function tigu_head() {
    if ( !is_admin() ) {
  // don't do this for admin pages.
    wp_enqueue_script("swfobject");
  }
  }
  function is_int_id ($id) {
  return is_numeric("".$id);
  }
    add_action('init', 'tigu_head');

function eg_settings_api_init() {
 	// Add the section to reading settings so we can add our fields to it
 	add_settings_section('tigu_setting_section', '<hr />' . __("<font color='#fb2900'>Flash Game Settings</font>"), 'tigu_setting_section_callback_function', 'media');

 	// Add the field with the names and function to use for our new settings, put it in our new section
 	add_settings_field('tigu_setting_name', __('Scale Flash content (while preserving aspect ratio)', 'Gameleon'), 'tigu_setting_callback_function', 'media', 'tigu_setting_section');
 	add_settings_field('tigu_iphone_setting_name', __('iPhone Alternate content', 'Gameleon'), 'tigu_iphone_callback_function', 'media', 'tigu_setting_section');
 	add_settings_field('tigu_feed_setting_name', __('Feed Alternate content', 'Gameleon'), 'tigu_feed_callback_function', 'media', 'tigu_setting_section');
 	add_settings_field('tigu_altcontent_setting_name', __('Alternate Content', 'Gameleon'), 'tigu_altcontent_callback_function', 'media', 'tigu_setting_section');
 	add_settings_field('tigu_params_setting_name', __('Additional params', 'Gameleon'), 'tigu_params_callback_function', 'media', 'tigu_setting_section');
 	add_settings_field('tigu_flashver_setting_name', __('Minimum Flash version', 'Gameleon'), 'tigu_flashver_callback_function', 'media', 'tigu_setting_section');

 	// Register our setting so that $_POST handling is done for us and our callback function just has to echo the <input>
 	register_setting('media','tigu_setting_name');

	register_setting('media','tigu_setting_name');
	register_setting('media','tigu_iphone_setting_name');
	register_setting('media','tigu_feed_setting_name');
	register_setting('media','tigu_altcontent_setting_name');
	register_setting('media','tigu_params_setting_name');
	register_setting('media','tigu_flashver_setting_name');


 }// eg_settings_api_init()

 add_action('admin_init', 'eg_settings_api_init');


 // ------------------------------------------------------------------
 // Settings section callback function
 // ------------------------------------------------------------------
 //
 // This function is needed if we added a new section. This function
 // will be run at the start of our section
 //

 function tigu_setting_section_callback_function() {
 	echo '<p>' . __("The settings below define how Flash content will be embedded with the ", 'Gameleon') . "<code>[flashgame][/flashgame]</code>" .__("shortcode") .'</p>';
 }


 // ------------------------------------------------------------------
 // Callback function for our example setting
 // ------------------------------------------------------------------
 //
 // creates a checkbox true/false option. Other types are surely possible
 //

 function tigu_setting_callback_function() {
 	$checked = "";

 	// Mark our checkbox as checked if the setting is already true
 	if (get_option('tigu_setting_name'))
 		$checked = " checked='checked' ";

 	echo "<input {$checked} name='tigu_setting_name' id='gv_thumbnails_insert_into_excerpt' type='checkbox'
 value='tigu_setting_name' class='code' /> " . __("Leaving this unchecked means that content is not scaled and excessively large or small flash files will remain excessively large or small", 'Gameleon');
 } // tigu_setting_callback_function()


 function tigu_iphone_callback_function() {
	echo "<input id='tigu_iphone_setting_name' name='tigu_iphone_setting_name' size='40' type='text' value='" .get_option('tigu_iphone_setting_name') ."' />";
	echo " this content will show if the Flash detection fails due to the user using an iPhone.";
 } // tigu_setting_callback_function()

 function tigu_feed_callback_function() {
	echo "<input id='tigu_feed_setting_name' name='tigu_feed_setting_name' size='40' type='text' value='" .get_option('tigu_feed_setting_name') ."' />";
	$s = '$s';
	echo 'this content will show if the feed (rss, atom etc.) is being displayed. Use %1$s for the post-id, %2$s for the post\'s permalink, and %3$s for the swf\'s title; If no value is specified it will default to:';

$format = '<br />To view the flash content, please go to <&#97; href="%2$s">%3';
$format2 = '$s';

echo "<code>".$format.$format2."<<span></span>/<span>&#97;</span>></code>";

 } // tigu_setting_callback_function()


function tigu_altcontent_callback_function() {
 	echo "<input id='tigu_altcontent_setting_name' name='tigu_altcontent_setting_name' size='40' type='text' value='" .get_option('tigu_altcontent_setting_name') ."' />";
	echo " this content will show if the Flash detection fails.";
 } // tigu_setting_callback_function()


function tigu_params_callback_function() {
 	echo "<input id='tigu_params_setting_name' name='tigu_params_setting_name' size='40' type='text' value='" .get_option('tigu_params_setting_name') ."' />";
	echo __('These are the parameters  in name:"value" pairs that are applied to every instance of the flashgame shortcode. See this page on', 'Gameleon') . "<a href='http://kb2.adobe.com/cps/127/tn_12701.html'>Flash OBJECT and EMBED tag attributes</a> " . __("for more information about using parameters. Example parameter usage: ", 'Gameleon') . '<code>wmode:"transparent", quality:"low"</code>';
 } // tigu_setting_callback_function()

function tigu_flashver_callback_function() {
 	echo "<input id='tigu_flashver_setting_name' name='tigu_flashver_setting_name' size='40' type='text' value='" .get_option('tigu_flashver_setting_name') ."' />";
	echo __("This is the minimum flash version that can be embedded on your blog. This can be overridden by setting the value on the media itself.", 'Gameleon');
 } // tigu_setting_callback_function()




function tigu_swf_activate() {
	/*
	 	register_setting('media','tigu_setting_name');
	 	register_setting('media','tigu_iphone_setting_name');
	 	register_setting('media','tigu_altcontent_setting_name');
	 	register_setting('media','tigu_params_setting_name');
	*/

	if (!trim(get_option('tigu_setting_name'))){
		update_option('tigu_setting_name', true);
	}
	if (!trim(get_option('tigu_iphone_setting_name'))){
		update_option('tigu_iphone_setting_name', __("Sorry, flash content is not available on the iPhone.", 'Gameleon'));
	}
	if (!trim(get_option('tigu_altcontent_setting_name'))){
		update_option('tigu_altcontent_setting_name', __("Sorry, either Adobe flash is not installed or you do not have it enabled", 'Gameleon'));
	}

	if (!trim(get_option('tigu_feed_setting_name'))){
			$format = '<br />To view the flash content, please go to <a href="%2$s">%3$s</a><br />';
	//////	update_option('tigu_feed_setting_name', $format);
	}
	/*
	if (!trim(get_option('tigu_params_setting_name'))){
		update_option('tigu_params_setting_name', __("Default params"));
	}
	*/

	if (!trim(get_option('tigu_flashver_setting_name'))){
		update_option('tigu_flashver_setting_name', __("9.0.0", 'Gameleon'));
	}

}

	// attach our function to the correct hook
	add_shortcode('flashgame', 'tigu_swf_shortcode');
	add_shortcode('swflink', 'tigu_swf_link');
	add_filter("attachment_fields_to_edit", "tigu_image_attachment_fields_to_edit", null, 2);
	add_filter("attachment_fields_to_save", "tigu_image_attachment_fields_to_save", null, 2);
	add_filter('media_send_to_editor', 'send_swf_to_editor', 10, 3);
	//	add_filter('the_excerpt_rss', 'tigu_feed_content');
	add_filter( "the_content", "tigu_content", -9999999999999999999 );

	function send_swf_to_editor ($html, $id, $alt=null, $title=null, $align=null, $url=null){
		if (get_post_mime_type( $id ) == "application/x-shockwave-flash") {
			return "[flashgame]" .$id ."[/flashgame]";
		}	else {
			return $html;
		}
	}


	function tigu_feed_content ($content) {
		global $post, $shortcode_tags;
		if (trim($post->post_content) && false) {
			$tempElem = $shortcode_tags["flashgame"];
			unset($shortcode_tags["flashgame"]);
			$content = strip_shortcodes( $post->post_content );
			$shortcode_tags["flashgame"] = $tempElem;
			$content = do_shortcode($content);
		}
		return $content;
	}


	function tigu_content ($content) {
		global $post;
		if (true && is_feed() && trim($post->post_content)) {
			global $post, $shortcode_tags;
			$tempElem = $shortcode_tags["flashgame"];
			unset($shortcode_tags["flashgame"]);
			$contentA = strip_shortcodes( $post->post_content );
			$shortcode_tags["flashgame"] = $tempElem;
			$content = do_shortcode($contentA);
			return $content;
		} elseif(is_feed()) {
			return $content;
		} elseif (get_post_mime_type( $post->ID )=="application/x-shockwave-flash"){
			return "" . tigu_swf_shortcode( null, $post->ID) . "<p>" .$post->post_excerpt ."</p><p>"  .$post->post_content ."</p>";
		}
		else return $content;
	}


function tigu_image_attachment_fields_to_save($post, $attachment) {
	// $attachment part of the form $_POST ($_POST[attachments][postID])
	// $post attachments wp post array - will be saved after returned
	//     $post['post_type'] == 'attachment'


	if( $post['post_type'] == 'attachment' && isset($attachment['tigu_x'])  && is_int_id($attachment['tigu_x'])){
		// update_post_meta(postID, meta_key, meta_value);
		update_post_meta($post['ID'], '_tigu_x', $attachment['tigu_x']);
	}
	if( $post['post_type'] == 'attachment' && isset($attachment['tigu_y']) && is_int_id($attachment['tigu_y'])){
		// update_post_meta(postID, meta_key, meta_value);
		update_post_meta($post['ID'], '_tigu_y', $attachment['tigu_y']);
	}
	if( $post['post_type'] == 'attachment' && isset($attachment['tigu_base']) ){
		// update_post_meta(postID, meta_key, meta_value);
		update_post_meta($post['ID'], '_tigu_base', $attachment['tigu_base']);
	}
	if( $post['post_type'] == 'attachment' && isset($attachment['tigu_swfver']) ){
		// update_post_meta(postID, meta_key, meta_value);
		update_post_meta($post['ID'], '_tigu_swfver', $attachment['tigu_swfver']);
	}

	return $post;
}

function tigu_image_attachment_fields_to_edit($form_fields, $post) {
	// $form_fields is a special array of fields to include in the attachment form
	// $post is the attachment record in the database
	//     $post->post_type == 'attachment'
	// (attachments are treated as posts in WordPress)

	// add our custom field to the $form_fields array
	// input type="text" name/id="attachments[$attachment->ID][custom1]"

	if (get_post_mime_type($post->ID) == "application/x-shockwave-flash") {

		$form_fields["custom_line"]["label"] = "";
		$form_fields["custom_line"]["input"] = "html";
		$form_fields["custom_line"]["html"] = "<hr />";

		$form_fields["tigu_x"]["label"] =  __("Width", 'Gameleon');
		$form_fields["tigu_x"]["input"] = "text";
		$form_fields["tigu_x"]["value"] = get_post_meta($post->ID, "_tigu_x", true);

		$form_fields["tigu_y"]["label"] =  __("Height", 'Gameleon');
		$form_fields["tigu_y"]["input"] = "text";
		$form_fields["tigu_y"]["value"] = get_post_meta($post->ID, "_tigu_y", true);

		$form_fields["tigu_base"]["label"] =  __("Base", 'Gameleon');
		$form_fields["tigu_base"]["input"] = "text";
		$form_fields["tigu_base"]["value"] = get_post_meta($post->ID, "_tigu_base", true);

		$form_fields["tigu_base"]["label"] =  __("SWF Version", 'Gameleon');
		$form_fields["tigu_base"]["input"] = "text";
		$form_fields["tigu_base"]["value"] = get_post_meta($post->ID, "_tigu_swfver", true);

	}
	return $form_fields;
}

/// [flashgame]ID, X, Y, flashvars, Base [/flashgame]


function tigu_swf_shortcode( $atts=null, $content = null, $code="", $contentStringOveride="" ) {
	global $swf_instance;
	global $post;
	$swf_instance++;

	if ( isset($atts["delimiter"]) && trim($atts["delimiter"]) ) {
		$delim = trim($atts["delimiter"]);
	} else {
		$delim = "|";
	}

	// strings to use the option API.
	if (trim($contentStringOveride)){
		$contentline = $contentStringOveride;
	} else if(isset($atts["altcontent"]) && trim($atts["altcontent"])){
		$contentline = $atts["altcontent"];
	} else {
		$contentline = get_option('tigu_altcontent_setting_name');
	}

	$scale_to_medium = get_option('tigu_setting_name');
	$iphone_message = get_option('tigu_iphone_setting_name');
	$feed_message = get_option('tigu_feed_setting_name');
	$max_width  = get_option('embed_size_w');
	$max_height = get_option('embed_size_h');

	$content = explode(",",$content);
	$contentbefore = $content[0];
    
    if (!empty($content[4])){
		$content[4] = " base:\"" . $content[4] . "\"";
	}

	if (	is_int_id(trim($content[0]))	){

		if (get_post_mime_type( $content[0] )!="application/x-shockwave-flash"){
			return "<br />" .__("Error: Attachment is not available or is not Flash content.") ."<br />";
		}
		if (empty($content[4])){
			get_post_meta($content[0], "_tigu_base", true);
		}
		if (empty($content[4])){
			$content[4]= 'base:"' . tigu_strip_swf_basetag(wp_get_attachment_url($content[0])) . "\"";
		} elseif ($content[4] == "null"){
			$content[4]="";
		}

		if (empty($content[4])){
			$content[1] =  get_post_meta($content[0], "_tigu_x", true);
		}

		if (empty($content[2])){ 
			$content[2] =  get_post_meta($content[0], "_tigu_y", true);
		}
		$flash_ver = get_post_meta($content[0], '_tigu_swfver', true);
		$content[0] = wp_get_attachment_url($content[0]);

	} elseif ($content[0] && !$content[4] ) {

	// if the swf location is valid there is no base argument then determine it
		if (!$content[4]){
			$content[4]= 'base:"' . tigu_strip_swf_basetag($content[0]) . "\"";
		} elseif ($content[4] == "null"){
			$content[4]="";
		}
	}


		if (!$flash_ver){
			$flash_ver = get_option('tigu_flashver_setting_name');
		}
		if (!$flash_ver){
			$flash_ver = "9.0.0";
		}


	/// dimension heirarchy; dimension provided by shortcode, dimension assigned to the media, dimension provided in the 'Maximum embed size', dimension provided in the 'Image-sizes: Medium size',
	/// Scales to dimension provided in the 'Maximum embed size', dimension provided in the 'Image-sizes: Medium size';

	if (!$max_width){
		$max_width  = get_option('medium_size_w');
	}
	if (!$max_height){
		$max_height  = get_option('medium_size_h');
	}

    if (empty($content[1])){
		$content[1] = $max_width;
	}

	if (!$content[2]){
		$content[2] = $max_height;
	}

	if ($scale_to_medium && $max_height && $max_width) {
		list( $content[1], $content[2] ) = wp_expand_dimensions( $content[1], $content[2], $max_width, $max_height );
	}

	if (!$content[1] && !$content[2]){
		return __("Error: Dimensions are not specified.", 'Gameleon');
	} elseif(!(strpos($_SERVER['HTTP_USER_AGENT'], "iPhone") === false)) {
		if (is_feed()){
			echo $iphone_message."<br /><br />";
			return "";
		} else {
			return $iphone_message;
		}
	} elseif(is_feed()){
		if(!trim($feed_message)){
			$format = 'To view the flash content, please go to <a href="%2$s">%3$s</a>';
		} else {
			$format = $feed_message;
		}

		if ($post->ID == $contentbefore[0]) {
			// the post is the media itself.
			$myPermalink = "$post->guid";
		}
		else {
			// the media is embedded on a post.
			$myPermalink = get_permalink();
		}

		echo sprintf($format, $post->ID, $myPermalink, $post->post_title) . "<br /><br />";
		return "";

		}  elseif ($content[0]) {
		// allow flashvars to have quotes because tinyMCE has annoying quotes.
        if ( !isset($content[3])) $content[3] = '';
		$content[3] = str_replace("&#8217;", "'", $content[3]);
		$content[3] = str_replace("&#8221;", '"', $content[3]);

		if ($post->ID == $contentbefore) {
			// the post is the media itself.
			$myPermalinkA = "$post->guid";
		}
		else {
			// the media is embedded on a post.
			$myPermalinkA = $content[0];
		}


		$echoline = "<span id='swf-".$post->ID."-".$swf_instance."'>". $contentline ."</span>";


		$sw = '<script type="text/javascript">swfobject.embedSWF(';

		/// File URL
		$sw .= '"' . $content[0] . '"';
		/// New ID
		$sw .= ', "swf-'	.$post->ID	."-"	.$swf_instance . '"';
		/// X
		$sw .= ', "' . trim($content[1]) . '"';
		/// Y
		$sw .= ', "' . trim($content[2]) . '"';
		/// flash_ver
		$sw .= ', "' . trim($flash_ver ) . '"';
		/// flashvars
		$sw .= ', "" ';
		$sw .= ', {' . str_replace($delim, ", ", trim($content[3] )) . '}';
		/// base
		$tigu_are_global_params = get_option('tigu_params_setting_name');
		$sw .= ', {' . trim($content[4]);
			if (trim($tigu_are_global_params)) {
			$sw .= "," . $tigu_are_global_params;
			}
		$sw .=  '}';
		$sw .= ');</script>';

		return $echoline . $sw;
	}
	else {
		return "<br />" .__("ERROR: Error Embedding SWF") ."<br />";
	}

}

function tigu_swf_link($atts,$content = null ){
	if (is_int($content) || ctype_digit($content) && trim(get_post_mime_type($content))){
		return "<a href='".get_permalink( $content )."' rel='attachment wp-att-$content'>".apply_filters( 'the_title',get_the_title($content), $content)."</a>";
	}
}

function tigu_strip_swf_basetag($inp) {

	$inp_array = explode("/", $inp);

	if(!$inp_array[count($inp_array)-1]){
		unset($inp_array[count($inp_array)-1]);
		// remove the trailing slash.
		// remove the last part of the path '/flash.swf/';
	}

	unset($inp_array[count($inp_array)-1]);
	// remove the last part of the path '/flash.swf';

	if (count($inp_array)){
		return (implode("/", $inp_array));
	}

}