<?php
// @ Using: http://www.cc.jyu.fi/~ltnevala/nowplaying/
// @ Possible post vars:
// 	+ Playing = 1 - WinAmp is playing the track, 0 - WinAmp is stopped.
// 	+ Artist1 = Artist of currently playing or last played track.
// 	+ Title1 = Title of currently playing or last played track.
// 	+ Album1 = Album of currently playing or last played track.
// 	+ Year1 = Release year of currently playing or last played track.
// 	+ Track1 = Track number of currently playing or last played track.
// 	+ Length1 = Length of currently playing or last played track.
// 	+ Genre1 = Genre of currently playing or last played track.
// 	+ Quality1 = Quality of currently playing or last played track.
// 	+ Comment1 = Comment of currently playing or last played track.
// 	+ Filename1 = Filename of currently playing or last played track.
// @ Song history is saved to parameters [parameter]2-n (n = number of tracks included in song history), so the title of the track which, has been played before currently playing track, is saved to Title2-parameter and so on.



$global = array();
/************************************/
  $global['name'] = "Now Playing Banner";
  $global['version'] = "1.0.1 beta-20050508";
/*@author Jochem 'XBL' van Leeuwen - vanleeuwen.at
*
* Do you want any addons?
* Mail me @ jochem@vuilnisbak.com
* Or PM @ the Webhostingtalk.nl boards
*
*-----------------
*   Copyright 2005
*   Jochem van Leeuwen (Freelance PHP/SQL Developer). 
*   All rights reserved.
*
* This software is distributed "as is" without
* any warranty. You may edit it freely under
* a FreeBSD-like license:
*   1. Redistributions of source code must retain
*      the above copyright notice, this list of 
*      conditions and the following disclaimer.
*   2. Redistributions in binary form must reproduce
*      the above copyright notice, this list of conditions
*      and the following disclaimer in the documentation
*      and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY JOCHEM VAN LEEUWEN (FREELANCE PHP/SQL DEVELOPER) ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. NO ONE WILL READ THIS, PROBABLY, IF YOU DO: CONGRATS. IN NO EVENT SHALL JOCHEM VAN LEEUWEN (FREELANCE PHP/SQL DEVELOPER) OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and
* documentation are those of the author and should not be
* interpreted as representing official policies, either
* expressed or implied, of
* Jochem van Leeuwen (Freelance PHP/SQL Developer).
*-----------------
*
* Functions:
* @ Write Current song + title to image
* @ Get album art from Amazon, write it to the image
* @ Save the image to disk
*
* Have fun!
*************************************/

// Amazon settings to get the album art
$amazon = array();
$amazon['SubscriptionId'] = "0000000000000000000"; // Get this for free @ http://amazon.com/webservices ("Register for AWS")
$amazon['no_album_art'] = "/path/to/image/image.jpg"; // if we can't get the album art, use this image (square size, minimum of 40x40 (will be resized to 40x40 anyway ;-) )
$amazon['xml'] = "/path/to/xml/amazon.xml"; // we will save the xml output here for 
$amazon['jpg'] = "/path/to/image/amazon.jpg"; // we will save the resized album art here

// Script settings
$global['password'] = "00000000000000000000000000000000"; // md5 (need md5 generator? ie, http://alexanderonline.nl)
$global['username'] = "username"; // to access the script combined with above password (specify this in the plugin)
$global['errorfile'] = "/path/to/textfile/error.txt"; // contains errors (not tested)

// File settings (to write the info to a text file)
$txt = array();
$txt['file'] = "/path/to/textfile/song.txt"; // write song info to

// Image settings (to write the info to a 468x60 image)
$image = array();
$image['from'] = imagecreatefrompng("/path/to/image/np_empty.png"); // write file from
$image['to'] = "/path/to/image/np.png"; // write file to
$image['color'] = imagecolorallocate($image['from'], 0xFF, 0xFF, 0xFF); // this is white
$image['font'] = "/path/to/font/font.ttf"; // A Freetype supported font

/*
// MySQL settings (to save the stuff in a mysql_db)
$mysql = array();
$mysql['host'] = "localhost"; // 99% chance you can leave this
$mysql['user'] = "username"; // mysql username
$mysql['pass'] = "password"; // mysql password
$mysql['db'] = "database"; // mysql database
*/

