<!--
==============================================================================
Filename: index.php

Description: Sample web page that accepts an uploaded document, converts it to
Flash using an external web service and shows the converted Flash document.
The sample demonstrates converting of uploaded documents on another server and
may be used for conversion of documents uploaded to a non-Windows machine by
relying on a web service running on a Windows machine where Print2Flash is installed.

This sample requires an external web service. You may take such a web service
from ASP.NET sample contained in this SDK (see Automation\Samples\ASP.NET folder).

For installation and usage instructions see ReadMe.htm file

This file is part of the Print2Flash OLE Automation SDK samples

Copyright (C) Print2Flash Software. All rights reserved

This source code is intended only as a supplement to Print2Flash OLE
Automation SDK and/or documentation. See Print2Flash documentation
and online help at http://print2flash.com for more information

THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
PARTICULAR PURPOSE.
-->
<?php
// Set this variable to the address of the web service
$WebServiceURL="http://localhost/p2fservice/WebService.asmx?wsdl";
?>
<!doctype html>
<html>
<head>
<TITLE>Convert Document to Flash Using a Web Service</TITLE>
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
</head>
<body>
<H1>Convert Document to Flash Using a Web Service</H1>
<?php
$sourcefile = "";
$swffile = "";

// upload
if (array_key_exists("IsPostBack",$_POST) && $_POST["IsPostBack"])
{
    if (array_key_exists('sourcefile',$_FILES))
    {
		if ($_FILES['sourcefile']['error'] == UPLOAD_ERR_OK)
		{
        	$sourcefile = realpath('uploadedfiles/').'/'.$_FILES['sourcefile']['name'];
        	if (move_uploaded_file($_FILES['sourcefile']['tmp_name'],$sourcefile))
    		{
    			PrintMsg("File uploaded","green");
    		}
    		else
        	{
        		PrintMsg("Error writing file $sourcefile");
        		$sourcefile = "";
        	}
		} else {
			PrintUploadError($_FILES['sourcefile']['error']);
		}
    }
	else
		PrintMsg("Please select a file to convert");
}

// convert
if (strlen($sourcefile))
{
	// convert file
	$outfilename = realpath('convertedfiles/').'/'.basename($sourcefile).'.swf';

	// Setup the ConvertStreamToStream parameters
	$fp=fopen($sourcefile,"r");
	$sourcecontent=fread($fp,filesize($sourcefile));
	fclose($fp);

	$ap_param = array(
	   'inputFile'    =>   $sourcecontent,
	   'FileName'     =>   basename($sourcefile)
	);

	// Call ConvertStreamToStream
	$swffile_fs = realpath('convertedfiles/').'/'.basename($sourcefile).'.swf';
	PrintMsg("Converting $sourcefile => $swffile_fs","green");
	try {
		$soapClient = new SoapClient($WebServiceURL);
		$info = $soapClient->__call("ConvertStreamToStream", array($ap_param));
		$fp=fopen($outfilename,"w+");
		if (fwrite($fp,$info->ConvertStreamToStreamResult)!=strlen($info->ConvertStreamToStreamResult))
			PrintMsg("Cannot write output Flash file");
		else
			$swffile = 'convertedfiles/'.basename($swffile_fs);
		fclose($fp);
	} catch (SoapFault $fault) {
	    PrintMsg("Error communicating with service: ".$fault->faultcode."-".$fault->faultstring);
	}
}
?>
<form method="POST" action=<?php echo$_SERVER["PHP_SELF"];?> enctype="multipart/form-data">
<input type="hidden" name="IsPostBack" value="1"/>
<input type="hidden" name="MAX_FILE_SIZE" value="1000000"/>
Select a file to convert: <INPUT TYPE="file" name="sourcefile"/>
<p><INPUT type="submit" VALUE="Convert File"/>
</form>
<?php
// show swf
if (strlen($swffile))
{
?>
  <!-- Start of document code -->
  <script type="text/javascript" language="JavaScript1.1">
    <!--

 var requiredMajorVersion = 8;
 var requiredMinorVersion = 0;
 var requiredRevision = 0;

 var appVersion=navigator.appVersion.toLowerCase()
 var isIE  = (appVersion.indexOf("msie") != -1) ? true : false;
 var isWin = (appVersion.indexOf("win") != -1) ? true : false;
 var isMac = /mac/.test(appVersion);
 var isSafari = /webkit/.test(appVersion);
 var isOpera = /opera/.test(appVersion);
 var safariVersion = (appVersion.match(/version\/((?:\d|\.)+)/) || [])[1]

 function JSGetSwfVer(i){
    if (navigator.plugins != null && navigator.plugins.length > 0) {
        if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
            var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
            var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
            descArray = flashDescription.split(" ");
            tempArrayMajor = descArray[2].split(".");
            versionMajor = tempArrayMajor[0];
            versionMinor = tempArrayMajor[1];
            if ( descArray[3] != "" ) tempArrayMinor = descArray[3].split("r"); else tempArrayMinor = descArray[4].split("r");
            versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
            flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
        } else flashVer = -1;
    }
    else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
    else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
    else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
    else flashVer = -1;
    return flashVer;
 }

 function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
 {
    reqVer = parseFloat(reqMajorVer + "." + reqRevision);
    for (i=25;i>0;i--) {
        versionStr = JSGetSwfVer(i);
        if (versionStr == -1) return false;
        else if (versionStr != 0) {
            versionArray      = versionStr.split(".");
            versionMajor      = versionArray[0];
            versionMinor      = versionArray[1];
            versionRevision   = versionArray[2];
            versionString     = versionMajor + "." + versionRevision;
            versionNum        = parseFloat(versionString);
            if (versionMajor > reqMajorVer && versionNum >= reqVer) return true; else return ((versionNum >= reqVer && versionMinor >= reqMinorVer) ? true : false );
        }
    }
    return (reqVer ? false : 0.0);
 }

 function GetDoc(movieName) {
    var isIE = navigator.appName.indexOf("Microsoft") != -1;
    return (isIE) ? window[movieName] : document[movieName];
}

