<?php if (!defined('PmWiki')) exit ();

/* 
    
	Original info:
	copyright 2009, Adam Overton
	based on code by Jon Haupt, copyright 2007-8
	which was built on code from swf.php copyright 2004 Patrick R. Michaud
	and from quicktime.php copyright 2006 Sebastian Siedentopf.
	
	YouTube, Vimeo, GoogleVideo, and FlickrVid code majorly amended by Adam Overton, 
	starting 2009-09-21, based primarily upon the original code of Jon Haupt, 
	but with the updated ability to define parameters from the YouTube api:
	http://code.google.com/apis/youtube/player_parameters.html. Additional suggestions and code
	from Jabba Laci & Byron Lunz was incorporated for non-XHTML-compliant output.
	
	This file is distributed under the terms of the GNU General Public 
	License as published by the Free Software Foundation; either 
	version 2 of the License, or (at your option) any later version.  
	
	This module enables embedding of video and audio hosted on Archive.org.
	The simplest use of any of these includes:
		(:archive.org videocode:)
	
	In addition, Replace-On-Edit Patterns ($ROEPatterns) have been created for this recipe, so that visitors can simply copy-and-paste the embed code, click save or save-and-edit, and have the code automatically converted to the appropriate pmwiki markup. If this is undesired, an admin can disable this in config.php by setting $YouTubeROEenabled, $VimeoROEenabled, etc to false.
	
	note that there is currently a bug for video playlists that usually have the first slot filled with an 'image.jpg'; this currently causes the video to automatically begin playing. i hope to fix this soon, but for now to prevent any autoplay simply remove the jpg from the playlist.
	
	. . .
	
	Versions:
	* 2009-12-20 - initial release
	
*/


# Version date
$RecipeInfo['SWFSites-ArchiveOrgPlayer']['Version'] = '2009-12-20';


### ARCHIVE.ORG
### (:archive.org videocode params:)
Markup('archive.org', '<img', "/\\(:archive\.org\\s+([^\\s]+)\\s*(.*):\\)/e", "ShowArchiveOrgPlayer('$1','$2')");
SDVA($ArchiveOrgPlayerDefaultParams, array(
	'defaultAudioWidth' => '350'
	,'defaultAudioHeight' => '24'
	,'defaultVideoWidth' => '640'
	,'defaultVideoHeight' => '504'
	,'scale' => '1'
	,'fs' => 'false'
	,'autoplay' => 'false'
	,'gloss' => 'high'
	,'bgColor' => '000000'
	,'bgGradient' => 'medium'  # more info: http://flowplayer.org/documentation/configuration/plugins.html#styling-properties
	,'sliderColor' => '777777'
	,'progressColor' => '777777'
	,'timeColor' => 'eeeeee'
	,'durationColor' => '01DAFF'
	,'buttonColor' => '333333'
	,'buttonOverColor' => '505050'
));
SDV($ArchiveOrgPlayerROEenabled, true);