// Define image resize function:
function resize($source, $n_width, $filename, $quality = 80) { 
	/* Check if dest img is writeable  (i might build in that it also checks the $source)*/ 
	if (!is_writable($filename)) { 
		return false; 
	} else { 
		$size = getimagesize($source); // Get the image dimensions and mime type 
		$scale = $size['0'] / $n_width;
		$w = $size[0] / $scale; // Width divided 
		$h = $size[1] / $scale; // Height divided 
		$resize = imagecreatetruecolor($w, $h); // Create a blank image 

		/* Check quality option. If quality is greater than 100, set quality to 100 (jpeg only) */ 
		if ($quality > 100) { 
			$quality = 100; 
		} else {             

			switch ($size['mime']) { 
				case "image/jpeg": 
				$im = imagecreatefromjpeg($source); 
				imagecopyresampled($resize, $im, 0, 0, 0, 0, $w, $h, $size[0], $size[1]); // Resample the original JPEG 
				imagejpeg($resize, $filename, $quality); // Write new img to $filename
				break; 

				case "image/png": 
				$im = imagecreatefrompng($source); 
				imagecopyresampled($resize, $im, 0, 0, 0, 0, $w, $h, $size[0], $size[1]); // Resample the original PNG 
				imagepng($resize, $filename); // Write new img to $filename
				break; 
			} 
			imagedestroy($im); 
		}
	return true; 
	} 
}

//Define error write function:
function error($error_file, $error_array) {
	// Write to the txt file
	if (is_writable($error_file)) {
		if (!$handle = fopen($txt['file'], "w")) {
			return false;
		}
		foreach($error_array as $error) {
			if (!fwrite($handle, $error)) {
				return false;
			}
		}
		return true;
	} else {
		return false;
	}
}

