<?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: upload.inc
 *    Description:  Upload functions - http post upload - no progress bar (yet)
 *    $Date: 2010-03-21 13:24:24 +0000 (Sun, 21 Mar 2010) $
 *    $Revision: 54 $
*/
global $rootpath,$sitepath,$templateimagepath,$isAdmin ;
$progressImage = $templateimagepath.'progress.gif' ;
$playpath = '' ;
$termsLink = "<a href='".$sitepath.'terms'."'>terms of service</a>" ;
$videos_allowed = getSetting("upload_videos", $db) > 0 ;
$music_allowed = getSetting("upload_music", $db) > 0 ;
$images_allowed = getSetting("upload_images", $db) > 0 ;
$games_allowed = getSetting("upload_games", $db) > 0 ;
$nomediaallowed = (!$videos_allowed) && (!$music_allowed) && (!$images_allowed) && (!$games_allowed) ;
$noembed = (getSetting("allow_embed", $db) < 1) ;
if ($isAdmin) {
	$videos_allowed = true ;
	$music_allowed = true ;
	$images_allowed = true ;
	$games_allowed = true ;
	$nomediaallowed = false ;
	$noembed = false ;
}
if ($nomediaallowed) {
	$mediaallowed = '' ;
}
else {
	$mediaallowed = 'You can upload: <b>' ;
	$mediaallowed .= ($videos_allowed) ? ' videos' : '' ;
	$mediaallowed .= ($music_allowed) ? ' music' : '' ;
	$mediaallowed .= ($images_allowed) ? ' images' : '' ;
	$mediaallowed .= ($games_allowed) ? ' games' : '' ;
	$mediaallowed .= '</b>' ;
}
$uploadsdisabled = ($nomediaallowed) && ($noembed) ;
$errorresult = 'ok' ;
$res = 0 ;
function postData() {
	return "&name=".stripslashes($_POST['name'])."&title=".stripslashes($_POST['title'])."&dis=".stripslashes($_POST['dis'])."&tags=".stripslashes($_POST['tags'])."&group=".stripslashes($_POST['group'])."&url=".stripslashes($_FILES['url']['name'])."&thumb=".stripslashes($_FILES['thumbnail']['name'])."&kat=".stripslashes($_POST['kat'])."&thumbnail=".stripslashes($_POST['thumbnail']) ;
}
function sendAdminNotice($poster, $file, $title, $catid) {
	global $db,$sitepath ;
	$fromAdd = "New Upload <http://".$_SERVER['SERVER_NAME'].">" ;
	$messageBody = getEmail("email_upload") ;
	$messageBody = str_replace("[MANAGELINK]", "http://".$_SERVER['SERVER_NAME']."?id=103", $messageBody) ;
	$messageBody = str_replace("[POSTER]", $poster, $messageBody) ;
	/* Get Link */
	$db->query("SELECT name FROM category WHERE id = ".$catid) ;
	$resKat = $db->fetch() ;
	$kat = url_encode($resKat['name']) ;
	$title = url_encode(stripslashes(alphanum($title))) ;
	$mediaLink = $sitepath."play/".$kat."/".$title ;
	$messageBody = str_replace("[MEDIALINK]", $mediaLink, $messageBody) ;
	$filelink = $sitepath."uploads/$file" ;
	$messageBody = str_replace("[FILELINK]", $filelink, $messageBody) ;
	$headers = "From: $fromAdd" ;
	$headers = "From: New Uploads <".getSetting('contact_email', $db).">>\r\n"."Reply-To: ".getSetting('contact_email', $db)."\r\n"."X-Mailer: PHP/".phpversion() ;
	mail(getSetting("contact_email", $db), 'New media Uploaded', $messageBody, $headers) ;
}
$db = new mysql($db_host, $db_user, $db_password, $db_database) ;
//get encoding settings