# ROEPatterns - ARCHIVE.ORG EMBED CONVERSION
# Converts pasted ArchiveOrgPlayer embed code into valid pmwiki (:archive.org:) code
if ($ArchiveOrgPlayerROEenabled) {
	$ROEPatterns['!<embed.*archive\.org/flow/flowplayer.*</embed>!ie'] = "ArchiveOrgPlayerROE(PSS('$0'))";	
	SDV($ArchiveOrgPlayerROEFmt, '(:archive.org filenames params:)');
	function ArchiveOrgPlayerROE($videocode) {
		global $ArchiveOrgPlayerROEFmt, $ArchiveOrgPlayerDefaultParams;

		# get filename(s)
		$filenamecount = preg_match_all('#http://www.archive.org/download/([^"]+\.[^"]+)",#', $videocode, $filenamesArray);
		
		if ($filenamecount==0) { return $videocode; }
		elseif ($filenamecount==1) {
			# return only 1 filename, no brackets
			$filenames = $filenamesArray[1][0];
			# determine type: video or audio
			$typeZ = mediaType($filenames);
		} elseif ($filenamecount>1) {
			# return list of [filenames]  (in brackets separated by commas)
			$filenames = "[".implode(",",$filenamesArray[1])."]";
			//echo $filenames; break;
			## NOTE: The playlist function works, however, the list of tracks won't show up in this version - flowplayer has to be implemented slightly differently. The tracks, however, can be reached individually via the << and >> buttons.
			## For now, the track listing is spit out automatically in the ROEPattern in case it's helpful, and in order to make it clear that indeed it's a playlist
			foreach($filenamesArray[1] as $key => $val) {
				$i = $key+1;
				$trackListing .= "# %newwin%[[http://www.archive.org/download/$val | $val]]\n";
			}
			# determine type: video or audio
			$typeZ = mediaType($filenamesArray[1][0]);
		}

		$type = $typeZ[1]; $ext = $typeZ[0];

		# change and remove some parameters from the audio version
		if ($type=="audio") {
			$ArchiveOrgPlayerDefaultParams['height'] = $ArchiveOrgPlayerDefaultParams['defaultAudioHeight'];
			$ArchiveOrgPlayerDefaultParams['width'] = $ArchiveOrgPlayerDefaultParams['defaultAudioWidth'];
			# remove scale & fs params in audio version
			$ArchiveOrgPlayerDefaultParams = array_diff_key($ArchiveOrgPlayerDefaultParams, array('scale'=>'','fs'=>''));
			//$removeDefaultParams = "#(scale|fs)#";
		} elseif ($type=="video") {
			$ArchiveOrgPlayerDefaultParams['height'] = $ArchiveOrgPlayerDefaultParams['defaultVideoHeight'];
			$ArchiveOrgPlayerDefaultParams['width'] = $ArchiveOrgPlayerDefaultParams['defaultVideoWidth'];
		}

		# remove some parameters from both versions -- don't need to be output
		$ArchiveOrgPlayerDefaultParams = array_diff_key($ArchiveOrgPlayerDefaultParams, array('defaultAudioWidth'=>'', 'defaultAudioHeight'=>'', 'defaultVideoWidth'=>'', 'defaultVideoHeight'=>''));

		# get default params - add all of the ArchiveOrgPlayerDefaultParams to the flowplayer pmwiki code
		foreach($ArchiveOrgPlayerDefaultParams as $key => $val) { $params .= " $key=$val"; }
		
		# output -- pops in filenames & parameters
		$out = $ArchiveOrgPlayerROEFmt;
		$out = str_replace(array('filenames','params'), array($filenames,$params), $out);
		if ($trackListing) {
			# spit out track listing if there are tracks
			$out .= "\n\nuse the << and >> buttons to navigate the playlist:\n$trackListing";
		}

		return $out;
	}
}