if($_POST['username'] == $global['username'] && md5($_POST['password']) == $global['password']) {

	// Get the thumb image of the album with xml
	$xml = array();
	$xml['file'] = $amazon['xml'];
	$artist = str_replace(" ", "%20", $_POST['Artist1']);
	$album = str_replace(" ", "%20", $_POST['Album1']);
	$xml['req'] = "http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&SubscriptionId=".$amazon['SubscriptionId']."&Operation=ItemSearch&Keywords=".$album."%20".$artist."&SearchIndex=Music";
	
	if (is_writable($xml['file'])) {
		if (!copy($xml['req'], $xml['file'])) {
			$error[] = "xml copy ".date("Y-m-d H:i:s")."\n";
			error($global['errorfile'], $error);
			die("<strong>Error:</strong> Ik kan het bestand '<strong>".$xml['req']."' niet copieëren naar '<strong>".$xml['file']."</strong>'.");
		}
		echo "Succes, ik heb '<strong>".$xml['req']."</strong>' naar bestand '<strong>".$xml['file']."</strong>' gecopieërd.";
	} else {
		$error[] = "xml write ".date("Y-m-d H:i:s")."\n";
		error($global['errorfile'], $error);
		die("Het bestand '<strong>".$xml['file']."</strong>' kan ik helaas niet beschrijven!");
	}
	$xml = simplexml_load_file($xml['file']);
	if($xml->Items->Error[0]->Code) {
		// no image, or other error
		$amazon['image'] = $amazon['no_album_art'];
	} else {
		$amazon['ASIN'] = $xml->Items->Item[0]->ASIN;
		$amazon['image'] = "http://images.amazon.com/images/P/".$amazon['ASIN'].".01.THUMBZZZ.jpg";
	}

	
	// Get info ready to use in the txt file + image + db
	$info = $_POST['Artist1']." - ".$_POST['Title1'];
	
	// Format the info for the txt file
	if($_POST['Playing'] == 1) {
		$content = "Music: On\nCurrent song: ".$info;
	} else {
		$content = "Music: Off\nLast song: ".$info;
	}
	// Write to the txt file
	if (is_writable($txt['file'])) {
		if (!$handle = fopen($txt['file'], "w")) {
			$error[] = "open txt ".date("Y-m-d H:i:s")."\n";
			error($global['errorfile'], $error);
			die("<strong>Error:</strong> Ik kan het bestand '<strong>".$txt['file']."</strong>' niet openen.");
		}
		if (!fwrite($handle, $content."\n".$amazon['image'])) {
			$error[] = "write txt ".date("Y-m-d H:i:s")."\n";
			error($global['errorfile'], $error);
			die("<strong>Error</strong> Ik kan niet naar het bestand '<strong>".$txt['file']."</strong>' schrijven.");
		}
		echo "Succes, ik heb '<strong>".$content."\n".$amazon['image']."</strong>' naar bestand '<strong>".$txt['file']."</strong>' geschreven.";
		fclose($handle);
	} else {
		$error[] = "nonwriteable txt ".date("Y-m-d H:i:s")."\n";
		error($global['errorfile'], $error);
		die("Het bestand '<strong>".$txt['file']."</strong>' kan ik helaas niet beschrijven!");
	}


/*
	// Format info for the database
	$_POST['Artist1'] = substr($_POST['Artist1'], 0, 252)."...";
	$_POST['Title1'] = substr($_POST['Title1'], 0, 252)."...";
	$_POST['Album1'] = substr($_POST['Album1'], 0, 252)."...";
	if(!is_nummeric($_POST['Year1'])) { 
		$_POST['Year1'] = -1;
	}
	if(!is_nummeric($_POST['Track1'])) {
		$_POST['Track1'] = -1;
	}
	$_POST['Lenght1'] = substr($_POST['Lenght1'], 0, 252)."...";
	$_POST['Genre1'] = substr($_POST['Genre1'], 0, 252)."...";
	$_POST['Quality1'] = substr($_POST['Quality1'], 0, 252)."...";
	$_POST['Filname1'] = substr($_POST['Filename1'], 0, 252)."...";
	// Write to the database
	$query = "INSERT INTO `song_monitor` (`artist`, `title`, `album`, `year`, `track`, `lenght`, `genre`, `quality`, `comment`, `filename`) VALUE ('".$_POST['Artist1']."', '".$_POST['Title1']."', '".$_POST['Album1']."', '".$_POST['Year1']."', '".$_POST['Track1']."', '".$_POST['Lenght1']."', '".$_POST['Genre1']."', '".$_POST['Quality1']."', '".$_POST['Comment1']."', '".$_POST['Filename1']."')";
*/	


	// Format the info for the image
	if(strlen($info) > 20 && $_POST['Playing'] == 1) {
		$content = "Music: On\nCurrent song: ".substr($info, 0, 20)."...";
	}
	if(strlen($info) > 20 && $_POST['Playing'] != 1) {
		$content = "Music: Off\nLast song: ".substr($info, 0, 20)."...";
	}
	// Resize the Amazon image
	if(!resize($amazon['image'], 40, $amazon['jpg'], 100)) {
		$error[] = "resizen ".date("Y-m-d H:i:s")."\n";
		error($global['errorfile'], $error);
		die("<strong>Error:</strong> Resizen van '<strong>".$amazon['image']."</strong>' naar '<strong>amazon.jpg</strong>' is mislukt.");
	}
	// Write the Amazon image to the image
	$dst_x = 150; // no. of pixels from the left of the destination img
	$dst_y = 10; // no. of pixels from the top of the destination img
	$src_x = 0; // where to start with getting the source img (the amazon pic) (width)
	$src_y = 0; // where to start with getting the source img (the amazon pic) (height)
	$src_w = 40; // full width of the source img (the amazon pic), we want the full img
	$src_h = 40; // full height of the source img (the amazon pic), we want the full img
	$pct = 100; // transparancy. Lower = more transparancy (haven't tested it)
	$amazon['image'] = imagecreatefromjpeg($amazon['jpg']);
	imagecopymerge($image['from'], $amazon['image'], $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct);
	// Write to the image
	// printing the text:
	// $image['to'] is so it prints on that image.
	// 13 is how large the font is
	// 0 is the rotation (add and the right side will tip up)
	// 200 is how far it is from the left side of the image
	// 22 is how far it is from the top of the image
	// $image['color'] color gives the text its color
	// $image['font'] is the font it uses
	// $content is the text is prints...
	imagettftext($image['from'], 13, 0, 200, 22, $image['color'], $image['font'], $content);
	
	// We want to save the image (in png format...) 
	imagepng($image['from'], $image['to']);

} else {
	?>
	<form action="<? echo $_SERVER['PHP_SELF']; ?>" method="post">
		Username: <input type="text" name="username" /><br />
		Password: <input type="password" name="password" /><br />
		Artist1: <input type="text" name="Artist1" value="green day" /><br />
		Title1: <input type="text" name="Title1" value="homecoming" /><br />
		Album1: <input type="text" name="Album1" value="american idiot" /><br />
		Playing: <input type="text" name="Playing" value="1" /><br />
		Submit: <input type="submit" name="submit" value="submit" />
	</form>
	<?php
}
?>