<?php
	// 
	// save.php
	//
	// This is part of the source code for the EditGallery application.  
	// See also the companion index.php file.
	//
	// This code can be freely copied, modified, and distributed.  
	//    

	// This file is responsible for detecting whether an image save occured.  If so,
	// it will use the given _imageid to save the new image data to the appropriate
	// place.  Then (whether or not a save occured) it will take down the Picnik-in-a-box
	// window or redirect as appropriate.
	
	// If someone wants to view the source, then dump it out.
	if( isset( $_GET["source"] ) ) {
		echo "<pre>";
		echo htmlentities( file_get_contents( "save.php") );								
		echo "</pre>";
		exit;
	}

	// NOTE: Most of the PHP code in this sample is used to manage finding, loading, and saving
	// the images on the disk.  Don't worry too much about how it works -- the Javascript
	// code down below is much more interesting.
	
	// $strRoot will be the URL to this page's parent directory
	$strPath = str_replace( "\\", "/", $_SERVER['REQUEST_URI'] );
	$aPath = explode( "?", $strPath);
	$strRoot = "http://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER['SERVER_PORT'] . $aPath[0];
	$aSelfBits = explode( "/", $_SERVER['PHP_SELF'] );
	$strFile = $aSelfBits[count($aSelfBits)-1];
	$strRoot = str_replace( $strFile, "", $strRoot );	// remove the name of the page
	if ($strRoot[strlen($strRoot)-1] != "/")
		$strRoot .= "/";

	// If we were given an _imageid, then download all the files we're expecting
	// and save them in the appropriate places.  If we weren't given an _imageid,
	// that's because the user hit "close" instead of "save".
	$strRefreshId = null;
	$strEditImg = "";
	$strEditThumbImg = "";
	
	if (isset($_GET['_imageid'])) {
		// we download both the full, edited image and the 75x75 square thumbnail
		// (the square thumbnail was generated because we set _thumbs=yes)
		$strRefreshId = $_GET['_imageid'];
		$imgData = DownloadFile( "file" );
		if ($imgData) {
			$strEditImg = "img/" . $strRefreshId . ".edit.jpg";
			file_put_contents( $strEditImg, $imgData );
			// create a URL for this img
			$strEditImg = $strRoot . $strEditImg;	
		}
		
		$thumbData = DownloadFile( "_thumb75" );
		if ($thumbData) {
			$strEditThumbImg = "img/" . $strRefreshId . ".edit_t.jpg";
			file_put_contents( $strEditThumbImg, $thumbData );
			// create a URL for this img
			$strEditThumbImg = $strRoot . $strEditThumbImg;
		}

	}
	
	// DownloadFile(): attempts to download a file that Picnik has sent to us.
	function DownloadFile( $strField = "file" ) {
		$strUrl = NULL;        
		if ( isset($_GET[$strField]) ) {
			$strUrl = rawurldecode($_GET[$strField]);
		}
        
		if ( NULL == $strUrl || 
			0 === strlen( $strUrl ) || 
			0 !== stripos( $strUrl, "http://www.picnik.com" )) {
			// nothing was sent to us or we got a bad URL, so return NULL
			return NULL;
		}
        
		$data = file_get_contents( $strUrl );
		if (FALSE === $data) return NULL;
		return $data;
	}

?>
<html>
<head>
<script language="javascript" type="text/javascript">
function close() {

        // Check to see if we are still in an iframe.  
	//
	// If we are still inside an iframe, then we can invoke some Javascript and tell the parent
	// to (a) refresh and (b) close the Picnik window.  
	// 
	// If we are not inside an iframe, then redirect back to our root page.  We pass in the id
	// of the image being edited so that the UI can be reset back to how it originally was before launch.
	
        if (parent.frames.length > 0) {		
		<?php 
			// (a) Create a javascript command to tell the parent to refresh
			if ($strRefreshId)
				echo "parent.refreshById( '$strRefreshId', {edit: '$strEditImg', edit_t: '$strEditThumbImg' } );\n";
		?>
		// (b) Let the parent frame close the picnik in a box frame.
		// Firefox doesn't like us closing the doc while we're in the onload callback 
		// (it'll stay stuck in the loading state), so set a very short timeout
		// to break out of this call stack.
		setTimeout( "parent.onPicnikClose()", 10 );
        } else {
		// Sometimes Picnik in a box may leave the box (e.g. authenticating to Flickr)
		// In this case, the user leaves your site and ends up back on Picnik.com.
		// They are then no longer in a frame when they hit close.
		// In this case, you should redirect to an appropriate page on your site
		document.location.replace('/samples/EditGallery/?id=<?php echo $strRefreshId?>');
        }
}
</script>
</head>
<body onload="close()">
<a href="/samples/EditGallery">Stuck here...?</a>
</body>
</html>