$encq = getSetting("encoding_quality", $db) ;
$encode_width = getSetting('encode_width', $db) ;
$encode_height = getSetting('encode_height', $db) ;
$path = getSetting("sitefolder", $db) ;
$upload_path = $_SERVER['DOCUMENT_ROOT'].$path.'uploads/' ;
$embedded = trim($_POST['embedcode']) != '' ? 1 : 0 ;
//thumbnail size
$sw = getSetting("thumb_w2", $db) ;
$lw = getSetting("thumb_w1", $db) ;
$sh = getSetting("thumb_h2", $db) ;
$lh = getSetting("thumb_h1", $db) ;
{
	if (isset($_POST['title']) && strlen($_POST['title']) > 0) {
		if (isset($_POST['kat'])) {
			if (isset($_POST['dis']) && strlen($_POST['dis']) > 0) {
				if (isset($_POST['name'])) {
					//set default values for db insert
					$title = alphanum(trim($_POST['title'])) ;
					$title = quote_smart(apply_word_censor2($title)) ;
					$title = str_replace("*", "x", $title) ;
					$cat = quote_smart($_POST['kat']) ;
					$group = quote_smart($_POST['groups']) ;
					$description = quote_smart($_POST['dis']) ;
					$embedcode = quote_smart($_POST['embedcode']) ;
					$description = quote_smart(apply_word_censor2($description)) ;
					$tags = quote_smart($_POST['tags']) ;
					$tags = alphaNumComma($tags) ;
					$mediaurl = "" ;
					$thumb = "" ;
					$poster = quote_smart($_POST['name']) ;
					$extern = "false" ;
					$status = "false" ;
					$useraw = "false" ;
					$url = "" ;
					//get thumbnail time
					$thumbtime = isset($_POST['thumb']) && $_POST['thumb'] != 0 ? $_POST['thumb'] : getSetting('default_thumbtime', $db) ;
					$int = 0 ;
					$db->query("SELECT * FROM `media` WHERE `title` = '".quote_smart($title)."';") ;
					//make title unique
					while ($db->numrows() >= 1) {
						$int++ ;
						$title .= $int ;
						$db->query("SELECT * FROM `media` WHERE `title` = '".quote_smart($title)."';") ;
					}
					//					$filename = md5(uniqid(rand())) . '_' . url_clean($title);
					//$filename = url_clean($title);
					$url = url_encode($title) ;
					$title = quote_smart($title) ;
					//set the time
					$added = time() ;
					if ($isAdmin) {
						if (isset($_POST['day']) && isset($_POST['month']) && isset($_POST['year']) && isset($_POST['hour']) && isset($_POST['minute']) && isset($_POST['second'])) {
							$added = mktime(intval($_POST['hour']), intval($_POST['minute']), intval($_POST['second']), intval($_POST['month']), intval($_POST['day']), intval($_POST['year'])) ;
						}
					}
					//set the status
					if (getSetting("admin_automod", $db) == '1' && $isAdmin) {
						$status = "true" ;
					}
					else {
						if (getSetting("moderate_media", $db) == '1')
						$status = "false" ;
						else
						$status = "true" ;
					}
					/*
					 ******** UPLOAD FILE *************
					 */
					if (($embedded == 1) && (!$noembed)) {
						$dbthumb = '';
						if (! empty($_FILES['uploadthumb']['tmp_name'])) {
							$thumbfilename = str_replace(" ", "_", $_FILES['uploadthumb']['name']) ;
							$thumbfilename = md5(uniqid(rand())).'_'.$thumbfilename ;
							$maxsize = 10000 ;
							if ($_FILES['uploadthumb']['size'] < $maxsize * 1024) {
								$thumbfilename = str_replace(" ", "_", $_FILES['uploadthumb']['name']) ;
								$thumbfilename = md5(uniqid(rand())).'_'.$thumbfilename ;
								//upload the thumbnail if one was specified
								$maxsize = 10000 ;
								if ($_FILES['uploadthumb']['size'] < $maxsize * 1024) {
									$filename = $_FILES['uploadthumb']['name'] ;
									$filename_without_ext = $filename ;
									$ext_pos = strrchr($filename, '.') ;
									if ($ext_pos !== false) {
										$filename_without_ext = substr($filename, 0, -strlen($ext_pos)) ;
									}
									$ext = strtolower(substr($filename, strrpos($filename, '.') + 1)) ;
									$img_exts = array('jpg', 'gif', 'bmp', 'png') ;
									if (array_search($ext, $img_exts) !== FALSE) {
										if (move_uploaded_file($_FILES['uploadthumb']['tmp_name'], 'uploads/thumbs/'.$thumbfilename)) {
											$thumb_name = str_replace("'","",$title);
											createThumb($thumbfilename, getSetting("avatar_h", $db), getSetting("avatar_w", $db), 'uploads/thumbs/', 'uploads/thumbs/', $title.".large.jpg") ;
											createThumb($thumbfilename, getSetting("savatar_h", $db), getSetting("savatar_w", $db), 'uploads/thumbs/', 'uploads/thumbs/', $title.".small.jpg") ;
											$dbthumb = $thumb_name ;
										}
									}
									else {
										$errorresult = "th" ;
									}
								}
							}
						}
						else if (trim($_POST['remotethumb']) != '') {
							createThumb($_POST['remotethumb'], getSetting("savatar_h", $db), getSetting("savatar_w", $db), '', 'uploads/thumbs/', $title.".small.jpg") ;
							createThumb($_POST['remotethumb'], getSetting("avatar_h", $db), getSetting("avatar_w", $db), '', 'uploads/thumbs/', $title.".large.jpg") ;
							$dbthumb = $title ;
						}
						$sql = "INSERT INTO `media` (title, category, description, tags, embed, mediaurl, thumb, poster, added, status, `url`,mediatype,groupid) VALUES ('".$title."', '".$cat."', '".$description."', '".$tags."', '".$embedcode."', '".$title."','".$dbthumb."',
							'".$poster."', '".$added."', '".$status."', '".$url."','embed',".$group."
							)" ;
						$db->query($sql) ;
						if ($status == "true") {
							$catpath = getCategoryPath($cat) ;
							$playpath = $sitepath.'play'.$catpath.'/'.$title ;
						}
					}
					else {
						if (isset($_FILES['url'])) {
							if ($_FILES['url']['error'] == 0) {
								if ($_FILES['url']['size'] < getSetting("mediamaxsize", $db)) {
									$filename = strtolower($_FILES['url']['name']) ;
									$ext = strtolower(substr($filename, strrpos($filename, '.') + 1)) ;
									$filename = preg_replace("/([^0-9a-zA-Z\.]+)/", '', $filename) ;
									$exts = explode(',', strtolower(getSetting('media_filter', $db))) ;
									$vid_exts = array('wmv', 'mov', 'mpg', 'avi', 'flv', 'mpeg', 'mp4', '3gp', 'rm', 'asf') ;
									$img_exts = array('jpg', 'gif', 'bmp', 'png') ;
									$aud_exts = array('mp3', 'midi', 'mid', 'wav', 'wma') ;
									$game_exts = array('swf') ;
									if ((array_search($ext, $vid_exts) !== FALSE) && ($videos_allowed)) {
										//video file
										move_uploaded_file($_FILES['url']['tmp_name'], $rootpath.'uploads/'.$filename) ;
										if (intval(substr(sprintf('%o', fileperms($rootpath.'uploads/'.$filename)), -4)) < 644)
										chmod($rootpath.'uploads/'.$filename, 0644) ;
										if ($ext == 'flv') {
											// FLV does not need to be encoded but thumbnail images are generated with ffmpeg
											$filename_without_ext = $filename ;
											$ext_pos = strrchr($filename, '.') ;
											if ($ext_pos !== false) {
												$filename_without_ext = substr($filename, 0, -strlen($ext_pos)) ;
											}
											$smallthumbsize = $argv[6]."x".$argv[7] ;
											$largethumbsize = $argv[8]."x".$argv[9] ;
											$ffmpegpath = getSetting("ffmpegpath", $db) ;
											//generate thumbnails from new FLV file
											exec($ffmpegpath." -y -i ".$upload_path.$filename_without_ext.".flv -f mjpeg -s ".$sw."x".$sh." -vframes 1 -ss ".$thumbtime." -an ".$upload_path."thumbs/".$filename_without_ext.".small.jpg") ;
											chmod($upload_path."thumbs/".$filename_without_ext.".small.jpg", 0755) ;
											exec($ffmpegpath." -y -i ".$upload_path.$filename_without_ext.".flv -f mjpeg -s ".$lw."x".$lh." -vframes 1 -ss ".$thumbtime." -an ".$upload_path."thumbs/".$filename_without_ext.".large.jpg") ;
											chmod($upload_path."thumbs/".$filename_without_ext.".large.jpg", 0755) ;
											createVideoPreview($filename_without_ext,500) ;
											$sql = "INSERT INTO `media` (title, category, description, tags, mediaurl, thumb, poster, added, status, `url`,mediatype,groupid,embed) VALUES ('".$title."', '".$cat."', '".$description."', '".$tags."', '".$filename_without_ext.".flv', '".$filename_without_ext."',
													'".$poster."', '".$added."', '".$status."', '".$url."','video',".$group.",'')" ;
											$db->query($sql) ;
											if ($status == "true") {
												$catpath = getCategoryPath($cat) ;
												$playpath = $sitepath.'play'.$catpath.'/'.$title ;
											}
										}
										else {
											//video format (not FLV) - encoded with ffmpeg and generate thumbnails
											$php_path = getSetting("phppath", $db) ;
											$filename_without_ext = $filename ;
											$ext_pos = strrchr($filename, '.') ;
											if ($ext_pos !== false) {
												$filename_without_ext = substr($filename, 0, -strlen($ext_pos)) ;
											}
											$thumbtime = getSetting("default_thumbtime", $db) ;
											$audiofrequency = getSetting("audiofrequency", $db) ;
											$audiobitrate = getSetting("audiobitrate", $db) ;
											$videobitrate = getSetting("videobitrate", $db) ;
											$framerate = getSetting("framerate", $db) ;
											$encodesize = getSetting("encodesize", $db) ;
											$encoder_type = getSetting("encoder", $db) ;
											if ($encoder_type == "ffmpeg") {
												//convert to FLV with ffmpeg
												exec(getSetting("ffmpegpath", $db)." -i ".$upload_path.$filename_without_ext.".".$ext." -ar ".$audiofrequency." -ab ".$audiobitrate." -b ".$videobitrate."k -r ".$framerate." -f flv -y -s ".$encodesize." ".$upload_path.$filename_without_ext.".flv 2>&1", $res, $err) ;
											}
											else {
												//convert to FLV with mencoder
												exec(getSetting("mencoderpath", $db)." ".$upload_path.$filename_without_ext.".".$ext." -o ".$upload_path.$filename_without_ext.".flv -of lavf  -oac mp3lame -lameopts abr:br=".$audiobitrate." -srate ".$audiofrequency." -ovc lavc -lavcopts vcodec=flv:vbitrate=".$argv[13].":mbd=2:mv0:trell:v4mv:cbp:last_pred=3 2>&1", $res, $err) ;
											}
											//add meta data - progress bar in player will not always work without this
											exec(getSetting("flvtool2path", $db)." -U ".$upload_path.$filename_without_ext.".flv");
											//send encoder output to log file in uploads folder
											$encoderlog = '' ;
											foreach ($res as $outputline) {
												$encoderlog .= $outputline."<br>" ;
											}
											//echo $encoderlog;
											$outputpath = $upload_path."encoderoutput.html" ;
											$file = fopen($outputpath, "w") ;
											fwrite($file, $encoderlog) ;
											fclose($file) ;
											//delete the original file
											if (getSetting("leavefileonserver", $db) < 1) {
												unlink($upload_path.$filename_without_ext.".".$ext) ;
											}
											$smallthumbsize = $argv[6]."x".$argv[7] ;
											$largethumbsize = $argv[8]."x".$argv[9] ;
											$ffmpegpath = getSetting("ffmpegpath", $db) ;
											//generate thumbnails from new FLV file
											//echo $ffmpegpath." -y -i ".$upload_path.$filename_without_ext.".flv -f mjpeg -s ".$sw."x".$sh." -vframes 1 -ss ".$thumbtime." -an ".$upload_path."thumbs/".$filename_without_ext.".small.jpg";
											exec($ffmpegpath." -y -i ".$upload_path.$filename_without_ext.".flv -f mjpeg -s ".$sw."x".$sh." -vframes 1 -ss ".$thumbtime." -an ".$upload_path."thumbs/".$filename_without_ext.".small.jpg") ;
											chmod($upload_path."thumbs/".$filename_without_ext.".small.jpg", 0755) ;
											//echo $upload_path."thumbs/".$filename_without_ext.".small.jpg";
											exec($ffmpegpath." -y -i ".$upload_path.$filename_without_ext.".flv -f mjpeg -s ".$lw."x".$lh." -vframes 1 -ss ".$thumbtime." -an ".$upload_path."thumbs/".$filename_without_ext.".large.jpg") ;
											chmod($upload_path."thumbs/".$filename_without_ext.".large.jpg", 0755) ;
											//create thumbnail animation
											createVideoPreview($filename_without_ext,500) ;
											$sql = "INSERT INTO `media` (title, category, description, tags, mediaurl, thumb, poster, added, status, `url`,mediatype,groupid,embed) VALUES ('".$title."', '".$cat."', '".$description."', '".$tags."', '".$filename_without_ext.".flv', '".$filename_without_ext."',
													'".$poster."', '".$added."', '".$status."', '".$url."','video',".$group.",'')" ;
											$db->query($sql) ;
											if ($status == "true") {
												$catpath = getCategoryPath($cat) ;
												$playpath = $sitepath.'play'.$catpath.'/'.$title ;
											}
										}
									}
									else if ((array_search($ext, $aud_exts) !== FALSE) && ($music_allowed))
									//audio file
									{
										//upload the file
										//$filename = md5(uniqid(rand())) . '_' . $filename;
										$filename = str_replace(" ", "-", $title).".".$ext ;
										move_uploaded_file($_FILES['url']['tmp_name'], $rootpath.'uploads/'.$filename) ;
										if (intval(substr(sprintf('%o', fileperms($rootpath.'uploads/'.$filename)), -4)) < 644)
										chmod($rootpath.'uploads/'.$filename, 0644) ;
										{
											if ($ext == 'mid' || $ext == 'midi' || $ext == 'mp3') {
												//these audio formats don't need to be encoded (mid, midi and mp3)
												$filename_without_ext = $filename ;
												$ext_pos = strrchr($filename, '.') ;
												if ($ext_pos !== false) {
													$filename_without_ext = substr($filename, 0, -strlen($ext_pos)) ;
												}
												$dbthumb = '' ;
												//upload the thumbnail if one was specified
												if (! empty($_FILES['uploadthumb']['tmp_name'])) {
													$thumbfilename = str_replace(" ", "_", $_FILES['uploadthumb']['name']) ;
													$thumbfilename = md5(uniqid(rand())).'_'.$thumbfilename ;
													$maxsize = 10000 ;
													if ($_FILES['uploadthumb']['size'] < $maxsize * 1024) {
														$filename = $_FILES['uploadthumb']['name'] ;
														$filename_without_ext = $filename ;
														$ext_pos = strrchr($filename, '.') ;
														if ($ext_pos !== false) {
															$filename_without_ext = substr($filename, 0, -strlen($ext_pos)) ;
														}
														$ext = strtolower(substr($filename, strrpos($filename, '.') + 1)) ;
														$img_exts = array('jpg', 'gif', 'bmp', 'png') ;
														if (array_search($ext, $img_exts) !== FALSE) {
															if (move_uploaded_file($_FILES['uploadthumb']['tmp_name'], 'uploads/thumbs/'.$thumbfilename)) {
																createThumb($thumbfilename, getSetting("avatar_h", $db), getSetting("avatar_w", $db), 'uploads/thumbs/', 'uploads/thumbs/', $filename_without_ext.".large.jpg") ;
																createThumb($thumbfilename, getSetting("savatar_h", $db), getSetting("savatar_w", $db), 'uploads/thumbs/', 'uploads/thumbs/', $filename_without_ext.".small.jpg") ;
																$dbthumb = $filename_without_ext ;
															}
														}
														else {
															$errorresult = "th" ;
														}
													}
												}
												//create a thumb from remote URL if specified
												else if (trim($_POST['remotethumb']) != '') {
													$thumb_name = str_replace("'","",$title);
													createThumb($_POST['remotethumb'], getSetting("savatar_h", $db), getSetting("savatar_w", $db), '', 'uploads/thumbs/', $title.".small.jpg") ;
													createThumb($_POST['remotethumb'], getSetting("avatar_h", $db), getSetting("avatar_w", $db), '', 'uploads/thumbs/', $title.".large.jpg") ;
													$dbthumb = $thumb_name ;
												}
												$path = getSetting("sitefolder", $db) ;
												$sql = "INSERT INTO `media` (title, category, description, tags, mediaurl, thumb, poster, added, status, `url`,mediatype,defaultthumb) VALUES
												('".$title."', '".$cat."', '".$description."', '".$tags."', '".$filename."', '".$dbthumb."', 
												'".$poster."', '".$added."', '".$status."', '".$url."','audio',1)" ;
												$db->query($sql) ;
												if ($status == "true") {
													$catpath = getCategoryPath($cat) ;
													$playpath = $sitepath.'play'.$catpath.'/'.$title ;
												}
											}
											else {
												//audio format that needs to be encoded (wav or wma) - use ffmpeg to convert to mp3
												$filename_without_ext = $filename ;
												$ext_pos = strrchr($filename, '.') ;
												if ($ext_pos !== false) {
													$filename_without_ext = substr($filename, 0, -strlen($ext_pos)) ;
												}
												$encoder_type = getSetting("encoder", $db) ;
												if ($encoder_type == "ffmpeg") {
													$encoder_path = getSetting("ffmpegpath", $db) ;
												}
												else {
													$encoder_path = getSetting("mencoderpath", $db) ;
												}
												$thumbtime = getSetting("default_thumbtime", $db) ;
												$audiofrequency = getSetting("audiofrequency", $db) ;
												$audiobitrate = getSetting("audiobitrate", $db) ;
												$videobitrate = getSetting("videobitrate", $db) ;
												$framerate = getSetting("framerate", $db) ;
												$encodesize = getSetting("encodesize", $db) ;
												$encoder_type = getSetting("encoder", $db) ;
												exec(getSetting("ffmpegpath", $db)." -i ".$upload_path.$filename_without_ext.".".$ext." -ab 128 -ac 2 -f mp3 ".$upload_path.$filename_without_ext.".mp3") ;
												if (getSetting("leavefileonserver", $db) < 1) {
													unlink($upload_path.$filename_without_ext.".".$ext) ;
												}
												$filename_without_ext = $filename ;
												$ext_pos = strrchr($filename, '.') ;
												if ($ext_pos !== false) {
													$filename_without_ext = substr($filename, 0, -strlen($ext_pos)) ;
												}
												$dbthumb = '' ;
												if (! empty($_FILES['uploadthumb']['tmp_name'])) {
													$thumbfilename = str_replace(" ", "_", $_FILES['uploadthumb']['name']) ;
													$thumbfilename = md5(uniqid(rand())).'_'.$thumbfilename ;
													//upload the thumbnail if one was specified
													$maxsize = 10000 ;
													if ($_FILES['uploadthumb']['size'] < $maxsize * 1024) {
														$filename = $_FILES['uploadthumb']['name'] ;
														$filename_without_ext = $filename ;
														$ext_pos = strrchr($filename, '.') ;
														if ($ext_pos !== false) {
															$filename_without_ext = substr($filename, 0, -strlen($ext_pos)) ;
														}
														$ext = strtolower(substr($filename, strrpos($filename, '.') + 1)) ;
														$img_exts = array('jpg', 'gif', 'bmp', 'png') ;
														if (array_search($ext, $img_exts) !== FALSE) {
															if (move_uploaded_file($_FILES['uploadthumb']['tmp_name'], 'uploads/thumbs/'.$thumbfilename)) {
																createThumb($thumbfilename, getSetting("avatar_h", $db), getSetting("avatar_w", $db), 'uploads/thumbs/', 'uploads/thumbs/', $filename_without_ext.".large.jpg") ;
																createThumb($thumbfilename, getSetting("savatar_h", $db), getSetting("savatar_w", $db), 'uploads/thumbs/', 'uploads/thumbs/', $filename_without_ext.".small.jpg") ;
																$dbthumb = $filename_without_ext ;
															}
														}
														else {
															$errorresult = "th" ;
														}
													}
												}
												//create a thumb from remote URL if specified
												else if (trim($_POST['remotethumb']) != '') {
													$thumb_name = str_replace("'","",$title);													
													createThumb($_POST['remotethumb'], getSetting("savatar_h", $db), getSetting("savatar_w", $db), '', 'uploads/thumbs/', $title.".small.jpg") ;
													createThumb($_POST['remotethumb'], getSetting("avatar_h", $db), getSetting("avatar_w", $db), '', 'uploads/thumbs/', $title.".large.jpg") ;
													$dbthumb = $thumb_name ;
												}
												$sql = "INSERT INTO `media` (title, category, description, tags, mediaurl, thumb, poster, added, status, `url`,mediatype,defaultthumb) VALUES
													('".$title."', '".$cat."', '".$description."', '".$tags."', '".$filename_without_ext.".mp3', '".$dbthumb."', 
													'".$poster."', '".$added."', '".$status."', '".$url."','audio',1)" ;
												$db->query($sql) ;
												if ($status == "true") {
													$catpath = getCategoryPath($cat) ;
													$playpath = $sitepath.'play'.$catpath.'/'.$title ;
												}
											}
										}
									}
									else if ((array_search($ext, $img_exts) !== FALSE) && ($images_allowed)) {
										//image file
										//$filename = md5(uniqid(rand())) . '_' . $filename;
										$filename = str_replace(" ", "-", $title).".".$ext ;
										move_uploaded_file($_FILES['url']['tmp_name'], $rootpath.'uploads/'.$filename) ;
										if (intval(substr(sprintf('%o', fileperms($rootpath.'uploads/'.$filename)), -4)) < 644)
										chmod($rootpath.'uploads/'.$filename, 0644) ;
										$path = getSetting("sitefolder", $db) ;
										$filename_without_ext = $filename ;
										$ext_pos = strrchr($filename, '.') ;
										if ($ext_pos !== false) {
											$filename_without_ext = substr($filename, 0, -strlen($ext_pos)) ;
										}
										$thumbspath = $_SERVER['DOCUMENT_ROOT'].$path."uploads/thumbs/" ;
										//create thumbnail image from uploaded file
										createThumb($filename, getSetting("avatar_h", $db), getSetting("avatar_w", $db), 'uploads/', 'uploads/thumbs/', $filename_without_ext.".large.jpg") ;
										createThumb($filename, getSetting("savatar_h", $db), getSetting("savatar_w", $db), 'uploads/', 'uploads/thumbs/', $filename_without_ext.".small.jpg") ;
										$sql = "INSERT INTO `media` (title, category, description, tags, mediaurl, thumb, poster, added, status, `url`,mediatype,groupid,embed) VALUES
										('".$title."', '".$cat."', '".$description."', '".$tags."', '".$filename."', '".$filename_without_ext."', 
										'".$poster."', '".$added."', '".$status."', '".$url."','image',".$group.",'')" ;
										$db->query($sql) ;
										if ($status == "true") {
											$catpath = getCategoryPath($cat) ;
											$playpath = $sitepath.'play'.$catpath.'/'.$title ;
										}
									}
									else if ((array_search($ext, $game_exts) !== FALSE) && ($games_allowed)) {
										//flash game file
										//$filename = md5(uniqid(rand())) . '_' . $filename;
										$filename = str_replace(" ", "-", $title).".".$ext ;
										move_uploaded_file($_FILES['url']['tmp_name'], $rootpath.'uploads/'.$filename) ;
										if (intval(substr(sprintf('%o', fileperms($rootpath.'uploads/'.$filename)), -4)) < 644)
										chmod($rootpath.'uploads/'.$filename, 0644) ;
										if ($ext == 'swf') {
											$filename_without_ext = $filename ;
											$ext_pos = strrchr($filename, '.') ;
											if ($ext_pos !== false) {
												$filename_without_ext = substr($filename, 0, -strlen($ext_pos)) ;
											}
											$dbthumb = '' ;
											if (! empty($_FILES['uploadthumb']['tmp_name'])) {
												$thumbfilename = str_replace(" ", "_", $_FILES['uploadthumb']['name']) ;
												$thumbfilename = md5(uniqid(rand())).'_'.$thumbfilename ;
												//upload the thumbnail if one was specified
												$maxsize = 10000 ;
												if ($_FILES['uploadthumb']['size'] < $maxsize * 1024) {
													$filename = $_FILES['uploadthumb']['name'] ;
													$filename_without_ext = $filename ;
													$ext_pos = strrchr($filename, '.') ;
													if ($ext_pos !== false) {
														$filename_without_ext = substr($filename, 0, -strlen($ext_pos)) ;
													}
													$ext = strtolower(substr($filename, strrpos($filename, '.') + 1)) ;
													$img_exts = array('jpg', 'gif', 'bmp', 'png') ;
													if (array_search($ext, $img_exts) !== FALSE) {
														if (move_uploaded_file($_FILES['uploadthumb']['tmp_name'], 'uploads/thumbs/'.$thumbfilename)) {
															createThumb($thumbfilename, getSetting("avatar_h", $db), getSetting("avatar_w", $db), 'uploads/thumbs/', 'uploads/thumbs/', $filename_without_ext.".large.jpg") ;
															createThumb($thumbfilename, getSetting("savatar_h", $db), getSetting("savatar_w", $db), 'uploads/thumbs/', 'uploads/thumbs/', $filename_without_ext.".small.jpg") ;
															$dbthumb = $filename_without_ext ;
														}
													}
												}
												else {
													$errorresult = "th" ;
												}
											}
											//create a thumb from remote URL if specified
											else if (trim($_POST['remotethumb']) != '') {
												$thumb_name = str_replace("'","",$title);													
												createThumb($_POST['remotethumb'], getSetting("savatar_h", $db), getSetting("savatar_w", $db), '', 'uploads/thumbs/', $title.".small.jpg") ;
												createThumb($_POST['remotethumb'], getSetting("avatar_h", $db), getSetting("avatar_w", $db), '', 'uploads/thumbs/', $title.".large.jpg") ;
												$dbthumb = $thumb_name ;
											}
											$sql = "INSERT INTO `media` (title, category, description, tags, mediaurl, thumb, poster, added, status, `url`,mediatype,defaultthumb,groupid) VALUES
											('".$title."', '".$cat."', '".$description."', '".$tags."', '".$filename."', '".$dbthumb."', 
											'".$poster."', '".$added."', '".$status."', '".$url."','flash',1,".$group.")" ;
											$db->query($sql) ;
											if ($status == "true") {
												$catpath = getCategoryPath($cat) ;
												$playpath = $sitepath.'play'.$catpath.'/'.$title ;
											}
										}
									}
									else
									$errorresult = "ff" ;
								}
								else
								$errorresult = "s" ;
							}
							else
							$errorresult = "fe" ;
						}
						else {
							$errorresult = "fn" ;
						}
					}
					if (getSetting("admin_notified", $db) == "1")
					sendAdminNotice($_POST['name'], $filename, $_POST['title'], $_POST['kat']) ;
					$res = 1 ;
				}
				else
				$errorresult = "n" ;
			}
			else
			$errorresult = "d" ;
		}
		else
		$errorresult = "k" ;
	}
	else {
		if (isset($_POST['this']))
		$errorresult = "t" ;
	}
}
?>