<?php
/*    
 *    Copyright (c) 2010 VidiScript
 *
 *    This file is part of VidiScript.
 *
 *    VidiScript is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    VidiScript is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with VidiScript.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    File Name: uploader.php
 *    Description:  Upload functions - http post upload - no progress bar (yet)
 *    $Date: 2010-02-21 23:16:57 +0000 (Sun, 21 Feb 2010) $
 *    $Revision: 12 $
 */ 
include_once("../includes/settings.inc");
include_once("../includes/mysql.inc");
include_once("../includes/loginfunctions.inc");
include_once("../includes/imagefunctions.inc");
global $db;
function uninject($data) {
	// replaces harmful data with safe data
	return str_replace("'", "\'", htmlspecialchars(stripslashes($data))) ;
}
function categoryOptions() {
	global $sitepath,$loggedIn,$templateimagepath ;
	$db = db_connect() ;
	$categories = '' ;
	$sql = "SELECT * FROM `category` WHERE `ptr` = 0 AND parent = '0' ORDER BY name DESC" ;
	$result = mysql_query($sql) or die(mysql_error()) ;
	if ($result) {
		$tmp = '' ;
		while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
			$sel = "" ;
			if ($selected == $row['id'])
				$sel = " selected" ;
			$categories .= "<option$sel value=\"".$row['id']."\">".$row['name']."</option>" ;
			//Subcats
			$db->query("SELECT * FROM category WHERE parent = '".$row['id']."' ORDER BY name") ;
			if ($db->numRows() > 0) {
				$subCats = $db->fetchAll() ;
				foreach ($subCats as $sub) {
					$sel = "" ;
					if ($selected == $sub['id'])
						$sel = " selected" ;
					$categories .= "<option$sel value=\"".$sub['id']."\">--->".$sub['name']."</option>" ;
					//Subsubcats
					$db->query("SELECT * FROM category WHERE parent = '".$sub['id']."' ORDER BY name") ;
					if ($db->numRows() > 0) {
						$subsubCats = $db->fetchAll() ;
						foreach ($subsubCats as $subsub) {
							$sel = "" ;
							if ($selected == $subsub['id'])
								$sel = " selected" ;
							$categories .= "<option$sel value=\"".$subsub['id']."\">------->".$subsub['name']."</option>" ;
						}
					}
				}
			}
		}
	}
	return $categories ;
}
function groupOptions($username) {
	global $sitepath,$loggedIn,$templateimagepath ;
	$db = db_connect() ;
	$db->query("SELECT id FROM member WHERE username = '".quote_smart($username)."'") ;
	$res = $db->fetch() ;
	$memberid = $res['id'] ;
	$joinquery = "SELECT * FROM `group` LEFT JOIN `group_member` ON (`group`.`group_id`=`group_member`.`group_id_g`) WHERE ((`group_member`.`member_id`=".$memberid.") AND (`group_member`.`approved`=1)) OR (`group`.`owner_id`=".$memberid.") GROUP BY `group`.`group_id`" ;
	$db->query($joinquery) ;
	$res = $db->fetchAll() ;
	$groups = "<option value=\"0\" SELECTED>(No Group)</option>" ;
	if ($db->numRows() > 0) {
		foreach ($res as $key=>$value) {
			if (($value['group_id'] == $currentGroupid) && ($currentGroupid != 0)) {
				$selectedString = ' SELECTED' ;
			}
			else {
				$selectedString = '' ;
			}
			$groups .= '<option value="'.$value['group_id'].'"'.$selectedString.'>'.$value['name'].'</option>' ;
		}
	}
	$groups .= "group".$currentGroupid ;
	return $groups ;
}
$portmin = 24000 ;
$portmax = 24100 ;
$uploaddir = "../uploads/" ;

/* Allow the script to hang around waiting for connections. */
set_time_limit(0);

/* Turn on implicit output flushing so we see what we're getting
 * as it comes in. */