function ShowArchiveOrgPlayer($id, $args) {
	global $ArchiveOrgPlayerDefaultParams; 
	
	# add default parameters before parsing arguments
	$args = array_merge($ArchiveOrgPlayerDefaultParams, ParseArgs($args)); # uses ArchiveOrgPlayerDefaultParams, unless supplied by user

	# determine type: video or audio
	$typeZ = mediaType($id);
	$type = $typeZ[1]; $ext = $typeZ[0];
	
	# define width & height
	## one can supply a 'scale' default different than '1', but it's not suggested, as it could be confusing to users
	$width = $args['width'];
	$height = $args['height'];

	if(!$width) {
		if($type=="video") $width = $ArchiveOrgPlayerDefaultParams['defaultVideoWidth'];
		else  $width = $ArchiveOrgPlayerDefaultParams['defaultAudioWidth'];
	}
	if(!$height) {
		if($type=="video") $height = $ArchiveOrgPlayerDefaultParams['defaultVideoHeight'];
		else  $height = $ArchiveOrgPlayerDefaultParams['defaultAudioHeight'];
	}

	# apply scaling
	$scale = $args['scale'];
	$width *= $scale;
	$height *= $scale;
	
	$autoplay = $args['autoplay'];
	if($autoplay=="1") $autoplay = "true";
	elseif($autoplay=="0") $autoplay = "false";

	if ($type=="audio") $fullscreen = "false"; # don't allow fullscreen for audio
	elseif ($type=="video") {
		$fullscreen = $args['fs'];
		if($fullscreen=="1") $fullscreen = "true";
		elseif($fullscreen=="0") $fullscreen = "false";
	}
	
	# check for playlist
	## NOTE: The playlist function works, however, the list of tracks won't show up in this version - flowplayer has to be implemented slightly differently. The tracks, however, can be reached individually via the << and >> buttons.
	## For now, the track listing is spit out automatically in the ROEPattern in case it's helpful...
	$playlistAudioFmt = '{"url":"FILENAME","autoPlay":true}';
	$playlistVideoFmt = '{"url":"FILENAME","autoPlay":true,"accelerated":true,"scaling":"fit","provider":"h264streaming"}';
	if ($type=="audio") $playlistFmt = $playlistAudioFmt;
	elseif ($type=="video") $playlistFmt = $playlistVideoFmt;
	if (strpos($id,"[")===0) {
		# playlist present: [$id]
		$playlist_enabled = "true";
		$id = str_replace(array("[","]"),'',$id); # remove brackets
		$playlist_array = explode(",",$id);
		# create playlist
		foreach($playlist_array as $key => $fn) {
			# allow for part of the url, or the entire url
			if (strpos($fn,"http")===false) $fn = "http://www.archive.org/download/$fn";
			if ($key!=0) { $playlist .= ",".str_replace("FILENAME",$fn,$playlistFmt); }
			# 1st should have autoplay set to the current autoplay setting, and have no comma at the front
			else {
				$thisExt = mediaType($fn); $thisExt = $thisExt[0];
				if ($thisExt=="jpg") { # for jpg, autoplay should always be true (so leave it alone)
					$playlist .= str_replace("FILENAME",$fn,$playlistFmt);
				} else { # videofiles get default autoplay, (except the 1st one after a jpg)
					$playlist .= str_replace(array("FILENAME","\"autoPlay\":true"),array($fn,"\"autoPlay\":$autoplay"),$playlistFmt);
				}
			}
		}
	} else {
		# playlist NOT PRESENT: $id
		$playlist_enabled = "false";
		# allow for part of the url, or the entire url
		if (strpos($id,"http")===false) $id = "http://www.archive.org/download/$id";
		# should have autoplay set to the current autoplay setting
		$playlist = str_replace(array("FILENAME","\"autoPlay\":true"),array($id,"\"autoPlay\":$autoplay"),$playlistFmt);
	}
	
	# for context menu - everything before the slash/
	if(preg_match('#download/([^/]+)/([^/"]+)"#',$playlist,$matches)) $id_reduced = $matches[1];
	
	# Output
	$out = "<embed type='application/x-shockwave-flash' width='".$width."' height='".$height."' allowfullscreen='true' allowscriptaccess='always' src='http://www.archive.org/flow/flowplayer.commercial-3.0.5.swf' w3c='true' ";
	$out .= 'flashvars=\'config={';
	$out .= '"key":"#$b6eb72a0f2f1e29f3d4",';
	$out .= "\n   ".'"playlist":['.$playlist.'],';
	if ($type=="audio") {
		$out .= "\n   ".'"clip":{"autoPlay":true},';
	} elseif ($type=="video") {
		$out .= "\n   ".'"clip":{"autoPlay":false,"accelerated":true,"scaling":"fit","provider":"h264streaming"},';
	}
	$out .= "\n   ".'"canvas":{"backgroundColor":"0x000000","backgroundGradient":"none"}';
	$out .= "\n   ".',"plugins":{"audio":{"url":"http://www.archive.org/flow/flowplayer.audio-3.0.3-dev.swf"},';
	$out .= "\n   ".'"controls":{"playlist":'.$playlist_enabled.', "fullscreen":'.$fullscreen.', "gloss":"high", "backgroundColor":"0x'.$args['bgColor'].'", "backgroundGradient":"'.$args['bgGradient'].'", "sliderColor":"0x'.$args['sliderColor'].'", "progressColor":"0x'.$args['progressColor'].'", "timeColor":"0x'.$args['timeColor'].'", "durationColor":"0x'.$args['durationColor'].'", "buttonColor":"0x'.$args['buttonColor'].'", "buttonOverColor":"0x'.$args['buttonOverColor'].'"}';
	if ($type=="video")
		$out .= ',"h264streaming":{"url":"http://www.archive.org/flow/flowplayer.h264streaming-3.0.5.swf"}';
	$out .= "},";
	$out .= "\n   ".'"contextMenu":[{"'.$id_reduced.' at archive.org":"function()"}, "-", "Flowplayer 3.0.5"]}\'>';
	$out .= '</embed>';

      return Keep($out);
}


function mediaType($filename) {
	# determine type: video or audio
	$ext = end(explode(".",str_replace(array("[","]"),'',$filename)));
	if ($ext=="mp3" || $ext=="ogg") $type = "audio";
	# include jpg as a video b/c archive.org often uses .jpg still as a the first item in a playlist
	elseif ($ext=="mp4" || $ext=="jpg") $type = "video";	
	return array($ext, $type);
}