var P2FDocs=new Array()
function AddP2FDoc(P2FDoc) {
    P2FDocs.push(P2FDoc);
}

var oldonmousewheel=document.onmousewheel
function mousewheel(event) {
    for (var i=0;i<P2FDocs.length;i++) {
	    if(event.target==P2FDocs[i]) {
		    var delta = 0;
		    if (event.wheelDelta) delta = event.wheelDelta / (isOpera ? 12 : 120);
		        else if (event.detail) delta = -event.detail;
		    if (event.preventDefault) event.preventDefault();
		    try {
		        P2FDocs[i].scrollLine(delta);
		    }
		    catch(e) {
		    }
		    return true;
	    }
	}
	return oldonmousewheel(event)
}

if(isMac || isWin && isSafari && safariVersion<"4.0") {
	if (typeof window.addEventListener != "undefined") window.addEventListener("DOMMouseScroll", mousewheel, false);
	window.onmousewheel = document.onmousewheel = mousewheel;
}

 // -->
  </script>
  <!-- Start of document placement code -->
  <script language="JavaScript" type="text/javascript">
    <!--
 var width="100%"
 var height="500px"
 var align="Middle"
 var url="<?php echo rawurlencode($swffile);?>"
 var name="Print2FlashDoc"

 var alternateContent = 'This content requires the Adobe Flash Player. It either has not been installed yet or is prohibited by your browser security settings. Either'
 	+ ' <a href="http://www.macromedia.com/go/getflash/">click here to get Flash</a> or loosen your browser security restrictions';
 if(isIE && isWin) alternateContent += ' and then <a href="javascript:document.location.reload()">Refresh</a> this page'
 alternateContent += '.'

 if(isIE && isWin) {
     var oeTags = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" '
     + 'width="'+width+'" height="'+height+'" align="'+align+'" id="'+name+'"'
     + 'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version='+requiredMajorVersion+','+requiredMinorVersion+','+requiredRevision+',0">'
     + '<param name="movie" value="'+url+'" /><param name="quality" value="best" />'
     + '<param name="allowScriptAccess" value="sameDomain" />'
     + '<param name="allowFullScreen" value="true" />'
     + '<param name="FlashVars" value="extName='+name+'" />'
     + alternateContent
     + '<\/object>';
     document.write(oeTags);
     AddP2FDoc(GetDoc(name));
   } else if(DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision)) {
     var oeTags = '<embed src="'+url+'" quality="best" '
     + 'width="'+width+'" height="'+height+'" align="'+align+'" name="'+name+'" '
     + 'play="true" '
     + 'loop="false" '
     + 'quality="best" '
     + 'allowScriptAccess="sameDomain" '
     + 'allowFullScreen="true" '
     + 'type="application/x-shockwave-flash" '
     + 'pluginspage="http://www.macromedia.com/go/getflashplayer" '
     + 'FlashVars="extName='+name+'"> '
     + '<\/embed>'
     document.write(oeTags);
     AddP2FDoc(GetDoc(name));
   } else document.write(alternateContent);
  -->
  </script>
  <noscript>
    This content requires scripts to be enabled in your browser. Please enable scripts in your browser settings.
  </noscript>
  <!-- End of document placement code -->

  <!-- End of document code -->

  <?php
}

function PrintMsg($s,$color="red")
{
	echo "<span style=\"color:$color\">".htmlspecialchars($s)."</span><br>";
}

function PrintUploadError($err)
{
	$a_upload_errors = array(
		UPLOAD_ERR_INI_SIZE=>'The uploaded file exceeds the upload_max_filesize directive in php.ini.',
		UPLOAD_ERR_FORM_SIZE=>'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',
		UPLOAD_ERR_PARTIAL=>'The uploaded file was only partially uploaded.',
		UPLOAD_ERR_NO_FILE => 'No file was uploaded.'
	);

	if (array_key_exists($err,$a_upload_errors))
		PrintMsg($a_upload_errors[$err]);
	else
		PrintMsg('File upload error');

}
?>
</body>
</html>