ob_implicit_flush();
ob_end_flush();
function getFilenameWithoutExt($filename) {
	$pos = strripos($filename, '.') ;
	if ($pos === false) {
		return $filename ;
	}
	else {
		return substr($filename, 0, $pos) ;
	}
}
// requesting an image
if (isset($_GET['progress'])) {
	header("Content-type: image/png") ;
	$image = imagecreatetruecolor(302, 15) ;
	imagefilledrectangle($image, 0, 0, 302, 15, imagecolorallocate($image, 220, 220, 220)) ;
	imagefilledrectangle($image, 2, 2, ($_GET['progress'] * 3), 13, imagecolorallocate($image, 35, 157, 246)) ;
	$spacers = 0 ;
	while ($spacers < 304) {
		imagefilledrectangle($image, $spacers, 2, $spacers, 13, imagecolorallocate($image, 220, 220, 220)) ;
		$spacers += 10 ;
	}
	imagepng($image) ;
	die() ;
}
// this is the iframe part, it just displays a form
if( isset($_GET['port']) && isset($_GET['addr'])) {
	$poster = uninject($_GET['poster']);
?>
	<form enctype="multipart/form-data" action="http://<?=$_GET['addr']?>:<?=$_GET['port']?>" method="POST">
		<input type="hidden" name="MAX_FILE_SIZE" value="220000000" />
		<table>
			<tr><td>Title</td><td><input type="text" name="title" value="" size="75"/></td></tr>
			<tr><td>Description</td><td><input type="text" name="desc" value="" size="75"/></td></tr>
			<tr><td>Keywords</td><td><input type="text" name="keywords" value="" size="75"/></td></tr>
			<tr><td>Category</td><td><select name="category"> <?php echo categoryOptions();?></select></td></tr>
			<tr><td>Group</td><td><select name="group"> <?php echo groupOptions($poster);?></select></td></tr>
			<tr><td>Upload Media</td><td><input name="media" type="file" size="64" /></td></tr>
			<tr><td>Embed</td><td><textarea name="embed" cols="63"></textarea></td></tr>
			<tr><td>Upload Thumbnail</td><td><input name="thumb" type="file" size="64" /></td></tr>
			<tr><td>Thumbnail URL</td><td><input type="text" name="thumburl" value="" size="75"/></td></tr>
			<tr><td colspan="2"><input type="submit" value="Upload" /></td></tr>
		</table>
	</form>
<?php
	die();
}
// requesting us to handle an upload
if(isset($_GET['upload'])) {
?>
 <div id = "detail" style = "text-align:center;display:none;">
	 <img style = "display:none;"id = "progressbar"src = "?progress=0"> 
	 <br>
	 <div align = "center">
	 	<div style = "background-color:#bbbbbb;width:300px;height:15px;"align = "left">
			<div id = "div1"style = "background-color:#239df6;width:0%;height:15px;">
			</div>
		</div>
	</div>
	<span id = "progress"> </span>
	<script type = "text/javascript"> document.getElementById('progress').innerHTML = 'Waiting for file...' ;
    </script>
 </div> 
<?php
    // the ip address of this server
    $address = $_SERVER['SERVER_ADDR'] ;
    //	echo "address ".$address;
    $addr = $address ;
    srand(time()) ;
    // pick a random port
    $port = rand($portmin, $portmax) ;
    //create a socket
    if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
    	echo "socket_create() failed: reason: ".socket_strerror(socket_last_error())."\n" ;
    }
    //bind to a port
    $try = 0 ;
    while (socket_bind($sock, $address, $port) === false) {
    	// bindingfailed try picking another port
    	$port = rand(4000, 5000) ;
    	$try++ ;
    	if ($try > 10) {
    		// error out after 10 trys
    		die("Failed to get port...") ;
    	}
    }
    // now that we know the ip address and port number we can display the upload form
    echo '<div id="iframe"><iframe src="./uploader.php?poster='.urlencode($_GET['poster']).'&addr='.$addr.'&port='.$port.'" width="100%" style="border: none;height:99%;"></iframe></div>' ;
    // begin to listen for connections
    if (socket_listen($sock, 5) === false) {
    	echo "socket_listen() failed: reason: ".socket_strerror(socket_last_error($sock))."\n" ;
    }
    //this will block until a connection is established
    if (($msgsock = socket_accept($sock)) === false) {
    	echo "socket_accept() failed: reason: ".socket_strerror(socket_last_error($sock))."\n" ;
    	break ;
    }
    echo '<script type="text/javascript">document.getElementById(\'iframe\').style.display=\'none\';document.getElementById(\'detail\').style.display=\'\';</script>' ;
    // update the download bar to reflect were starting to transfer data
    echo '<script type="text/javascript">document.getElementById(\'progress\').innerHTML=\'Progress: 0% done, 0:00 elapsed, 0:00 remain\';</script>' ;
    $read = true ;
    $data = "" ;
    $getpost = false ;
    do {
    	// read data in
    	if (false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))) {
    		echo "socket_read() failed: reason: ".socket_strerror(socket_last_error($msgsock))."\n" ;
    		break 2 ;
    	}
    	$data .= $buf ;
    	// lines end with \r\n were looking for the \n
    	if ($buf == "\n") {
    		$retval = "" ;
    		// see below for parsedata definition
    		switch (parsedata($data, &$retval)) {
    			case 0:
    				// this ends the header information
    				$read = false ;
    				break ;
    			case 1:
    				// ignored data
    				break ;
    			case 2:
    				//we need the is the length of postdata
    				$length = $retval ;
    				$getpost = true ;
    				break ;
    			case 3:
    				// this is the boundary between post elements
    				$boundary = $retval ;
    				break ;
    		}
    		$data = "" ;
    	}
    }
    while ($read) ;
    // ok now look and see if there is post data attached to the http
    $start = time() ;
    if ($getpost) {
    	$read = 0 ;
    	$data = "" ;
    	$lastpct = 0 ;
    	$markpct = 0 ;
    	$mode = 0 ;
    	$postarray ;
    	$filename = "" ;
    	$lastdata = "" ;
    	do {
    		// read data in
    		if (false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))) {
    			echo "socket_read() failed: reason: ".socket_strerror(socket_last_error($msgsock))."\n" ;
    			break 2 ;
    		}
    		$data .= $buf ;
    		// again were looking for \n
    		if ($buf == "\n") {
    			switch ($mode) {
    				// mode 1 is when we need to parse out the key, in the key=>value pairs that were going to make
    				case 1 ;
    				$begin = strpos($data, "name=") + 6 ;
    				$end = strpos(substr($data, ($begin)), '"') ;
    				$name = substr($data, $begin, $end) ;
    				$mode = 2 ;
    				// this checks to see if there is a filename attached
    				if (strstr($data, "filename=")) {
    					$begin = strpos($data, "filename=") + 10 ;
    					$end = strpos(substr($data, ($begin)), '"') ;
    					$filename = substr($data, $begin, $end) ;
    					$mode = 3 ;
    				}
    				break ;
    			case 2 ;
    			// there is a blank line before the value
    			$mode = 4 ;
    			break ;
    		case 3 ;
    		// this is a context mime type, but were ignoring it cause its usually wrong
    		$mode = 5 ;
    		break ;
    	case 4 ;
    	// get the value and dump it in to the postdata array under the proper key
    	$postdata[$name] = trim($data) ;
    	$mode = 0 ;
    	break ;
    case 5 ;
    // this is a blank line befor the actual file data starts
    // add the file name to the postdata array
    if ($filename) {
    	$postdata[$name]['filename'] = str_replace(" ", "_", $uploaddir.$filename) ;
    	$postdata[$name]['nameonly'] = str_replace(" ", "_", $filename) ;
    	$postdata[$name]['withoutext'] = getFilenameWithoutExt($postdata[$name]['nameonly']) ;
    	$filename = "" ;
    	$ext = strtolower(pathinfo($postdata[$name]['filename'], PATHINFO_EXTENSION)) ;
    	if (($ext == "avi") || ($ext == "wmv") || ($ext == "mp4") || ($ext == "mpeg") || ($ext == "mpg")) {
    		exec("mkfifo ".$postdata[$name]['filename'].".pipe") ;
    		encode_video_from_pipe($postdata[$name]['filename']) ;
    		// open the pipe
    		$file = fopen($postdata[$name]['filename'].".pipe", "w") ;
    		$postdata[$name]['type'] = "video" ;
    		$withoutext = getFilenameWithoutExt($postdata[$name]['filename']) ;
    		$postdata[$name]['realfilename'] = $withoutext.'.flv' ;
    	}
    	elseif (($ext == "wma") || ($ext == "ogg") || ($ext == "wav") || ($ext == "ac3")) {
    		// open the file
    		exec("mkfifo ".$postdata[$name]['filename'].".pipe") ;
    		$debug = encode_audio_from_pipe($postdata[$name]['filename']) ;
    		// open the pipe
    		$file = fopen($postdata[$name]['filename'].".pipe", "w") ;
    		$postdata[$name]['type'] = "audio" ;
    		$withoutext = getFilenameWithoutExt($postdata[$name]['filename']) ;
    		$postdata[$name]['realfilename'] = $withoutext.'.mp3' ;
    	}
    	elseif (($ext == "png") || ($ext == "gif") || ($ext == "tif") || ($ext == "tiff") || ($ext == "bmp")) {
    		// open the file
    		$file = fopen($postdata[$name]['filename'], "w") ;
    		$postdata[$name]['type'] = "image" ;
    		$postdata[$name]['realfilename'] = $postdata[$name]['filename'] ;
    	}
    	elseif ( // some stuff thats not allowed
    	 ($ext == "") || ($ext == "exe") || ($ext == "sh") || ($ext == "pl") || ($ext == "php") || ($ext == "inc")) {
    		die("Disallowed file type") ;
    	}
    	elseif ($ext == "flv") {
    		$file = fopen($postdata[$name]['filename'], "w") ;
    		$postdata[$name]['type'] = "video" ;
    		$postdata[$name]['realfilename'] = $postdata[$name]['filename'] ;
    	}
    	elseif ($ext == "mp3") {
    		$file = fopen($postdata[$name]['filename'], "w") ;
    		$postdata[$name]['type'] = "audio" ;
    		$postdata[$name]['realfilename'] = $postdata[$name]['filename'] ;
    	}
    	elseif ($ext == "jpg") {
    		$file = fopen($postdata[$name]['filename'], "w") ;
    		$postdata[$name]['type'] = "image" ;
    		$postdata[$name]['realfilename'] = $postdata[$name]['filename'] ;
    	}
    	elseif ($ext == "swf") {
    		$file = fopen($postdata[$name]['filename'], "w") ;
    		$postdata[$name]['type'] = "flash" ;
    		$postdata[$name]['realfilename'] = $postdata[$name]['filename'] ;
    	}
    	else {
    		// open the file
    		$file = fopen($postdata[$name]['filename'], "w") ;
    	}
    }
    $filesize = 0 ;
    $mode = 6 ;
    break ;
    case 6 ;
    // now were going to be dumping the file data into a file
    // but we want to handle the end of the file specially so
    // were going to post whatever data came through last time
    // ok check to see if we have reached a boundary between elements
    if (strstr($data, $boundary)) {
    	// ok time to clean up a little bit
    	if ($file) {
    		// chop off the trailing \r\n and write the rest of the data
    		$writethis = substr($lastdata, 0, (strlen($lastdata) - 2)) ;
    		fwrite($file, $writethis) ;
    		$filesize += strlen($writethis) ;
    		// close the file
    		fclose($file) ;
    	}
    	// reset the mode
    	$mode = 1 ;
    	$lastdata = "" ;
    }
    else {
    	// update the next rounds data
    	if ($lastdata) {
    		if ($file) {
    			fwrite($file, $lastdata) ;
    			$filesize += strlen($lastdata) ;
    		}
    	}
    	$lastdata = $data ;
    }
    break ;
    default:
    	// ok this searches for the next boundary
    	if (strstr($data, $boundary)) {
    		// and starts the process when found
    		$mode = 1 ;
    	}
    	break ;
    }
    $data = "" ;
    }
    // keep track of the entire amount of data transfered
    $read += strlen($buf) ;
    if (($lastpct + 0.005) <= ($read / $length)) {
    	// calculate the percentage and times that the user wants to know about
    	$lastpct = $read / $length ;
    	$totaltime = (time() - $start) * ($length) / ($read + 1) ;
    	$timeleft = round(($totaltime - (time() - $start)), 0) ;
    	// calculate the average speed
    	$step = (time() - $start) + 1 ;
    	if ($step > 0) {
    		$kbps = number_format($read / $step / 1024, 2) ;
    	}
    	else {
    		$kbps = 0 ;
    	}
    	// update the text
    	echo '<script type="text/javascript">document.getElementById(\'progress\').innerHTML=\'Progress: '.(round($lastpct, 2) * 100).'% done, '.sec2human(time() - $start).' elapsed, '.sec2human($timeleft).' remain, '.($kbps).' kb/s\';</script>' ;
    	echo '<script type="text/javascript">document.getElementById(\'div1\').style.width=\''.(round($lastpct, 2) * 100).'%\';</script>' ;
    }
    }
    while ($read < ($length - 1)) ;
    // this is a special case for if the last of the post data is also the end of a file
    if ($mode = 6) {
    	// we need to flush out our buffer and close the file
    	if ($file) {
    		$writethis = substr($lastdata, 0, (strlen($lastdata) - 2)) ;
    		fwrite($file, $writethis) ;
    		$filesize += strlen($writethis) ;
    		fclose($file) ;
    	}
    }
    // do something with the post data
    process($postdata) ;
    }
    // ok now that were done processing the http request
    // its time to assemble a response
    $msg = 'HTTP/1.1 200 OK'."\r\n".'Connection: close'."\r\n".'Content-Type: text/html'."\r\n".'Content-Length: 349'."\r\n".'Date: Mon, 21 Jul 2008 22:52:53 GMT'."\r\n".'Server: php_uploader/0.0.0'."\r\n"."\r\n".'<?xml version="1.0" encoding="iso-8859-1"
    ?>
    '."\r\n".
    '
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    '."\r\n".
    
     '         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
    ."\r\n".
    
     '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'
    ."\r\n".
    
     ' <head>'
    ."\r\n".
    
     '  <title>Uploading... Please Wait</title>'
    ."\r\n".
    
     ' </head>'
    ."\r\n".
    
     ' <body>'
    ."\r\n".
    
     '  <h1>Complete!!</h1>'
    ."\r\n".
    
     ' </body>'
    ."\r\n".
    
     '</html>'
    ."\r\n\r\n";
    // send the response and close the socket 
    socket_write($msgsock,$msg,strlen($msg));
    socket_close($msgsock);
    // we close our main listner too 
    socket_close($sock);
    ?>
    <script type="text/javascript">
        document.getElementById('progress').innerHTML = 'Transfer Completed in <?php echo sec2human(round($totaltime, 0)); ?>';
    </script>
    <?php
    die() ;
    }
// requesting a ping
if (isset($_GET['ping'])) {
	// respond with our clock skew
	echo time() - $_GET['ping'] ;
}
// requesting we mirror a remote file
if (isset($_GET['mirror'])) {
	if (file_exists($uploaddir.basename($_GET['mirror']))) {
		echo md5_file($uploaddir.basename($_GET['mirror'])) ;
	}
	else {
		// download the remote file
		if ($filename = grabfile($_GET['mirror'], $uploaddir.basename($_GET['mirror']), "fopen")) {
			// calculate the md5 sum of the file
			$md5sum = md5_file($uploaddir.basename($_GET['mirror'])) ;
			// test the md5sum aginst the md5 sum of a blank file
			if ($md5sum == "d41d8cd98f00b204e9800998ecf8427e") {
				// file is empty delete it
				unlink($filename) ;
				// apoligize for the inconvience
				echo "failed" ;
			}
			else {
				// display our md5 sum to the server and let it decide what to do with it
				echo $md5sum ;
			}
		}
	}
}
// requesting that we remove a file
if (isset($_GET['remove'])) {
	// first check to see if the file exists in the first place
	if (file_exists($uploaddir.$_GET['remove'])) {
		// delete the file
		unlink($uploaddir.$_GET['remove']) ;
		// check to ensure success
		if (file_exists($uploaddir.$_GET['remove'])) {
			// print out an error message
			echo "Failed to remove: ".$_GET['remove']."\n" ;
		}
		else {
			// print out debug info
			echo "Success" ;
		}
	}
	else {
		// requested that we delete a non existant file, print out a debug message
		echo "Warn: The file ".$_GET['remove']." dose not exist\n" ;
		// but the problem isnt fatal, so we still succeed
		echo "Success" ;
	}
}
// the core function of this utility
function grabfile($url, $localfile, $mode = "wget") {
	// a few configuration checks
	if (allow_url_fopen) {
		$mode = "fopen" ;
	}
	else {
		if ($mode == "fopen") {
			$mode = "wget" ;
		}
	}
	// if file was sent as post data, then automagically...
	if (isset($_POST['file'])) {
		// change the mode to post
		$mode = "post" ;
	}
	// end of mode checking
	// $mode represents the way were going to grab this file
	switch ($mode) {
		// were goint to uese the php built in fopen wrappers
		case "fopen":
			return grab_fopen($url, $localfile) ;
			break ;
		// were goint to uese the binary program wget
		case "wget":
			return grab_wget($url, $localfile) ;
			break ;
		// were goint to use the supplied POST data
		case "post":
			return grab_post($_POST['file'], $localfile) ;
			break ;
		// TODO: add some AI to try to get this done automatically
		default ;
		return NULL ;
}
// since we cannont get this file we will return NULL
return NULL ;
}
// use the php builtin fopen wrappers to fetch a url and save it as a localfile
function grab_fopen($url, $localfile) {
	// open the local file
	if ($local = fopen($localfile, "w")) {
		// everything went well, so copy the contents from url to the local file
		fwrite($local, file_get_contents($url)) ;
		// clean up
		fclose($local) ;
	}
	// now report back the name of the saved file
	return $localfile ;
}
// use the binary 'wget' to grab the file
function grab_wget($url, $localfile) {
	// run the binary
	exec("/usr/bin/wget $url -O $localfile") ;
	// now report back the name of the saved file
	return $localfile ;
}
function grab_post($postdata, $localfile) {
	if ($local = fopen($localfile, "w")) {
		// everything went well, so copy the contents from one to the other
		fwrite($local, $postdata) ;
		// clean up
		fclose($local) ;
	}
	// now report back the name of the saved file
	return $localfile ;
}
// parse the http header data
function parsedata($data, &$retval) {
	if ($data == "\r\n") {
		// header is over
		return 0 ;
	}
	elseif (strstr($data, "Content-Length: ")) {
		// this signals that there is post data
		$retval = substr($data, 16) ;
		return 2 ;
	}
	elseif (strstr($data, "Content-Type: multipart/form-data; boundary=")) {
		// this is the boundary between elements in the post data
		$retval = substr($data, 44) ;
		return 3 ;
	}
	else {
		// anything else just gets ignored
		return 1 ;
	}
}
// converts seconds to a human readable hh:mm:ss format
function sec2human($seconds) {
	$minutes = 0 ;
	$hours = 0 ;
	while ($seconds >= 60) {
		$seconds -= 60 ;
		$minutes++ ;
	}
	if ($minutes >= 60) {
		while ($minutes >= 60) {
			$minutes -= 60 ;
			$hours++ ;
		}
		$str = "$hours:" ;
		if ($minutes > 9) {
			$str .= "$minutes:" ;
		}
		else {
			$str .= "0$minutes:" ;
		}
		if ($seconds > 9) {
			$str .= "$seconds" ;
		}
		else {
			$str .= "0$seconds" ;
		}
		return $str ;
	}
	else {
		$str = "$minutes:" ;
		if ($seconds > 9) {
			$str .= "$seconds" ;
		}
		else {
			$str .= "0$seconds" ;
		}
		return $str ;
	}
}
// this is the function that process the post data when were all done
function process($post) {
	// report back to mother ship
	if (isset($_GET['sitepath'])) {
		$sitepath = $_GET['sitepath'];
	}
	$report=$sitepath.'includes/control.php';
	if($post['media']['filename'] != "") {
		$report.="?name=".pathinfo($post['media']['filename'], PATHINFO_FILENAME);
		if($post['title'] != "") {
			$report.='&title='.urlencode(str_replace(' ','-',$post['title']));
		} else {
			$report.='&title='.urlencode(pathinfo($post['media']['filename'], PATHINFO_FILENAME));
		}
		if($post['desc'] != "") {
			$report.='&desc='.urlencode($post['desc']);
		}
		if($post['keywords'] != "") {
			$report.='&keywords='.urlencode($post['keywords']);
		}
		if($post['thumburl'] != "") {
			$report.='&thumburl='.urlencode($post['thumburl']);
			$report.='&remotethumb=1';
		} else {
			if($post['thumb']['filename'] != "") {
				$report.='&thumburl='.urlen;code($sitepath."uploads/thumbs/".$post['thumb']['filename']);
			} else {
				if($post['media']['type'] == "video") {
					
					exec("ffmpeg -y -i ../uploads/".$post['media']['withoutext'].".flv -f mjpeg -s 160x120 -vframes 1 -ss 8 -an ../uploads/thumbs/".$post['media']['withoutext'].".flv.jpg");
					
					$report.='&thumburl='.urlencode($sitepath."uploads/thumbs/".$post['media']['withoutext'].".flv.jpg");
					$report.='&thumbname='.urlencode($post['media']['withoutext'].".flv.jpg");
				}
				if($post['media']['type'] == "image") {
					echo "<br>creating thumb.....";
					createThumb($post['media']['filename'], 96, 96, '','../uploads/thumbs/', $post['media']['withoutext'].".thumb.jpg");
					
					echo "<br>done";
					$report.='&thumburl='.urlencode($sitepath."uploads/thumbs/".$post['media']['withoutext'].".thumb.jpg");
					$report.='&thumbname='.urlencode($post['media']['withoutext'].".thumb.jpg");
				}
			}
		}
		if($post['media']['type'] != "") {
			$report.='&type='.urlencode($post['media']['type']);
		}
		$report.='&ip='.$_SERVER['REMOTE_ADDR'];
		$report.='&size='.filesize($post['media']['realfilename']);
		$report.='&md5='.md5_file($post['media']['realfilename']);
		$report.='&category='.$post['category'];
		$report.='&group='.$post['group'];
		if ($sitepath.='') {
			$report.='&sitepath='.urlencode($sitepath);
		}			
		if(isset($_GET['poster'])) {
			if($_GET['poster'] != "") {
				$report.='&poster='.$_GET['poster'];
			}
		}
		echo $report;
		readfile($report);
?>
<h2>Download Complete</h2>
<p>Your media has been uploaded successfully.</p>
<?php
	}
	if($post['embed'] != "") {
		$report.='?embed='.urlencode($post['embed']);
		if($post['title'] != "") {
			$report.='&title='.urlencode($post['title']);
		}
		if($post['desc'] != "") {
			$report.='&desc='.urlencode($post['desc']);
		}
		if($post['keywords'] != "") {
			$report.='&keywords='.urlencode($post['keywords']);
		}
		if($post['thumburl'] != "") {
			$report.='&thumburl='.urlencode($post['thumburl']);
		}
		if($post['media']['type'] != "") {
			$report.='&type=embed';
		}
		$report.='&ip='.$_SERVER['REMOTE_ADDR'];
		$report.='&size=0';
		$report.='&md5=0';
		$report.='&category='.$post['category'];
		$report.='&group='.$post['group'];
		if(isset($_GET['poster'])) {
			if($_GET['poster'] != "") {
				$report.='&poster='.$_GET['poster'];
			}
		}
		readfile($report);
?>
<h2>Download Complete</h2>
<p>Thank you for you submission.</p>
<?php
	}
}
function encode_video_from_pipe($filename) {
	$basename = pathinfo($filename, PATHINFO_DIRNAME)."/".pathinfo($filename, PATHINFO_FILENAME) ;
	$pipes = "" ;
	$cmd = 'ffmpeg -i "'.$filename.'.pipe" -ar 22050 -ab 64 -b 400k -r 25 -f flv "'.$basename.'.flv" && rm "'.$filename.'.pipe" &' ;
	$descriptorspec = array(0=>array("file", "/dev/null", "r"), 1=>array("file", "/dev/null", "w"), 2=>array("file", "/dev/null", "a")) ;
	$process = proc_open($cmd, $descriptorspec, $pipes) ;
	if (is_resource($process)) {
		return proc_close($process) ;
	}
	else {
		return - 200 ;
	}
}
function encode_audio_from_pipe($filename) {
	$basename = pathinfo($filename, PATHINFO_DIRNAME)."/".pathinfo($filename, PATHINFO_FILENAME) ;
	$pipes = "" ;
	$cmd = 'ffmpeg -i "'.$filename.'.pipe" -ab 128 -ac 2 -f mp3 "'.$basename.'.mp3" && rm "'.$filename.'.pipe" &' ;
	$descriptorspec = array(0=>array("file", "/dev/null", "r"), 1=>array("file", "/dev/null", "w"), 2=>array("file", "/dev/null", "w")) ;
	$process = proc_open($cmd, $descriptorspec, $pipes) ;
	if (is_resource($process)) {
		return proc_close($process) ;
	}
	else {
		return - 200 ;
	}
}
?>