<?php

header("Location: https://wizard.modthesims.info/");
exit;

$globaltemplates = array(
	'navbar',
	'headinclude',
	'footer',
	'upload_frontpage',
	'extracss',
);

switch ($_REQUEST['stage']) {
	case 0:
		$globaltemplates[] = "upload_gameselect";
		break;
	case 1: 
		$globaltemplates[] = "upload_selectionbox";
		break;
	case 2:
		$globaltemplates[] = "upload_stage2";
		break;
	case 3:
		$globaltemplates[] = "upload_stage3";
		$globaltemplates[] = "postbit_legacy";
		break;
	case 4:
		$globaltemplates[] = "upload_stage4";
		break;
	case 5:
		$globaltemplates[] = "upload_stage5";
		break;
	case 6:
		$globaltemplates[] = "upload_stage6";
		break;
	case 7:
		$globaltemplates[] = "upload_stage7";
		break;
	case 8:
		$globaltemplates[] = "upload_stage8";
		break;
	case 9:
		$globaltemplates[] = "upload_stage9";
		break;
	case 10:
		$globaltemplates[] = "upload_stage10";
		break;
	case 11:
		$globaltemplates[] = "upload_stage11";
		break;
	case 12:
		$globaltemplates[] = "upload_stage12";
		$globaltemplates[] = "postbit_attachment2";
		$globaltemplates[] = "postbit_attachmentimage2";
		break;
	case 13:
		$globaltemplates[] = "upload_stage13";
		break;

}

$specialtemplates = array(
        'smiliecache',
        'bbcodecache',
);

$phrasegroups = array('threadmanage', 'posting', 'postbit');


define('THIS_SCRIPT', 'newthread');
require_once("./global.php");
require_once("./includes/functions_bbcodeparse.php");
require_once("./includes/functions_newpost.php");
require_once("./classes/statsd.class.php");

$bbuserinfo['styleid'] = 24;

if (($bbuserinfo['usergroupid'] >= 5 && $bbuserinfo[usergroupid] <= 7) || $bbuserinfo[usergroupid] == 45) {
	// Staff are allowed to upload
} else {
#	echo "Uploading of new items to MTS is currently turned OFF so we can have a spring clean of the moderation queues. They'll be back soon.";
#	exit;
}


require_once("./includes/functions_databuild.php");

$expansionpacks = array(
	'gameTS4'		=> 1,
	'gameTS3'		=> 1,
        'gameOrig'              => 1,
        'gameEP1'               => 2,
        'gameEP2'               => 4,
        'gameEP3'               => 8,
        'gameEP4'               => 16,
        'gameEP5'               => 32,
        'gameEP6'               => 64,
        'gameEP7'               => 128,
        'gameEP8'               => 256,
        'gameEP9'               => 512,
        'gameEP10'              => 1024,
        'gameEP11'              => 2048,
        'gameStore'             => 4096,
        'gameSP0'               => 8192,
        'gameSP1'               => 16384,
        'gameSP2'               => 32768,
        'gameSP3'               => 65536,
        'gameSP4'               => 131072,
        'gameSP5'               => 262144,
        'gameSP6'               => 524288,
        'gameSP7'               => 1048576,
        'gameSP8'               => 2097152,
        'gameSP9'               => 4194304,
        'gameSP10'              => 8388608,
        'gameSP11'              => 16777216,
	'gameSP12'		=> 33554432,
	'gameSP13'		=> 67108864,
	'gameSP14'		=> 134217728,
	'gameSP15'		=> 268435456,
	'gameSP16'		=> 536870912,
	'gameSP17'		=> 1073741824,
	'gameSP18'		=> 2147483648,
	'gameSP19'		=> 4294967296,
	'gameSP20'		=> 8589934592,
	'gameSP21'		=> 17179869184,
	'gameSP22'		=> 34359738368,
	'gameSP23'		=> 68719476736,
	'gameSP24'		=> 137438953472,
	'gameSP25'		=> 274877906944,
	'gameSP26'		=> 549755813888,
);

$mydomain = substr($vboptions['cookiedomain'], 1);

// Navbar
  $navbits = array();

// Main section

$navbits["upload.php"] = "Upload Creations";

if (is_member_of($bbuserinfo, 28) || ($bbuserinfo[userid] == 0)) {
  print_no_permission();
  exit;
}

if ($bbuserinfo[userid] <> 1) {
//  echo "Delphy is currently breaking/fixing stuff.... try again later. :)";
//  exit;
}

/* 
  Function overrides
*/

function textBoxStuff($string)
{

	if (isset($_GET['debug'])) { echo "textBoxStuff: ".$string; }

                $edit['message'] = trim($string);

        $edit['message'] = strip_empty_bbcode($edit['message']);

        // add # to color tags using hex if it's not there
        $edit['message'] = preg_replace('#\[color=(&quot;|"|\'|)([a-f0-9]{6})\\1]#i', '[color=\1#\2\1]', $edit['message']);

        // remove /list=x remnants
        if (stristr($edit['message'], '/list=') != false)
        {
                $edit['message'] = preg_replace('#/list=[a-z0-9]+\]#siU', '/list]', $edit['message']);
        }

        // remove extra whitespace between [list] and first element
        $edit['message'] = preg_replace('#(\[list(=(&quot;|"|\'|)([^\]]*)\\3)?\])\s+#i', "\\1\n", $edit['message']);

        $edit['message'] = convert_url_to_bbcode($edit['message']);


                // remove /list=x remnants
                if (stristr($edit['message'], '/list=') != false)
                {
                        $edit['message'] = preg_replace('#/list=[a-z0-9]+\]#siU', '/list]', $edit['message']);
                }

                require_once('./includes/functions_login.php');
                $edit['message'] = fetch_censored_text(fetch_removed_sessionhash($edit['message']));


        return $edit['message'];

}

// Grab PM texts
$result = $DB_site->query("SELECT title, pagetext FROM post WHERE threadid=291414 AND title <> ''");
while ($row = mysql_fetch_array($result)) {
        if ($row['title'] == "Changes Required") { $conditionalPM = $row['pagetext']; }
        if ($row['title'] == "Changes Required - Rubric") { $conditionalPMRubric = $row['pagetext']; }
        if ($row['title'] == "Approved") { $approvePM = $row['pagetext']; }
        if ($row['title'] == "Rejection") { $rejectPM = $row['pagetext']; }
	if ($row['title'] == "Submission") { $submissionPM = $row['pagetext']; }
	if ($row['title'] == "Submission Bypass") { $submissionPMBypass = $row['pagetext']; }
}

function getContentList($posthash) {

		global $isdebug, $DB_site;
		global $bbuserinfo;

                $currentattaches = $DB_site->query("
                        SELECT filename, filesize, zipinfo, zipdetails, attachmentid
                        FROM " . TABLE_PREFIX . "attachment
                        WHERE posthash = '" . addslashes($posthash) . "'
                        AND thumbnail_filesize = 0
                ");


                $contentlist = array();

                $numccs = -1;
                $linknum = 0;

                if ($isdebug) { echo mysql_num_rows($currentattaches)." attachments found<br />"; }

                while ($attach = $DB_site->fetch_array($currentattaches))
                {
                        //echo print_r($attach);
                        if ($isdebug) { echo "Processing....".$attach['attachmentid']." ".$attach['filename']."<br />"; }

			if (!empty($attach['zipdetails'])) {

				$zipdetailsall = unserialize($attach['zipdetails']);

				if ($bbuserinfo['userid'] == 1) {
				//	echo "<pre>".print_r($zipdetailsall, true)."</pre>";
				}

				foreach ($zipdetailsall as $filename => $zipdetails) {
					$zipdetails = $zipdetails['zipdetails'];

					foreach($zipdetails as $pName => $packageFile) {

						if (!is_array($packageFile)) continue;
						if ($pName == "gameversion") continue;

						if ($pName != "lotSegmentForUpload.sims" && $packageFile['type'] !== "Lot") {
							$numccs++;

							$contentlist[$numccs]['filename'] = $pName;
							$contentlist[$numccs]['filesize'] = $packageFile['length'];
							$contentlist[$numccs]['type'] = $packageFile['type'];
							$contentlist[$numccs]['description'] = $packageFile['description'];

                                                	// Check the package database for the Creator and Link
                                        	        if (($contentlist[$numccs]['filename'] != '') && !empty($contentlist[$numccs]['filesize']) && is_numeric($contentlist[$numccs]['filesize'])) {
                                	                        $result = $DB_site->query("/*zipdetailsall*/ SELECT * FROM packagedb WHERE filename='".htmlspecialchars($contentlist[$numccs]['filename'], ENT_QUOTES, "ISO-8859-1")."' and hidden=0 and filesize=".$contentlist[$numccs]['filesize']);
                        	                                $row = $DB_site->fetch_array($result);
                	                                        $contentlist[$numccs]['creator'] = $row['creator'];

								$row['linkurl'] = str_replace("http://www.modthesims2.com/member.php?u=", "http://modthesims.info/m/", $row['linkurl']);

        	                                                $contentlist[$numccs]['link'] = $row['linkurl'];
	                                                }

							$temp1 = explode("<br />", $packageFile['description']);

							$contentlist[$numccs]['title'] = $temp1[0];
						}
					}
				}

				$attach['zipinfo'] = "";

			}

                        if ($attach['zipinfo'] != "") {

                                $blah = explode("<table style='border: 1px dashed #000;' ", $attach['zipinfo']);

                                $blah = $blah[1];
                                $blah = str_replace("cellpadding=3><tr><th>Package file</th><th>Size</th><th>Type</th><th>Description</th></tr>", "", $blah);
                                //$blah = str_replace("</table>", "", $blah);

                                $blah = str_replace("<tr>", "!|!|!|!", $blah);
                                $blah = str_replace("</tr>", "", $blah);

                                $blah = str_replace("<td colspan=2>", "|||||||", $blah);
                                $blah = str_replace("<td align='right'>", "|||||||", $blah);
                                $blah = str_replace("<td>", "|||||||", $blah);
                                $blah = str_replace("<td style='border-bottom: 1px dotted;'>", "|||||||", $blah);
                                $blah = str_replace("</td>", "", $blah);
                                $blah = str_replace("<td align='right' style='border-bottom: 1px dotted;'>", "|||||||", $blah);

                                //echo $blah;

                                $stuff2 = strstr($blah, "</table>");
                                $blah = substr($blah, 0, (strlen($blah) - strlen($stuff2)));


                                $stuff = explode("!|!|!|!", $blah);
                                foreach ($stuff as $meep) {
                                        if (($meep != "") && (strstr($meep, "custom content files") == false)) {
                                                $wark = explode("|||||||", $meep);
                                                if ($isdebug) { echo "<pre>".print_r($wark, true)."</pre>"; }

                                                if ($wark[1] != "lotSegmentForUpload.sims")  {

                                                // Package name
                                                $numccs++;
                                                $contentlist[$numccs]['filename'] = htmlspecialchars($wark[1], ENT_QUOTES, "ISO-8859-1");

                                                // Filesize
                                                $contentlist[$numccs]['filesize'] = $wark[2];

                                                // Type
                                                $contentlist[$numccs]['type'] = $wark[3];

                                                // Description
                                                $contentlist[$numccs]['description'] = $wark[4];
						$contentlist[$numccs]['description'] = str_replace("&nbsp;", "", $contentlist[$numccs]['description']);
						if ($contentlist[$numccs]['description'] == '&nbsp;') {
							$contentlist[$numccs]['description'] = '';
						}

						// Check the package database for the Creator and Link
						if ($contentlist[$numccs]['filename'] != '') {
							$result = $DB_site->query("/*zipinfo*/ SELECT * FROM packagedb WHERE filename='".htmlspecialchars($contentlist[$numccs]['filename'], ENT_QUOTES, "ISO-8859-1")."' and hidden=0 and filesize=".str_replace(",", "", $contentlist[$numccs]['filesize']));
							$row = $DB_site->fetch_array($result);
							$contentlist[$numccs]['creator'] = $row['creator'];
							$contentlist[$numccs]['link'] = $row['linkurl'];
						}

						// Reset back to non htmlspecialchars
						$contentlist[$numccs]['filename'] = $wark[1];
						$contentlist[$numccs]['filesize'] = $wark[2];

		                                // Try and figure out what the package "Title" is
                		                $temp1 = explode("<br />", $wark[4]);
                                		$contentlist[$numccs]['title'] = $temp1[0];
						if ($contentlist[$numccs]['title']  == "&nbsp;") {
							$contentlist[$numccs]['title'] = '';
						}

                                                }

                                        }
                                }
                        }
                }

	return $contentlist;

}

if (!function_exists('htmlspecialchars_decode')) {
function htmlspecialchars_decode ($str, $quote_style = ENT_COMPAT) {
   return strtr($str, array_flip(get_html_translation_table(HTML_SPECIALCHARS, $quote_style)));
}
}

function SendPM($message,$title,$to,$from){
        global $DB_site;
        // Permssions Crap XD your getting a damn PM!! XD
        // Parse It Out
        $title = addslashes(htmlspecialchars_uni(fetch_censored_text($title)));
        $message = addslashes(fetch_censored_text($message));

        $to=$DB_site->query_first("select * from ".TABLE_PREFIX."user where userid='{$to}'");  // Grab Member Its Going TO
        //echo "<pre>".print_r($to, true)."</pre>";
        if($from=="BOT"){
                $from=$DB_site->query_first("select * from ".TABLE_PREFIX."user where userid='{$rpg_option['pmbot']}'"); // FROM Teh Bot =D
        } else {
                $from=$DB_site->query_first("select * from ".TABLE_PREFIX."user where userid='{$from}'"); // Grab Member Its Coming FROM
        }
        // Insert The Message
        $to_string["$to[userid]"] = $to['username'];

//        echo $to_string["$to[userid]"]."<br />";
        $now=time();
        $DB_site->query("insert into ".TABLE_PREFIX."pmtext (fromuserid,fromusername,title,message,touserarray,iconid,dateline,showsignature  ,allowsmilie) values ('{$from['userid']}','".addslashes($from['username'])."','{$title}','{$message}','".addslashes(serialize($to_string))."','4','{$now}','1','1')");
        // id thingy
        $DB_site->query("insert into ".TABLE_PREFIX."pm (pmtextid, userid) values (".$DB_site->insert_id().", '{$to['userid']}')");
        // Update pm count
        $DB_site->shutdown_query("update ".TABLE_PREFIX."user set pmtotal=pmtotal+'1',pmunread=pmunread+'1' WHERE userid='{$to['userid']}'");
}

function build_text_array($parentid = -1, $addbox = 1, $prependchars = '', $permission = '')
{
        global $optionselected, $usecategories, $jumpforumid, $jumpforumtitle, $jumpforumbits, $curforumid, $daysprune;
        global $vboptions, $stylevar, $vbphrase, $defaultselected, $forumjump, $bbuserinfo, $selectedone, $session, $_FORUMOPTIONS;
        global $frmjmpsel; // allows context sensitivity for non-forum areas
        global $iforumcache, $forumcache, $gobutton, $permissions;

        global $textArray, $massforumbits;
	global $uploadstore, $styleinfo;
	global $gameselect;


        if (!isset($iforumcache))
        {
                require_once('./includes/functions_forumlist.php');
                cache_ordered_forums(1, 1);
        }

        if (empty($iforumcache["$parentid"]) OR !is_array($iforumcache["$parentid"])) { return; }

        foreach($iforumcache["$parentid"] AS $holder)
        {
                foreach($holder AS $forumid)
                {

                        $forumperms = $bbuserinfo['forumpermissions']["$forumid"];

			//echo $forumid." - ".$forumcache[$forumid][title]."<br />";

                $forumoptions = array(
                        'MaxisRecolour' => 1,
                        'NewMesh' => 2,
                        'MeshRecolour' => 4,
			'ClosedUploads' => 8,
                );

                $isticked = array(
                        'MaxisRecolour' => 0,
                        'NewMesh' => 0,
                        'MeshRecolour' => 0,
                        'ModerateAll' => 0,
			'ClosedUploads' => 0,
                );

//        foreach ($forumoptions AS $option => $bitfield) {
//                if ($forumcache[$forumid]['mrmqueue'] & $bitfield) { $isticked[$option] = 1; }
//        }

//	echo $forumcache["$forumid"]['title'].": ".$gameselect." - ".$forumcache["$forumid"]['gametype']." == ".($forumcache["$forumid"]['gametype'] & $gameselect)." // ".($gameselect & $forumcache["$forumid"]['gametype'])."<br />";
//	if (($forumcache["$forumid"]['gametype'] & $gameselect) == $gameselect) { echo "Beep<br />"; }

                        if ((!($forumperms & CANVIEW) AND $vboptions['hideprivateforums']) OR !$forumcache["$forumid"]['displayorder'] OR !($forumcache["$forumid"]['options'] & $_FORUMOPTIONS['active']) OR ($forumcache["$forumid"]['link'] != "") OR ($isticked['ClosedUploads'] == 1) OR (!(($forumcache["$forumid"]['gametype'] & $gameselect) == $gameselect))  )
                        {
                                continue;
                        }
                        else
                        {


				switch ($forumid) {
				case 429:
				case 415:
				case 469:
				case 453:
				case 446:
					break;
				default:

				//echo "Forum ".$forumid." info: ".$forumcache["$forumid"]['title']."<br />";

				$size++;

                                $forum = $forumcache["$forumid"];
                                $optionvalue = $forumid;
                                $optiontitle = $prependchars . html_entity_decode($forum[title]);

                                //if (!($forum['options'] & $_FORUMOPTIONS['allowposting'])) { 
				//	if ($parentid == 38) { 
                                //		$massforumbits .= "<option value=\"".$optionvalue."\">".$optiontitle;
				//	} else {
                                                //$optiontitle .= " (No posting)";
                                //		$massforumbits .= "<option value=\"".$optionvalue."\">".$optiontitle."</option>";
				//	}
				//} else {
                                //        if ($parentid == 38) {                                
				//		$massforumbits .= "<option value=\"".$optionvalue."\">".$optiontitle."</option>";
				//	} else {
				//		$massforumbits .= "<option value=\"".$optionvalue."\">".$optiontitle."</option>";	
				//	}
				//}

				//$massforumbits .= "<option value=\"".$optionvalue."\">".$optiontitle;

				if ($forumid <> 139 && $forumid <> 229 && $forumcache[$forumid]['childlist'] != $forumid.",-1") {
					$massforumbits .= "<div id='forum".$forumid."' style='cursor:pointer;' onClick=\"showDiv('branch".$forumid."')\">".$prependchars."[+] <span class='pslink'>".html_entity_decode($forum[title])."</span></div>\n";
					$massforumbits .= "<div id='branch".$forumid."'";
					if (isset($uploadstore['forumID']) && ($uploadstore['forumID'] > 0)) {
						$parentlist = explode(",", $forumcache[$uploadstore['forumID']]['parentlist']);
						if ($isdebug) {  echo print_r($parentlist, true)."<br />"; }
						if (!in_array($forumid, $parentlist)) {
							$massforumbits .= " style='display:none'";
						}
					} else {
						$massforumbits .= " style='display:none'";
					}
					$massforumbits .= ">\n";
				} else {
					$massforumbits .= "<div id='leaf".$forumid."' onClick=\"clickSelect('leaf".$forumid."')\"";
					if (isset($uploadstore['forumID']) && ($uploadstore['forumID'] > 0)) {
						if ($forumid == $uploadstore['forumID']) {
							$massforumbits .= " style=\"background-color: ".$styleinfo[vbmenu_option_bgcolor]."; color: ".$styleinfo[vbmenu_option_fgcolor].";\"";
						}
					}
					$massforumbits .= ">".$prependchars."<span class='pslink'>".html_entity_decode($forum[title])."</span></div>\n";
				}
				//$massforumbits .= "</option>";

                                //$massforumbits .= "<option value=\"".$optionvalue."\">".$optiontitle."</option>";
				$textArray .= "myText['".$optionvalue."'] = '".htmlentities(html_entity_decode($forum[description]), ENT_QUOTES)."';\n";

                                build_text_array($optionvalue, 0, $prependchars . FORUM_PREPEND . "&nbsp;", $forumperms);

				if ($forumcache[$forumid]['childlist'] != $forumid.",-1") {
					$massforumbits  .= "</div>\n";
				}
				//construct_forum_children($optionvalue, 0, $prependchars . FORUM_PREPEND, $forumperms);

				break;
				}

                        } // if can view

                } // end foreach ($holder as $forum)
        } // end foreach ($iforumcache[$parentid] as $holder)

	return $size;

}


function construct_forum_children($parentid = -1, $addbox = 1, $prependchars = '', $permission = '')
{
        global $DB_site, $optionselected, $usecategories, $jumpforumid, $jumpforumtitle, $jumpforumbits, $curforumid, $daysprune;
        global $vboptions, $stylevar, $vbphrase, $defaultselected, $forumjump, $bbuserinfo, $selectedone, $session, $_FORUMOPTIONS;
        global $frmjmpsel; // allows context sensitivity for non-forum areas
        global $iforumcache, $forumcache, $gobutton, $permissions;

        global $massforumbits;
        global $subscribedforums;
        global $forumcategories;

        if (!isset($iforumcache))
        {
                require_once('./includes/functions_forumlist.php');
                cache_ordered_forums(1, 1);
        }

        if (empty($iforumcache["$parentid"]) OR !is_array($iforumcache["$parentid"])) { return; }

        foreach($iforumcache["$parentid"] AS $holder)
        {
                foreach($holder AS $forumid)
                {

                        $forumperms = $bbuserinfo['forumpermissions']["$forumid"];

			if ($isdebug) { echo $forumcache["$forumid"]['title']."<br />"; }

                        if ((!($forumperms & CANVIEW) AND $vboptions['hideprivateforums']) OR !$forumcache["$forumid"]['displayorder'] OR !($forumcache["$forumid"]['options'] & $_FORUMOPTIONS['active']) OR ($forumcache["$forumid"]['link'] != "") )
                        {
                                continue;
                        }
                        else
                        {
                                $forum = $forumcache["$forumid"];
                                $optionvalue = $forumid;
                                $optiontitle = $prependchars . " $forum[title]";

                                if (!($forum['options'] & $_FORUMOPTIONS['allowposting'])) { $optiontitle .= " (No posting)"; }

                                $massforumbits .= "<option value=\"".$optionvalue."\">".$optiontitle."</option>";

                                construct_forum_children($optionvalue, 0, $prependchars . FORUM_PREPEND, $forumperms);


                        } // if can view

                } // end foreach ($holder as $forum)
        } // end foreach ($iforumcache[$parentid] as $holder)
}

// #######################################################################
// ######################## START MAIN SCRIPT ############################
// #######################################################################

if ($_REQUEST['debug'] == "1") { $isdebug = true; } else { $isdebug = false; }
//if ($bbuserinfo[userid] == 1) { $isdebug = true; } 

global $massforumbits;
global $forumcategories;
global $textArray;

if ($isdebug) { echo "Request: <pre>".print_r($_REQUEST, true)."</pre>"; }

/* ========================================================================================

                                 ACTUAL START HERE

=========================================================================================== */

$stage = $_REQUEST['stage'];
//$crumbs = $_REQUEST['crumbs'];
//$uploadType = $_REQUEST['uploadType'];
//$category = $_REQUEST['category'];
$posthash = $_REQUEST['posthash'];
//$stuffser = $_REQUEST['stuffser'];
$gameselect = $_REQUEST['gameselect'];

if ($stage == "") {
	if ($isdebug) { echo "Initial stage setup...<br />"; }
	// DEFAULTS
	$poststarttime = TIMENOW;
	$posthash = md5($poststarttime . $bbuserinfo['userid'] . $bbuserinfo['salt']);
} else {
        if ($posthash == '') { exit; }

	if ($isdebug) { echo "Getting uploadstore...<br />"; }
	$query = "SELECT * FROM uploadstore WHERE posthash='".$posthash."'";
	if ($isdebug) { echo $query."<br />"; }
	$uploadstore = $DB_site->query_first($query);

	if ($uploadstore['poststarttime'] == "") { 
	//	$poststarttime = TIMENOW; 
	} else { 
		$poststarttime = $uploadstore['poststarttime']; 
	}

	if ($stage >= 3) {
	if (empty($uploadstore['posthash'])) { echo "Invalid posthash!"; exit; }
	}

	if ($isdebug) {  echo "<pre>".print_r($uploadstore, true)."</pre>"; }
	$crumbs = $uploadstore['crumbs'];
	$forumID = $uploadstore['forumID'];
	
	if (!isset($gameselect)) { $gameselect = $uploadstore['gameselect']; }
}

                include("/home/mts/db/includes/queueBypass.php");

//if ($stuffser == '') {
//	if ((isset($_REQUEST['stuff'])) && ($_REQUEST['stuff'] != '')) {
//		$stuffser = serialize($_REQUEST['stuff']);
//	}
//} else {
//	$_REQUEST['stuff'] = unserialize($stuffser);
//}
//$meshtype = $_REQUEST['meshtype'];

if ((isset($_POST['refreshlist'])) && ($_POST['refreshlist'] == "Refresh List")) {
//	$customcontent = getContentList($posthash);
	unset($_REQUEST['stuff']);
	$uploadstore[stuffser] = '';
	$DB_site->query("UPDATE uploadstore set stuffser='' WHERE id=".$uploadstore[id]);
}

// User clicked the Back button
if ((isset($_POST['backb'])) && ($_POST['backb'] == "<- Back") )   {

	if ($isdebug) {  echo "Processing back button..... <br />"; }

        // Figure out the Back via the crumbs

	$forumID = $uploadstore[forumID];

	if ($stage <= 2) {

		if ($_REQUEST['crumbs'] != '') { $crumbs = $_REQUEST['crumbs']; }

	        $stuff = explode(",", $crumbs);
	        // Count number in array
        	$crumbs2 = '';
	        if (count($stuff) > 1) {
        	        for($i=0; $i < (count($stuff) - 1); $i++ ) {
                	        //echo $i." ".$stuff[$i]."<br />";
	                        $crumbs2[] = $stuff[$i];
        	                $lastsel = $stuff[$i];
                	}
	                $crumbs = implode(",", $crumbs2);
        	        $_REQUEST['uploadType'] = $lastsel;
			$forumID = $lastsel;
	        } else {
        	        $crumbs = "38";
			$lastsel = 0;
			$forumID = 38;
	        }
//		$DB_site->query("UPDATE uploadstore SET crumbs='".$crumbs."', forumID=".$lastsel." WHERE id=".$uploadstore[id]);

	        $stuff = explode(",", $crumbs);
        	if (count($stuff) > 1) {
	                for($i=0; $i < (count($stuff)); $i++ ) {
                        	$uppertext .= $forumcache[$stuff[$i]]['title']." -> ";
                	        $forumID= $stuff[$i];
        	        }
	        } else {
                	$uppertext = "Downloads";
        	        $forumID= 38;
	        }

	}

        if ($stage == "2") { $stage--; }
        if ($stage == "3") {
		if ($uploadstore[category] == '') {
			// Assume no category for this forum, so go back to stage 1
			$stage = 1;

/*
        	        $stuff = explode(",", $uploadstore['crumbs']);
	                // Count number in array
                	$crumbs2 = '';
        	        if (count($stuff) > 1) {
	                        for($i=0; $i < (count($stuff) - 1); $i++ ) {
                        	        //echo $i." ".$stuff[$i]."<br />";
                	                $crumbs2[] = $stuff[$i];
        	                        $lastsel = $stuff[$i];
	                        }
                        	$crumbs = implode(",", $crumbs2);
                	        $_REQUEST['uploadType'] = $lastsel;
        	                $forumID = $lastsel;

	                } else {
                	        $crumbs = "38";
        	                $lastsel = 0;
	                        $forumID = 38;
        	        }
	        //        $DB_site->query("UPDATE uploadstore SET crumbs='".$crumbs."', forumID=".$lastsel." WHERE id=".$uploadstore[id]);
*/
		} else {
			// Assume category is selected, so we want to pick that again
			$stage = 2;
		}
	}
	if ($stage == "4") { $stage--; }
	if ($stage == "5") {
		$stuffser = serialize($_REQUEST['stuff']);
		$stage--;
	}

	if ($stage == "6") { $stage--; }
	if ($stage == "7") { 
		if ($forumcache[$forumID]['mrm'] == "1") { $stage--; } else { $stage = 5; }
	}
	if ($stage == "8") {
		if (($forumcache[$forumID]['npcat'] == 2) || (($forumcache[$forumID]['mrm'] == "1") && ($uploadstore['meshtype'] == 3))) {
			$stage = 7;
		} else {
			$stage = 5;
		}
	}
	if ($stage == "9") {
		//if ($gameselect == 1) {
			$stage--;
		//}
		/*
		if ($gameselect == 2) {
	                if (($forumcache[$forumID]['npcat'] == 2) || (($forumcache[$forumID]['mrm'] == "1") && ($uploadstore['meshtype'] == 3))) {
                        	$stage = 7;
                	} else {
        	                $stage = 5;
	                }
		}
		*/
		
	}
	if ($stage == "10") {
		$stage--;
	}
        if ($stage == "11") {
                $stage--;
        }
        if ($stage == "12") {
                $stage--;
        }
        if ($stage == "13") {
                $stage--;
        }


}

//if ($stage == 10) {
  for($i = 10; $i <= 64; $i++) {
    $lotSizeX .= "<option value='".$i."'>".$i."</option>";
    $lotSizeY .= "<option value='".$i."'>".$i."</option>";
  }
//}

// User clicked the Next button
if ((isset($_POST['nextb']) && ($_POST['nextb'] == "Next ->")) || (isset($_POST['saveb']) && ($_POST['saveb'] == "Save")))   {

if ((isset($_POST['saveb']) && ($_POST['saveb'] == "Save"))) {
	$issave = true;
} else {
	$issave = false;
}
if ($isdebug) {  echo "Is save: ".$issave."<br />"; }

	if ($stage == 13) {

		// Double check everything

                require_once('./includes/functions_newpost.php');

                $uppertext = $uploadstore[uppertext];
                $forumID = $uploadstore['forumID'];

        	$forumoptions = array(
	                'MaxisRecolour' => 1,
                	'NewMesh' => 2,
        	        'MeshRecolour' => 4,
	        );

	        $isticked = array(
        	        'MaxisRecolour' => 0,
                	'NewMesh' => 0,
	                'MeshRecolour' => 0,
        	        'ModerateAll' => 0,
	        );

		$userinfo = fetch_userinfo($uploadstore['userid']);

                $queueBypassArray = calcQueueBypass($userinfo['userid'], $userinfo['username'], $gameselect);
                $canBypass = $queueBypassArray['fastpass'];

		if (isset($_REQUEST['dontBypass'])) {
			$canBypass = false;
		} 

	        foreach ($forumoptions AS $option => $bitfield) {
        	        if ($forumcache[$forumID]['mrmqueue'] & $bitfield) { $isticked[$option] = 1; }
	        }
		if ($canBypass) {
			$threadupdate[] = "visible = 1";
			$threadupdate[] = "queuebypass = 1";
			StatsD::increment("mts.uploads.approved");
		} else {

			if ($forumcache[$forumID]['mrmqueue'] == 7) { 
				$threadupdate[] = "visible = 0";
			} else {
				if ($uploadstore[meshtype] > 0) {
					if ($uploadstore[meshtype] == 1 && $isticked['MaxisRecolour']) { $threadupdate[] = "visible = 0"; }
					if ($uploadstore[meshtype] == 2 && $isticked['NewMesh']) { $threadupdate[] = "visible = 0"; }
					if ($uploadstore[meshtype] == 3 && $isticked['MeshRecolour']) { $threadupdate[] = "visible = 0"; }
				}
			}
		}



		$forumid = verify_id('forum', $forumID);
		$foruminfo = $forumcache[$forumid];

                        if ($foruminfo[restrictthreads] == 1) {
                                $attachments = $DB_site->query("SELECT * FROM " . TABLE_PREFIX . "attachment WHERE posthash='".$uploadstore[posthash]."'");
                                $numAttachments = 0; $numImgAttachments = 0; $numFileAttachments = 0;
                                while ($attachment = $DB_site->fetch_array($attachments))
                                {
                                        $deleteids[$attachment['attachmentid']] = $attachment['userid'];
                                        $attachment['attachmentextension'] = strtolower(file_extension($attachment['filename']));
                                        switch ($attachment['attachmentextension']) {
                                        case "jpg": $numImgAttachments++; break;
                                        case "rar": $numFileAttachments++; break;
                                        case "zip": $numFileAttachments++; break;
					case "7z": $numFileAttachments++; break;
                                        case "jpeg": $numImgAttachments++; break;
                                        case "gif": $numImgAttachments++; break;
                                        case "png": $numImgAttachments++; break;
                                        case "sims2pack": $numFileAttachments++; break;
                                        case "txt": $numFileAttachments++; break;
                                        }
                                }

                                $numAttachments = $numImgAttachments + $numFileAttachments;
                                if (($numImgAttachments == 0)  || ($numFileAttachments == 0)) {
        	                        $uppertext .= "<br /><span style='color:#ff0000; font-size:2.0em;'>You have not attached the right number of files!</span>(".$numImgAttachments." images, ".$numFileAttachments." archives)<br /><br />";
	                                $error = true;

                                }
                        }

//                       if (isset($vboptions['expansionpacks'])) {

/*
                                foreach($vboptions['expansionpacks'] AS $option => $bitfield) {
                                        //define(strtoupper($option), $bitfield);
                                        if ($uploadstore['gametype'] & $bitfield) {
                                                $gametype[$option] = true;
                                        } else {
                                                $gametype[$option] = false;
                                        }
                                }
                                unset($option, $bitfield);

*/

		$meep = 0;
/*
		foreach($expansionpacks AS $option => $bitfield) {
			if ($uploadstore['epsbitwise'] & $bitfield) {
				//$threadupdate[] = $option." = 1";
				$meep += $bitfield;
			} else {
				//$threadupdate[] = $option." = 0";
			}
		}
		unset($option, $bitfield);
*/

		$meep = intval($uploadstore['epsbitwise']);


//                        }


		if ($uploadstore[gameselect] != 0) { $threadupdate[] = "gametype = ".$uploadstore[gameselect];  }
		//if ($uploadstore[gameselect] == 2) { $meep = 1; }
		//if ($uploadstore[gameselect] == 4) { $meep = 1; }

		if ($meep == 0) {
			//$errors[] = "No games specified!";
			//if ($uploadstore[gameselect] == 4) { $meep = 1; }
			$meep = 1;
		}

		$threadupdate[] = "epsbitwise = ".$meep;
		if ($uploadstore[meshtype] != 0) { $threadupdate[] = "objecttype = ".$uploadstore[meshtype]; }

		if ($uploadstore[keywords] != '') { $threadupdate[] = "keywords = '".mysql_real_escape_string($uploadstore[keywords])."'"; }

		if ($uploadstore[preview] != '') { $threadupdate[] = "preview = '".mysql_real_escape_string($uploadstore[preview])."'"; } else {
			
			//$errors[] = "No preview text specified!";
		}

		//if ($uploadstore[gameselect] == 2) {
			if (trim($uploadstore[patch]) != '') { $threadupdate[] = "patch = '".mysql_real_escape_string($uploadstore[patch])."'"; }
		//}

	        if ($forumid != 38) {
        		if (!$foruminfo['allowposting'] OR $foruminfo['link'] OR !$foruminfo['cancontainthreads'])
		        {
                		eval(print_standard_error('error_forumclosed'));
		        }
	        }
		
		$threadcategory = $uploadstore[category];

                // Custom Content List Formatting

		if (($forumcache[$forumid]['npcat'] == 2) || ($forumcache[$forumid]['npcat'] == 11) || ($forumcache[$forumid]['npcat'] == 50) ) {
	                if (isset($uploadstore[stuffser])) {
        	                $cclist = unserialize($uploadstore[stuffser]);
				if (count($cclist) > 0) {
                	        foreach ($cclist as $ccpackage) {
					if ($ccpackage['meauthor'] == "on") {
						$cctextme .= "\n- ".$ccpackage[title];
					} else {
		                                $cctext .= "\n- ".$ccpackage[title]." by [url=".$ccpackage[link]."]".$ccpackage[creator]."[/url]";
					}
                        	}
			}
                }
                }

                $actualmessage = $uploadstore['message'];

                if ($forumcache[$forumID]['npcat'] == 11) {
                        $actualmessage .= "\n\n[b]Lot Size:[/b] ".$uploadstore[lotsize];
                        $actualmessage .= "\n[b]Lot Price (furnished):[/b] ".$uploadstore[lotprice];
			if (!empty($uploadstore['lotprice_unfurnished'])) {
                        	$actualmessage .= "\n[b]Lot Price (unfurnished):[/b] ".$uploadstore[lotprice_unfurnished];
                	}
		}

                if ($uploadstore[meshtype] == 2) {
                        if ($uploadstore[polycounts] != '') { $actualmessage .= "\n\n[b]Polygon Counts:[/b]\n".$uploadstore[polycounts]; }
                }
		if ($cctextme != '') { $actualmessage .= "\n\n[b]Custom Content by Me:[/b]".$cctextme; }
                if ($cctext != '') { $actualmessage .= "\n\n[b]Custom Content Included:[/b]".$cctext; }
                if ($uploadstore[addcredits] != '') { $actualmessage .= "\n\n[b]Additional Credits:[/b]\n".$uploadstore[addcredits]; }

		$threadupdate[] = "forumid=".$forumid;


			$threadupdate[] = "defaultpic=".$uploadstore[defaultpic];

                $newpost[message] = $actualmessage;

	        // ### THREAD CATEGORY HACK START ###
	        if ($foruminfo['allowcategories'])
        	{
	                $newpost['category'] = $threadcategory;
        	}
	        else
        	{
	                $newpost['category'] = '';
        	}
	        // ### THREAD CATEGORY HACK END ###

        	$newpost['title'] = $uploadstore['subject'];
	        $newpost['iconid'] = 0;
	        $newpost['parseurl'] = 1;
	        $newpost['email'] = 0;
	        $newpost['signature'] = 1;
	        $newpost['preview'] = '';
	        $newpost['disablesmilies'] = 0;
	        $newpost['rating'] = $_POST['rating'];
	        $newpost['username'] = $bbuserinfo[username];
	        $newpost['postpoll'] = 0;
	        $newpost['polloptions'] = 4;
	        $newpost['folderid'] = $_POST['folderid'];
	        $newpost['emailupdate'] = 0;
	        $newpost['poststarttime'] = $uploadstore[poststarttime];
	        $newpost['posthash'] = $uploadstore[posthash];
	        // moderation options
	        $newpost['stickunstick'] = 0;
	        $newpost['openclose'] = 0;
	

		if ($error == false) {

		        $attachdump = 429;
		        $forumid = verify_id('forum', $attachdump);
	
			$foruminfo = fetch_foruminfo($forumid);
	
			build_new_post('thread', $foruminfo, array(), 0, $newpost, $errors);		

		if ($isdebug) { echo "<pre>".print_r($threadupdate, true)."</pre>"; }

	        if (sizeof($errors) > 0)
        	{
                	// ### POST HAS ERRORS ###
	                $postpreview = construct_errors($errors); // this will take the preview's place
			$uppertext .= "<br /><span style='color:#ff0000; font-size:2.0em;'>".$postpreview."</span><br /><br />";
        	}
		else
	        {
			if ($uploadstore[defaultpic] == 0) {

		                $attachments = $DB_site->query("SELECT * FROM " . TABLE_PREFIX . "attachment WHERE postid=".$newpost[postid]." AND thumbnail_filesize > 0 ORDER BY attachmentid ASC LIMIT 1");
        		        $attachment = $DB_site->fetch_array($attachments);
                		if ($attachment['attachmentid'] != "") {
                        		$picarray = array( 'symlink' => $attachment[symlink], 'symlink_thumb' => $attachment[symlink_thumb], 'thumbnail_filesize' => $attachment['thumbnail_filesize'] );
					$threadupdate[] = "defaultpic=".$attachment['attachmentid'];
					$threadupdate[] = "defaultpicarray='".$picarray['symlink']." ".$picarray['symlink_thumb']." ".$picarray['thumbnail_filesize']."'";
					//$threadupdate[] = "defaultpicarray='".serialize($picarray)."'";
				}
			} else {
                                $attachments = $DB_site->query("SELECT * FROM " . TABLE_PREFIX . "attachment WHERE postid=".$newpost[postid]." AND thumbnail_filesize > 0 AND attachmentid=".$uploadstore[defaultpic]);
                                $attachment = $DB_site->fetch_array($attachments);
                                if ($attachment['attachmentid'] != "") {
                                        $picarray = array( 'symlink' => $attachment[symlink], 'symlink_thumb' => $attachment[symlink_thumb], 'thumbnail_filesize' => $attachment['thumbnail_filesize'] );
                                        //$threadupdate[] = "defaultpic=".$attachment['attachmentid'];
					$threadupdate[] = "defaultpicarray='".$picarray['symlink']." ".$picarray['symlink_thumb']." ".$picarray['thumbnail_filesize']."'";
 //                                       $threadupdate[] = "defaultpicarray='".serialize($picarray)."'";
                                }
			}

			// Fix up any attachments with postid  = 0
			$DB_site->query("UPDATE attachment SET postid=".$newpost['postid']." WHERE posthash='".$newpost['posthash']."' AND postid=0 AND userid=".$bbuserinfo['userid']);

	                $DB_site->query("INSERT INTO moderatorlog VALUES (0, " . TIMENOW . ", ".$bbuserinfo[userid].", ".$forumID.", ".$newpost[threadid].", 0, 0, '".$_SERVER[SERVER_NAME]." - Uploadstore ID: $uploadstore[id] <br /> ".mysql_real_escape_string(print_r($threadupdate, true))."')");

	                $DB_site->query("REPLACE INTO subscribethread VALUES (0, ".$bbuserinfo[userid].", ".$newpost[threadid].", 0, 0)");

        	        $stuff = array($uploadstore['mesh1'], $uploadstore['mesh2'], $uploadstore['mesh3'], $uploadstore['mesh4'], $uploadstore['mesh5']);
                	$hasmeshes = 0;
	                foreach ($stuff as $value) {
        	        //foreach ($value2 as $value) {
                	if ($value != "") {
	                        if (strpos(strtolower($value), $mydomain) === false) {
        	                        $DB_site->query("INSERT INTO meshes (id, threadid, mts2link, link) VALUES (0, ".$newpost[threadid].", 0, '".mysql_real_escape_string($value)."')");
                	        } else {
                        	        $value = str_replace("threadid", "t", $value);
	                                $pos = strstr(strtolower($value), "t=");
        	                        //echo $pos."<br />";
                	                if ($pos === false)   {
                        	                $DB_site->query("INSERT INTO meshes (id, threadid, mts2link, link)  VALUES (0, ".$newpost[threadid].", 0, '".mysql_real_escape_string($value)."')");
	                                } else {
        	                                $value = substr($value, strpos(strtolower($value), "t=")+2);

						if (strpos($value, "&") !== false) {
							$value = substr($value, 0, strpos($value, "&") - 1);
						}
                	                        //$value = str_replace("&c=1", "", $value);

                        	                $DB_site->query("INSERT INTO meshes (id, threadid, mts2link, link)  VALUES (0, ".$newpost[threadid].", ".$value.", '')");
                                	        //$DB_site->query("UPDATE thread SET hasrecolours=1 WHERE threadid=".$value);
						$threadupdate[] = "hasrecolours=1";
	                                }
        	                }
                	        $hasmeshes = 1;
	                }
        	        //}
                	}

	                if ($hasmeshes == 1) {
				$threadupdate[] = "hasmeshes=1";
        	                //$DB_site->query("UPDATE thread SET hasmeshes=1 WHERE threadid=".$newpost[threadid]);
                	}

			$DB_site->query("UPDATE thread SET ".implode(', ', $threadupdate)." WHERE threadid=".$newpost[threadid]);

			$rubricCategory = getRubricCategory($forumID);
			$DB_site->query("INSERT INTO rubricupload (userid, gametype, threadid, rubriccat, qstatus, dateline) VALUES (".$uploadstore['userid'].", ".$uploadstore['gameselect'].", ".$newpost['threadid'].", ".$rubricCategory.", 0, ".time().")");

                if (isset($uploadstore['searchparms'])) {

                        $searchp = unserialize($uploadstore['searchparms']);
                        $searchupdate = array();
                        $searchfields = array();
                        foreach ($searchp as $key => $value) {
                                $key = str_replace("p", "", $key);

                                if (is_array($value)) {
                                        $value2 = implode(", ", $value);
                                } else {
                                        $value2 = $value;
                                }

                                $searchupdate[] = "'".mysql_real_escape_string($value2)."'";
                                $searchfields[] = "parm".$key;

                        }

                        if ($bbuserinfo[userid] == 1) {
                        echo "<pre>".print_r($searchfields, true)."</pre>";
                        echo "<pre>".print_r($searchupdate, true)."</pre>";
                        }

                        if (count($searchupdate) > 0) {
                                $DB_site->query("DELETE FROM threadsearch WHERE threadid=".$newpost[threadid]);
                                $DB_site->query("INSERT INTO threadsearch (forumid, threadid, ".implode(", ", $searchfields).") VALUES (".$forumID.", ".$newpost[threadid].", ".implode(", ", $searchupdate).")");
                        }
                }



			$DB_site->query("INSERT INTO threadextra (tid, threadid, qstatus, paysitemesh, uploadpolicy, multiposttext, custominstalltext, relateduploadtext) VALUES (0, ".$newpost[threadid].", 0, ".$uploadstore[paysitemesh].", ".$uploadstore[uploadpolicy].", '".mysql_real_escape_string($uploadstore[multiposttext])."', '".mysql_real_escape_string($uploadstore[custominstalltext])."', '".mysql_real_escape_string($uploadstore[relateduploadtext])."'  )");

			$threadinfo = $DB_site->query_first("SELECT forum.forumid, forum.title as ftitle, thread.* FROM forum, thread WHERE forum.forumid=thread.forumid AND thread.threadid=".$newpost['threadid']);

			if ($threadinfo['visible'] == 1) {
                                $pmbody = $submissionPMBypass;
		                $pmtitle = "Submission of ".$threadinfo[title];

                                $messageb = str_replace("{AUTHOR}", $threadinfo['postusername'], $pmbody);
                                $messageb = str_replace("{UPLOADTITLE}", $threadinfo['title'], $messageb);
                                $messageb = str_replace("{FORUMTITLE}", $threadinfo[ftitle], $messageb);
                                $messageb = str_replace("{THREADID}", $threadinfo[threadid], $messageb);
                                $messageb = str_replace("{EDITPOST}", $threadinfo['firstpostid'], $messageb);
                                $messageb = str_replace("{REASONTEXT}", $reasontext, $messageb);

                                SendPM($messageb, $pmtitle, $threadinfo['postuserid'], 34554);

			}

		        if ($threadinfo['visible'] == 0) {

                		$pmbody = $submissionPM;
		                $pmtitle = "Submission of ".$threadinfo[title];

		                $messageb = str_replace("{AUTHOR}", $threadinfo['postusername'], $pmbody);
		                $messageb = str_replace("{UPLOADTITLE}", $threadinfo['title'], $messageb);
		                $messageb = str_replace("{FORUMTITLE}", $threadinfo[ftitle], $messageb);
		                $messageb = str_replace("{THREADID}", $threadinfo[threadid], $messageb);
		                $messageb = str_replace("{EDITPOST}", $threadinfo['firstpostid'], $messageb);
		                $messageb = str_replace("{REASONTEXT}", $reasontext, $messageb);

		                SendPM($messageb, $pmtitle, $threadinfo['postuserid'], 34554);
		        } else {
				// Insert packages into database

			if ($uploadstore[stuffser] != '') {

			$_REQUEST['stuff'] = unserialize($uploadstore[stuffser]);
                foreach($_REQUEST['stuff'] as $key => $value) {
                        $value['filename'] = trim($value['filename'],"\x7f..\xff\x0..\x1f");
                        $value['filesize'] = trim($value['filesize'],"\x7f..\xff\x0..\x1f");
                        $value['title'] = trim($value['title'],"\x7f..\xff\x0..\x1f");
                        $value['creator'] = trim($value['creator'],"\x7f..\xff\x0..\x1f");
                        $value['link'] = trim($value['link'],"\x7f..\xff\x0..\x1f");

                        if (($value['filename'] == '') || ($value['filesize'] == '') || ($value['title'] == '')) {
                                $ismissing = true;
                        } else {
                                $value['filename'] = htmlspecialchars_decode($value['filename'], ENT_QUOTES);
                                $value['title'] = htmlspecialchars_decode($value['title'], ENT_QUOTES);
                                $value['creator'] = htmlspecialchars_decode($value['creator'], ENT_QUOTES);
                                $value['link'] = htmlspecialchars_decode($value['link'], ENT_QUOTES);
                                $value['description'] = htmlspecialchars_decode($value['description'], ENT_QUOTES);

                                $_REQUEST['stuff'][$key]['filename'] = $value['filename'];
                                $_REQUEST['stuff'][$key]['title'] = $value['title'];
                                $_REQUEST['stuff'][$key]['creator'] = $value['creator'];
                                $_REQUEST['stuff'][$key]['link'] = $value['link'];
                                $_REQUEST['stuff'][$key]['description'] = $value['description'];

                        }

                        if ($ismissing == false) {
                                if (($value['creator'] == ''))  {
                                        if ((isset($_REQUEST['stuff'][$key]['meauthor'])) && ($_REQUEST['stuff'][$key]['meauthor'] == "on")) {
                                                //$creatorstring = "[url=http://www.modthesims2.com/member.php?u=".$bbuserinfo[userid]."]".$value['title']." by ".$bbuserinfo[username]." at ModTheSims2[/url]\r\n";
                                                //echo $creatorstring."<br />";
                                                //$creditslist .= $creatorstring;

                                                $dbitem = $DB_site->query_first("/*blargh*/ SELECT * FROM packagedb WHERE filename='".htmlspecialchars($value['filename'], ENT_QUOTES, "ISO-8859-1")."' and hidden=0 AND filesize=".str_replace(",", "", $value['filesize']));
                                                if ($dbitem == '') {
//                                                        $DB_site->query("INSERT INTO packagedb (id, filename, filesize, creator, linkurl, title, userid, description)  VALUES (0, '".mysql_real_escape_string($value['filename'])."', ".str_replace(",", "", $value['filesize']).", '".mysql_real_escape_string($bbuserinfo[username])."', 'http://www.modthesims2.com/member.php?u=".$bbuserinfo[userid]."', '".mysql_real_escape_string($value['title'])."', ".$bbuserinfo[userid].", '".mysql_real_escape_string($value['description'])."')");
                                                }
                                        } else {
                                                $ismissing = true;
                                        }
                                } else {
                                       if ($value['link'] != '') {
                                                //$creatorstring = "[url=".$value['link']."]".$value['title']." by ".$value['creator']."[/url]\r\n";
                                                //echo $creatorstring."<br />";
                                                //$creditslist .= $creatorstring;

                                                $dbitem = $DB_site->query_first("/*burgle*/SELECT * FROM packagedb WHERE filename='".htmlspecialchars($value['filename'], ENT_QUOTES, "ISO-8859-1")."' and hidden=0 AND filesize=".str_replace(",", "", $value['filesize']));
                                                if ($dbitem == '') {
//                                                        $DB_site->query("INSERT INTO packagedb (id, filename, filesize, creator, linkurl, title, userid, description) VALUES (0, '".mysql_real_escape_string($value['filename'])."', ".str_replace(",", "", $value['filesize']).", '".mysql_real_escape_string($value['creator'])."', '".mysql_real_escape_string($value['link'])."', '".mysql_real_escape_string($value['title'])."', 0, '".mysql_real_escape_string($value['description'])."')");
                                                }

                                        } else {
                                                $ismissing = true;
                                        }

                                }
                        }
		}
		}

			}

			// Cleanup
			//$DB_site->query("DELETE FROM uploadstore WHERE id=".$uploadstore['id']);
			$DB_site->query("UPDATE uploadstore SET hidden=1, threadid=".$newpost[threadid]." WHERE id=".$uploadstore['id']);

 //               	$redirectServer = '';
//        	        if ((($bbuserinfo[usergroupid] < 5) || ($bbuserinfo[usergroupid] > 7)) && ($bbuserinfo[usergroupid] != 20) && ($bbuserinfo[usergroupid] != 10) && ($bbuserinfo[usergroupid] != 18))
//	                {
//                	        $redirectServer = "http://www.".$mydomain."/";
//        	        }
			$redirectServer = "http://www.".$mydomain."/";

			//if ($threadinfo['visible'] == 0) {

	                // ### NOT PREVIEW - ACTUAL POST ###
/*
                	if ($newpost['postpoll'])
        	        {
	                        $url = $redirectServer."poll.php?$session[sessionurl]t=$newpost[threadid]&amp;polloptions=$newpost[polloptions]";
                	}
        	        else if ($newpost['visible'])
	                {
                	        $url = $redirectServer."showthread.php?$session[sessionurl]t=$newpost[threadid]#post$newpost[postid]";
        	        }
	                else
        	        {
	                        $_REQUEST['forceredirect'] = 1;
                        	//$url = $redirectServer."download.php?$session[sessionurl]f=$foruminfo[forumid]";
                	        $url = $redirectServer."usercp.php";
        	        }
*/
			$url = $redirectServer."download.php?$session[sessionurl]&t=$newpost[threadid]&posted=1";
	                eval(print_standard_redirect('redirect_postthanks'));

                }

		}

	}

	if ($stage == 12) {
                $uppertext = $uploadstore[uppertext];
                $forumID = $uploadstore['forumID'];

/*
		// Check for everything
		$customcontent = unserialize($uploadstore['stuffser']);
		$customcontent2 = getContentList($posthash);
		if (count($customcontent) != count($customcontent2)) {
                                $uppertext .= "<br /><span style='color:#ff0000; font-size:2.0em;'>You have not filled in your Custom Content List!</span><br /><br />";
                                $error = true;
		}

		if (!$error) {
			$stage++;
		}
*/


		$stage++;

	}

	if ($stage == 11) {
                $uppertext = $uploadstore[uppertext];
                $forumID = $uploadstore['forumID'];
		$error = false;

/*
		if ($forumcache[$forumID]['npcat'] == 11) {
			if (($_POST['dim_x'] != '') && ($_POST['dim_y'] != '')) {
				$lotsize = "lotsize='".mysql_real_escape_string($_POST['dim_x']."x".$_POST['dim_y'])."', ";

				$dimx[$_POST['dim_x']] = "selected";
				$dimy[$_POST['dim_y']] = "selected";

			} else {
				$uppertext .= "<br /><span style='color:#ff0000; font-size:2.0em;'>You have not specified a lot size!</span><br /><br />";
				$error = true;
			}
			if ($_POST['lotprice'] != '') {
				$lotprice = "lotprice='".mysql_real_escape_string($_POST['lotprice'])."', ";	
				$uploadstore[lotprice] = $_POST['lotprice'];
			} else {
                                $uppertext .= "<br /><span style='color:#ff0000; font-size:2.0em;'>You have not specified a lot price!</span><br /><br />";
                                $error = true;
			}

		}

		if (!isset($_POST['polycounts']) && ($uploadstore[meshtype] == 2)) {
                        $uppertext .= "<br /><span style='color:#ff0000; font-size:2.0em;'>You have not specified the polygon counts for the meshes!</span><br /><br />";
                        $error = true;
		}
*/

		if (!isset($_POST['defaultpic'])) { 
                        $uppertext .= "<br /><span style='color:#ff0000; font-size:2.0em;'>You have not specified a default picture!</span><br /><br />";
                        $error = true;
		}

		if ($error == false) {
			if ($uploadstore[maxstage] <= 11) { $uploadstore[maxstage] = 11; $setmaxstage = 'maxstage=11, '; } else { $setmaxstage = ''; }
//        	        $DB_site->query("UPDATE uploadstore SET ".$lotsize.$lotprice.$setmaxstage."keywords='".mysql_real_escape_string($_REQUEST['keywords'])."', polycounts='".mysql_real_escape_string($_REQUEST['polycounts'])."', defaultpic=".$_POST[defaultpic]." WHERE id=".$uploadstore[id]);
                        $DB_site->query("UPDATE uploadstore SET ".$setmaxstage."keywords='".mysql_real_escape_string($_REQUEST['keywords'])."', defaultpic=".$_POST[defaultpic]." WHERE id=".$uploadstore[id]);
			$uploadstore[keywords] = $_REQUEST['keywords'];
			$uploadstore[defaultpic] = $_POST['defaultpic'];

			if (!$issave) {
			$stage++;
			}
		}
	}

	/* Stage 10 Next */
	if ($stage == 10) {
                $uppertext = $uploadstore[uppertext];
                $forumID = $uploadstore['forumID'];

		$error = false;

			 $uploadstore[preview] = trim(htmlspecialchars_decode($_REQUEST['preview'], ENT_QUOTES), "\x7f..\xff\x0..\x1f");

                        $uploadstore[message] = trim(htmlspecialchars_decode($_REQUEST['message'], ENT_QUOTES), "\x7f..\xff\x0..\x1f");
                        $uploadstore[subject] = trim(htmlspecialchars_decode($_REQUEST['subject'], ENT_QUOTES), "\x7f..\xff\x0..\x1f");
                        $uploadstore[polycounts] = trim(htmlspecialchars_decode($_REQUEST['polycounts'], ENT_QUOTES), "\x7f..\xff\x0..\x1f");
                        $uploadstore[addcredits] = trim(htmlspecialchars_decode($_REQUEST['addcredits'], ENT_QUOTES), "\x7f..\xff\x0..\x1f");

		if ($uploadstore['subject'] == '') {
			$uppertext .= "<br /><span style='color:#ff0000; font-size:2.0em;'>You have not added a subject!</span><br /><br />";			                        $error = true;
		}
                if ($uploadstore['message'] == '') {
                        $uppertext .= "<br /><span style='color:#ff0000; font-size:2.0em;'>You have not written any text!</span><br /><br />";
                        $error = true;
                }

/*
                if (isset($_POST['searchp'])) {

                        $searchp = $_POST['searchp'];
                        $searchupdate = array();
                        $searchfields = array();
                        foreach ($searchp as $key => $value) {
                                $key = str_replace("p", "", $key);

                                if (count($value) > 1) {
                                        $value2 = implode(", ", $value);
                                } else {
                                        $value2 = $value;
                                }

                                $searchupdate[] = "'".mysql_real_escape_string($value2)."'";
                                $searchfields[] = "parm".$key;

                        }

                        if ($bbuserinfo[userid] == 1) {
                        echo "<pre>".print_r($searchfields, true)."</pre>";
                        echo "<pre>".print_r($searchupdate, true)."</pre>";
                        }

                        if (count($searchupdate) > 0) {
                                $DB_site->query("DELETE FROM threadsearch WHERE threadid=".$threadinfo[threadid]);
                                $DB_site->query("INSERT INTO threadsearch (forumid, threadid, ".implode(", ", $searchfields).") VALUES (".$threadinfo[forumid].", ".$threadinfo[threadid].", ".implode(", ", $searchupdate).")");
                        }
		}
*/
        // Does this forum have search parameters?
        $fsearchparms = array();
        if ($forumcache[$forumID]['searchparms'] != '') {
                $fsearchparms = unserialize($forumcache[$forumID]['searchparms']);
        } else {
                // Check forums parent
                if ($forumcache[$forumcache[$forumID]['parentid']]['searchparms'] != '') {
                        $fsearchparms = unserialize($forumcache[$forumcache[$forumID]['parentid']]['searchparms']);
                }
        }

        if (count($fsearchparms) > 0) {

		if ($bbuserinfo['userid'] == 1) { echo "<pre>Search P: ".print_r($_POST['searchp'], true)."</pre>"; }

		$searchErrors = '';

                for($i = 1; $i <= 10; $i++) {

	                if ($fsearchparms['t'.$i] != '') {

				if (!isset($_POST['searchp']['p'.$i])) { $searchErrors =  "<br /><span style='color:#ff0000; font-size:2.0em;'>You have not filled in all the search parameters!</span><br /><br />"; }

			}

		}		

		if (isset($_POST['searchp'])) {
	                $uploadstore[searchparms] = serialize($_POST['searchp']);
		}

		if ($searchErrors == '') {
			$searchparms_cad = "searchparms='".mysql_real_escape_string(serialize($_POST['searchp']))."', ";
		} else {
			$uppertext .= $searchErrors;
			$error = true;
		}


	}

  //              }


                if ($forumcache[$forumID]['npcat'] == 11) {
                        if (($_POST['dim_x'] != '') && ($_POST['dim_y'] != '')) {
                                $lotsize = "lotsize='".mysql_real_escape_string($_POST['dim_x']."x".$_POST['dim_y'])."', ";

                                $dimx[$_POST['dim_x']] = "selected";
                                $dimy[$_POST['dim_y']] = "selected";

                        } else {
                                $uppertext .= "<br /><span style='color:#ff0000; font-size:2.0em;'>You have not specified a lot size!</span><br /><br />";
                                $error = true;
                        }
                        if ($_POST['lotprice'] != '') {
                                $lotprice = "lotprice='".mysql_real_escape_string($_POST['lotprice'])."', ";
                                $uploadstore[lotprice] = $_POST['lotprice'];
                        } else {
                                $uppertext .= "<br /><span style='color:#ff0000; font-size:2.0em;'>You have not specified a lot price!</span><br /><br />";
                                $error = true;
                        }
			if ($_POST['lotprice_unfurnished'] != '') {
                                $lotprice_unfurnished = "lotprice_unfurnished='".mysql_real_escape_string($_POST['lotprice_unfurnished'])."', ";
                                $uploadstore[lotprice_unfurnished] = $_POST['lotprice_unfurnished'];
			}	

			if (($_POST['nocustomcontent'] != '') && ($_POST['nocustomcontent'] == "on")) {
				$uploadstore[nocustomcontent] = 1;
				$nocustomcontent = "nocustomcontent = 1, ";
			}

                }

                if (trim($uploadstore[polycounts],"\x7f..\xff\x0..\x1f") == '' && ($uploadstore[meshtype] == 2)) {
                        $uppertext .= "<br /><span style='color:#ff0000; font-size:2.0em;'>You have not specified the polygon counts for the meshes!</span><br /><br />";
                        $error = true;
                }

		if ($error == false) {

		        if (isset($_POST['WYSIWYG_HTML']))
		        {
		                require_once('./includes/functions_wysiwyg.php');
		                $newpost['message'] = convert_wysiwyg_html_to_bbcode($_POST['WYSIWYG_HTML'], $forumcache[$forumID]['allowhtml']);
		        }
		        else
		        {
		                $newpost['message'] = &$_POST['message'];
		        }

//			$_REQUEST['subject'] = ashes($_REQUEST['subject']);

			if ($uploadstore[maxstage] <= 10) { $uploadstore[maxstage] = 10; $setmaxstage = 'maxstage=10, '; } else { $setmaxstage = ''; }


			if (isset($_GET['debug'])) { echo $uploadstore['message']; }
                        $uploadstore[message] = htmlspecialchars_decode($newpost['message'], ENT_QUOTES);

                        $multiposttext = addslashes(textBoxStuff($_REQUEST['multiposttext']));


                        if ($_REQUEST['custominstalltextselect'] == "0") {
                                // Do nothing
				$custominstalltext = '';
                        } else {
                                if ($_REQUEST['custominstalltextselect'] == "Install Instructions - Custom:") {
                                        $custominstalltext = addslashes(textBoxStuff($_REQUEST['custominstalltexttext']));
                                } else {
                                        $custominstalltext = $_REQUEST['custominstalltextselect'];
                                }
                        }
                        $relateduploadtext = addslashes(textBoxStuff($_REQUEST['relateduploadtext']));

                        $DB_site->query("UPDATE uploadstore SET ".$searchparms_cad.$nocustomcontent.$lotsize.$lotprice.$lotprice_unfurnished.$setmaxstage."message='".mysql_real_escape_string($uploadstore['message'])."', subject='".mysql_real_escape_string($uploadstore['subject'])."', polycounts='".mysql_real_escape_string($uploadstore['polycounts'])."', addcredits='".mysql_real_escape_string($uploadstore['addcredits'])."', multiposttext = '".$multiposttext."', custominstalltext='".$custominstalltext."', relateduploadtext='".$relateduploadtext."', preview='".mysql_real_escape_string($uploadstore[preview])."' WHERE id=".$uploadstore[id]);

			if (!$issave) {
			$stage++;
			}

		}

	}

	if ($stage == 9) {

                $uppertext = $uploadstore[uppertext];
                $forumID = $uploadstore['forumID'];

		if (isset($_POST['usepolicy']) && ($_POST['usepolicy'] == "0")) {
			$mypolicies = 0;
		} else {

		        if (isset($_REQUEST['lotpolicym'])) { if ($_REQUEST['lotpolicym'] == 1) { $policy['lotpolicym'] = 1; } else { $policy['lotpolicym'] = 0; } }
		        if (isset($_REQUEST['lotpolicyr'])) { if ($_REQUEST['lotpolicyr'] == 1) { $policy['lotpolicyr'] = 1; } else { $policy['lotpolicyr'] = 0; } }
	        	if (isset($_REQUEST['lotpolicyw'])) { if ($_REQUEST['lotpolicyw'] == 1) { $policy['lotpolicyw'] = 1; } else { $policy['lotpolicyw'] = 0; } }
		        if (isset($_REQUEST['simspolicym'])) { if ($_REQUEST['simspolicym'] == 1) { $policy['simspolicym'] = 1; } else { $policy['simspolicym'] = 0; } }
        		if (isset($_REQUEST['simspolicyr'])) { if ($_REQUEST['simspolicyr'] == 1) { $policy['simspolicyr'] = 1; } else { $policy['simspolicyr'] = 0; } }
	        	if (isset($_REQUEST['simspolicyw'])) { if ($_REQUEST['simspolicyw'] == 1) { $policy['simspolicyw'] = 1; } else { $policy['simspolicyw'] = 0; } }

		        if (isset($_REQUEST['mesh1policym'])) { if ($_REQUEST['mesh1policym'] == 1) { $policy['mesh1policym'] = 1; } else { $policy['mesh1policym'] = 0; } }

        		if (isset($_REQUEST['reusetexturepolicym'])) { if ($_REQUEST['reusetexturepolicym'] == 1) { $policy['reusetexturepolicym'] = 1; } else { $policy['reusetexturepolicym'] = 0; } }

	        	foreach ($checkboxes as $value) {
        	        	if (isset($_REQUEST[$value])) { if ($_REQUEST[$value] == "on") { $policy[$value] = 1; } else { $policy[$value] = 0; } } else { $policy[$value] = 0; }
		        }

			//      echo "<pre>".print_r($policy, true)."</pre>";

        		$mypolicies = 0;
		        foreach($creatorpolicies as $key => $value) {
        		        if ($policy[$key] == true) { $mypolicies += $value; }
	        	}
		}

		if ($uploadstore[maxstage] <= 9) { $uploadstore[maxstage] = 9; $setmaxstage = 'maxstage=9, '; } else { $setmaxstage = ''; }
                $DB_site->query("UPDATE uploadstore SET ".$setmaxstage."uploadpolicy=".$mypolicies." WHERE id=".$uploadstore['id']);
		$uploadstore['uploadpolicy'] = $mypolicies;

		if (!$issave) {
		$stage++;
		}

	}


	if ($stage == 8) {

                $uppertext = $uploadstore[uppertext];
                $forumID = $uploadstore['forumID'];

		if (isset($_REQUEST['gametype'])) {
			$temptype = 0;
			foreach($_REQUEST['gametype'] as $key => $value) {
				if ($isdebug) { echo $key." => ".$value."<br />"; }
				$temptype += $value;
			}
		} else {
			$temptype = 1;
		}

		/*
		if (isset($_REQUEST['patch'])) {
			$temptype .= ", patch='".mysql_real_escape_string($_REQUEST['patch'])."'";
		} else {
			$temptype .= ", patch='' ";
		}
		*/

		if ($uploadstore[maxstage] <= 8) { $uploadstore[maxstage] = 8; $setmaxstage = 'maxstage=8, '; } else { $setmaxstage = ''; }
		$DB_site->query("UPDATE uploadstore SET ".$setmaxstage."epsbitwise=".$temptype." WHERE id=".$uploadstore['id']);
		$uploadstore[epsbitwise] = $temptype;

		if (!$issave) {
			// Skip stage 9
			$stage = 10;
		}
	}


	if ($stage == 7) {

		$uppertext = $uploadstore[uppertext];
		$forumID = $uploadstore['forumID'];

		if ($_REQUEST['paysitemesh'] == "on") { $paysitemesh = 1; } else { $paysitemesh = 0; }

		$mesh1 = $_REQUEST['mesh1'];
		$mesh2 = $_REQUEST['mesh2'];
		$mesh3 = $_REQUEST['mesh3'];
		$mesh4 = $_REQUEST['mesh4'];
		$mesh5 = $_REQUEST['mesh5'];

		if ($uploadstore[maxstage] <= 7) { $uploadstore[maxstage] = 7; $setmaxstage = ', maxstage=7 '; } else { $setmaxstage = ''; }
		$DB_site->query("UPDATE uploadstore SET 
			mesh1='".mysql_real_escape_string($mesh1)."', 
			mesh2='".mysql_real_escape_string($mesh2)."', 
			mesh3='".mysql_real_escape_string($mesh3)."', 
			mesh4='".mysql_real_escape_string($mesh4)."', 
			mesh5='".mysql_real_escape_string($mesh5)."', 
			paysitemesh=".$paysitemesh."
			".$setmaxstage." 
			WHERE id=".$uploadstore[id]);

		$uploadstore[paysitemesh] = $paysitemesh;
		$uploadstore[mesh1] = $mesh1;		

		// Try and parse the mesh links....

			$meshHasErrors = false;

                        $stuff = array($mesh1, $mesh2, $mesh3, $mesh4, $mesh5);
                        $hasmeshes = 0;
                        foreach ($stuff as $value) {
                        if ($value != "") {
                                if (strpos(strtolower($value), $mydomain) === false) {
                        //                $DB_site->query("INSERT INTO meshes VALUES (0, ".$newpost[threadid].", 0, '".mysql_real_escape_string($value)."')");
                                } else {
                                        $value = str_replace("threadid", "t", $value);
                                        $pos = strstr(strtolower($value), "t=");
                                        //echo $pos."<br />";
                                        if ($pos === false)   {
                                                //$DB_site->query("INSERT INTO meshes VALUES (0, ".$newpost[threadid].", 0, '".mysql_real_escape_string($value)."')");
                                        } else {
						if ($bbuserinfo[userid] == 1) { echo "mesh error: ".$value."<br />"; }
                                                $value = substr($value, strpos(strtolower($value), "t=")+2);
						if ($bbuserinfo[userid] == 1) { echo "mesh error: ".$value."<br />"; }
                                                if (strpos($value, "&") !== false) {
                                                        $value = substr($value, 0, strpos($value, "&") - 1);
                                                }
                                                //$value = str_replace("&c=1", "", $value);

						if (!is_numeric($value)) {
							if ($bbuserinfo[userid] == 1) { echo "mesh error: ".$value."<br />"; }
							$meshHasErrors = true;
						}

                                        }
                                }
                                $hasmeshes = 1;
                        }
			}

		if ($meshHasErrors == false) {
			if (!$issave) {
				if (($uploadstore[forumID] == 406) || ($uploadstore[forumID] == 407)) {
					$stage = 10;
				} else {
					$stage++;
				}
			}
			if ($gameselect == 4) {
				$stage = 10;
			}
		} else {
			$uppertext .= "<br /><span style='color:#ff0000; font-size:2.0em;'>Error! One or more of your mesh links is not valid! Please check and try again.</span><br /><br />";			
		}

	}


	if ($stage == 6) {

                $uppertext = $uploadstore[uppertext];
                $forumID = $uploadstore[forumID];

		if ($_REQUEST['meshtype'] != '') {

			if ($uploadstore[maxstage] <= 6) { $uploadstore[maxstage] = 6; $setmaxstage = 'maxstage=6, '; } else { $setmaxstage = ''; }
			$DB_site->query("UPDATE uploadstore SET ".$setmaxstage."meshtype=".$_REQUEST['meshtype']." WHERE id=".$uploadstore[id]);
			$meshtype = $_REQUEST['meshtype'];
			$uploadstore[meshtype] = $meshtype;

			if (!$issave) {
			if ($meshtype == 3) {
				$stage++;
			} else {
				$stage = 8;
			}
			}
		}

	}	

        /* Stage 5 Next */
	if ($stage == 5) {
		// Iterate through the custom content lists
		$ismissing = false;

                $uppertext = $uploadstore[uppertext];
                $forumID = $uploadstore[forumID];

		//if (isset($_REQUEST['stuffser']) && ($_REQUEST['stuffser'] != '')) { $_REQUEST['stuff'] = unserialize($_REQUEST['stuffser']); }

                $creditslist = '';

		if ($bbuserinfo['userid'] == 1)
		{
			echo "<pre>".print_r($_REQUEST, true)."</pre>";
		}

		if (isset($_REQUEST['stuff'])) {
		foreach($_REQUEST['stuff'] as $key => $value) {

			if ($bbuserinfo['userid'] == 1) { echo print_r($value, true)."<br />"; }

			$value['filename'] = trim($value['filename'],"\x7f..\xff\x0..\x1f");
                        $value['filesize'] = trim($value['filesize'],"\x7f..\xff\x0..\x1f");
                        $value['title'] = trim($value['title'],"\x7f..\xff\x0..\x1f");
                        $value['creator'] = trim($value['creator'],"\x7f..\xff\x0..\x1f");
                        $value['link'] = trim($value['link'],"\x7f..\xff\x0..\x1f");

			if ($bbuserinfo['userid'] == 1) { echo print_r($value, true)."<br />"; }

			if ($bbuserinfo['userid'] == 1701258) { echo "IsMissing: ".$ismissing."<br />"; }

			if (($value['filename'] == '') ||  ($value['title'] == '')) {
				if ($bbuserinfo['userid'] == 1) { echo "Filename, filesize or title are blank<br />"; }
				$ismissing = true;
			} else {
				$value['filename'] = htmlspecialchars_decode($value['filename'], ENT_QUOTES);
				$value['title'] = htmlspecialchars_decode($value['title'], ENT_QUOTES);
				$value['creator'] = htmlspecialchars_decode($value['creator'], ENT_QUOTES);
				$value['link'] = htmlspecialchars_decode($value['link'], ENT_QUOTES);
				$value['description'] = htmlspecialchars_decode($value['description'], ENT_QUOTES);

                                $_REQUEST['stuff'][$key]['filename'] = $value['filename'];
                                $_REQUEST['stuff'][$key]['title'] = $value['title'];
                                $_REQUEST['stuff'][$key]['creator'] = $value['creator'];
                                $_REQUEST['stuff'][$key]['link'] = $value['link'];
				$_REQUEST['stuff'][$key]['description'] = $value['description'];

			}

			 if ($bbuserinfo['userid'] == 1) { echo "IsMissing: ".$ismissing."<br />"; }

                        //if ($bbuserinfo['userid'] == 1701258)
                        //{
                        //        echo print_r($value, true)."<br />";
                        //}
			//if ($bbuserinfo['userid'] == 1701258) { echo "IsMissing: ".$ismissing."<br />"; }

			if ($ismissing == false) {
				if (($value['creator'] == ''))  {
					//if ($bbuserinfo['userid'] == 1701258) {
					//	echo "Creator is blank, checking meauthor...<br />";
					//}
					if ((isset($_REQUEST['stuff'][$key]['meauthor'])) && ($_REQUEST['stuff'][$key]['meauthor'] == "on")) {
						//$creatorstring = "[url=http://www.modthesims2.com/member.php?u=".$bbuserinfo[userid]."]".$value['title']." by ".$bbuserinfo[username]." at ModTheSims2[/url]\r\n";
						//echo $creatorstring."<br />";
						//$creditslist .= $creatorstring;

						//$dbitem = $DB_site->query_first("SELECT * FROM packagedb WHERE filename='".htmlspecialchars($value['filename'], ENT_QUOTES)."' and hidden=0 AND filesize=".str_replace(",", "", $value['filesize']));
						//if ($dbitem == '') {
							//$DB_site->query("INSERT INTO packagedb (id, filename, filesize, creator, linkurl, title, userid, description, hidden)  VALUES (0, '".mysql_real_escape_string($value['filename'])."', ".str_replace(",", "", $value['filesize']).", '".mysql_real_escape_string($bbuserinfo[username])."', 'http://www.modthesims2.com/member.php?u=".$bbuserinfo[userid]."', '".mysql_real_escape_string($value['title'])."', ".$bbuserinfo[userid].", '".mysql_real_escape_string($value['description'])."', 1)");
						//}
					} else {
						$ismissing = true;
						if ($bbuserinfo['userid'] == 1) { echo "Creator is blank...<br />"; }
					}
				} else { 
                                       if ($value['link'] != '') {
                                                //$creatorstring = "[url=".$value['link']."]".$value['title']." by ".$value['creator']."[/url]\r\n";
                                                //echo $creatorstring."<br />";
                                                //$creditslist .= $creatorstring;

                                                //$dbitem = $DB_site->query_first("SELECT * FROM packagedb WHERE filename='".$value['filename']."' and hidden=0 AND filesize=".str_replace(",", "", $value['filesize']));
                                                //if ($dbitem == '') {
                                                //        $DB_site->query("INSERT INTO packagedb (id, filename, filesize, creator, linkurl, title, userid, description, hidden) VALUES (0, '".mysql_real_escape_string($value['filename'])."', ".str_replace(",", "", $value['filesize']).", '".mysql_real_escape_string($value['creator'])."', '".mysql_real_escape_string($value['link'])."', '".mysql_real_escape_string($value['title'])."', 0, '".mysql_real_escape_string($value['description'])."', 1)");
                                                //}

                                        } else {
						if ($bbuserinfo['userid'] == 1) { echo "Link is blank...<br />"; }
                                                $ismissing = true;
                                        }

				}
			}
		}
		}

		//if ($bbuserinfo['userid'] == 1701258) { echo "IsMissing: ".$ismissing."<br />"; }
		if ($ismissing == true) {
			$uppertext .= "<br /><span style='color:#ff0000; font-size:2.0em;'>You have not filled in all the boxes!</span><br /><br />";
		} else {
			$stuffser = serialize($_REQUEST['stuff']);
			//echo $creditslist."<br />";

			if ($uploadstore[maxstage] <= 5) { $uploadstore[maxstage] = 5; $setmaxstage = 'maxstage=5, '; } else { $setmaxstage = ''; }
			$DB_site->query("UPDATE uploadstore SET ".$setmaxstage."stuffser='".mysql_real_escape_string($stuffser)."' WHERE id=".$uploadstore[id]);

			$uploadstore['stuffser'] = $stuffser;

			if (!$issave) {
			if ($forumcache[$forumID]['mrm'] == "1") {
				$stage = 6;
			} else {
				if ($forumcache[$forumID]['npcat'] == 2) { // Sims
					$stage = 7;
				} else {
					/* 
					// Temporary Sims 3 skip
					if ($gameselect == 2) {
						$stage = 10;
					} else {
						$stage = 8;
					}
					*/
					$stage = 8;
				}
			}
			}
			if ($bbuserinfo['userid'] == 1) { echo "Stage is now: ".$stage; }
		}

	}

	/* Stage 4 Next */ 
	if ($stage == 4) {

                $uppertext = $uploadstore[uppertext];
                $forumID = $uploadstore[forumID];

		// Check current attachments for images + zip/rar
		//                     AND userid = $bbuserinfo[userid]
		$currentattaches = $DB_site->query("
			SELECT *
			FROM " . TABLE_PREFIX . "attachment
			WHERE posthash = '" . addslashes($posthash) . "'
		");
		if (mysql_num_rows($currentattaches) > 0) {
			$numfiles = 0;
			$numimages = 0;
			while ($attach = $DB_site->fetch_array($currentattaches))
			{
				//echo "<pre>".print_r($attach, true)."</pre>";
				if ($attach['thumbnail_filesize'] == 0) { $numfiles++; } else { $numimages++; }
			}
			if ($numfiles == 0) {
				$uppertext .= "<br /><span style='color:#ff0000; font-size:2.0em;'>You have not attached any <b>zip</b>, <b>rar</b> or <b>7z</b> files!</span><br /><br />";
			}
			if ($numimages == 0) {
				$uppertext .= "<br /><span style='color:#ff0000; font-size:2.0em;'>You have not attached any <b>image</b> files!</span><br /><br />";
			}

			if (($numimages > 0) && ($numfiles > 0)) {
				// Proceed to stage 5!  (Custom content lists)
				if ($uploadstore[maxstage] <= 4) { 
					$uploadstore[maxstage] = 4;
					$DB_site->query("UPDATE uploadstore SET maxstage=4 WHERE id=".$uploadstore[id]);
				}
				if (!$issave) {
				$stage = 5;
				}
			}

		} else {
			$uppertext .= "<br /><span style='color:#ff0000; font-size:2.0em;'>You have not attached any files!</span><br /><br />";	
		}

	}

	if ($stage == 3) {

		$uppertext = $uploadstore[uppertext];
		$forumID = $uploadstore[forumID];

                if ($uploadstore[maxstage] <= 3) {
			$uploadstore[maxstage] = 3;
			$DB_site->query("UPDATE uploadstore SET maxstage=3 WHERE id=".$uploadstore[id]);
		} 

		if (!$issave) {
		$stage = 4;
		}

	}


        if ($stage == 2) {

		if ($isdebug) { echo "Processing stage 2... "; }

/*
                $stuff = explode(",", $crumbs);
                if (count($stuff) > 1) {
                        $uppertext = '';
                        for($i=0; $i < (count($stuff)); $i++ ) {
                                $uppertext .= $forumcache[$stuff[$i]]['title']." -> ";
                                $forumID= $stuff[$i];
                        }
                } else {
                        $uppertext = "Downloads";
                        $forumID= 38;
                }
*/

		if (isset($_REQUEST['category']) && $category != '') {
			// Onto stage 3
			if (!$issave) {
			$stage = 3;
			$showAnnouncements = true;
			}
			$uppertext = $uploadstore[uppertext];
			$uppertext .= $category;

	                if ($uploadstore[maxstage] <= 2) { $setmaxstage = 'maxstage=2, '; $uploadstore[maxstage] = 2; } else { $setmaxstage = ''; }

			$DB_site->query("UPDATE uploadstore SET ".$setmaxstage."category='".mysql_real_escape_string($category)."', crumbs='".$crumbs."', forumID=".$forumID.", uppertext='".mysql_real_escape_string($uppertext)."' WHERE id=".$uploadstore[id]);
			$uploadstore['category'] = $category;
			$uploadstore['uppertext'] = $uppertext;
		}

        }

	if ($stage == 1) {

		$uploadArea = $_POST['uploadArea'];
		// If an uploadType exists, add that to the crumbs
		if (isset($uploadArea) && ($uploadArea <> "")) {

                        $forumoptions = array(
                                'MaxisRecolour' => 1,
                                'NewMesh' => 2,
                                'MeshRecolour' => 4,
                                'ClosedUploads' => 8,
                        );

                        $isticked = array(
                                'MaxisRecolour' => 0,
                                'NewMesh' => 0,
                                'MeshRecolour' => 0,
                                'ModerateAll' => 0,
                                'ClosedUploads' => 0,
                        );

                        $forumstuff = $DB_site->query_first("SELECT mrmqueue FROM forum WHERE forumid=".$uploadArea);
                        foreach ($forumoptions AS $option => $bitfield) {
                                if ($forumstuff['mrmqueue'] & $bitfield) { $isticked[$option] = 1; }
                        }
                        if ($isticked['ClosedUploads'] == 1) {
				$uppertext .= "<br /><span style='color:#ff0000; font-size:1.5em;'>This area is currently closed for uploading.  Please try back later.</span><br /><br />";	
			} else {

                	if ($crumbs == '') {
        	                $crumbs = "38";
	                        $DB_site->query("INSERT INTO uploadstore (id, posthash, poststarttime, userid, gameselect) VALUES (0, '".$posthash."', ".$poststarttime.", ".$bbuserinfo[userid].", ".$gameselect.")");
                        	$uploadstore[id] = mysql_insert_id();
                	} else {
        	                $crumbs = $uploadstore[crumbs];
	                }


			$parentlist = explode(",", $forumcache[$uploadArea]['parentlist']);
			if ($isdebug) { echo "<pre>".print_r($parentlist, true)."</pre>"; }
			if ($isdebug) { echo "<pre>".print_r($forumcache[$uploadArea], true)."</pre>"; }

			$parentlist = array_reverse($parentlist, true);
			foreach($parentlist as $key => $value) 
			{
				if ($value > -1) {
					if ($isdebug) { echo $key." => ".$value."<br />"; }
					$uppertext .= $forumcache[$value]['title']." -> ";
				}
			}

			$forumID = $uploadArea;

			if ($uploadstore[maxstage] <= 1) { $setmaxstage = 'maxstage=1, '; $uploadstore[maxstage] = 1; } else { $setmaxstage = ''; }
			$query = "UPDATE uploadstore SET ".$setmaxstage."crumbs='".$crumbs."', forumID=".$forumID.", uppertext='".mysql_real_escape_string($uppertext)."' WHERE id=".$uploadstore[id];
			if ($isdebug) { echo $query."<br />"; }
        	        $DB_site->query($query);

			$uploadstore['forumID'] = $forumID;
			$uploadstore['uppertext'] = $uppertext;
 
			// Now check if the forum we are in now has children
			if ($isdebug) { echo "Child list: ".$forumcache[$forumID]['childlist']."<br />"; }
			if ($isdebug) { echo "Crumbs: ".$crumbs."<br />"; }

			if ($issave == false) {
				if ($isdebug) { echo "Checking for next stage...<br />"; }

			        if ($forumcache[$forumID]['childlist'] == $forumID.",-1" || $forumID == 139 || $forumID = 229 ) {
        			        if ($isdebug) { echo "Forum has no children... going to stage 2<br />"; }
					$stage = 2;
	        		}
			}	
			}	

		} else {
			$uppertext .= "<br /><span style='color:#ff0000; font-size:1.5em;'>You have not selected an Upload Area!</span><br /><br />";
		}
	}

	if ($stage == 0) {
		if (!isset($_REQUEST['gameselect'])) {
			$uppertext .= "<br /><span style='color:#ff0000; font-size:1.5em;'>You have not selected a Game type!</span><br /><br />";
		} else {
			$stage = 1;
			$gameselect = $_REQUEST['gameselect'];
		}
	}

}

if ($isdebug) { echo "Stage is: ".$stage."<br />"; }
if ($isdebug) { echo "Crumbs: ".$crumbs."<br />"; }
if ($isdebug) { echo "Upload forum: ".$forumID."<br />"; }

$stagetitles = array(
	0 => array("enabled" => false, "title" => "Select Game"),
	1 => array("enabled" => false, "title" => "Select Area"),
	2 => array("enabled" => false, "title" => "Choose Category"),
	3 => array("enabled" => false, "title" => "Announcements"),
	4 => array("enabled" => false, "title" => "Upload Files"),
	5 => array("enabled" => false, "title" => "Custom Content"),
	6 => array("enabled" => false, "title" => "Upload Type"),
	7 => array("enabled" => false, "title" => "Meshes Used"),
	8 => array("enabled" => false, "title" => "Compatibility"),
	9 => array("enabled" => false, "title" => "Policy Exception"),
	10 => array("enabled" => false, "title" => "Main Text"),
	11 => array("enabled" => false, "title" => "Keywords/Thumbnail"),
	12 => array("enabled" => false, "title" => "Preview"),
	13 => array("enabled" => false, "title" => "Submit"),
);

if ($isdebug) {
	echo "<pre>".print_r($uploadstore, true)."</pre>";
}

if ($bbuserinfo['userid'] == 1) {
	echo "Stage: ".$stage."<br />";
	echo "Posthash: ".$posthash."<br />";
	echo "<pre>".print_r($uploadstore, true)."</pre>";
}

switch ($stage)
{
	case "":
	case 0:

                $template = "upload_gameselect";

		$numInQueueRes = $DB_site->query_first("SELECT COUNT(*) AS numInQueue FROM thread WHERE visible=0 AND epsbitwise > 0 AND threadtype <> 'rejected' AND postuserid = ".$bbuserinfo['userid']);
		$numInQueue = intval($numInQueueRes['numInQueue']);

                $queueBypassArray = calcQueueBypass($bbuserinfo['userid'], $bbuserinfo['username'], $gameselect);
                $canBypass = $queueBypassArray['fastpass'];

		if (!$canBypass) {
			if ($bbuserinfo['approveduploads'] <= intval($vboptions['queueLimitMaxUploadsTrigger1'])) {
				$maxInQueue = intval($vboptions['maxInQueueValue1']);
			} else {
				$maxInQueue = intval($vboptions['maxInQueueValue2']);
			}
			if ($numInQueue >= $maxInQueue) {
				$template = "upload_toomany";
			}
		}

                $_REQUEST['uploadType'] = $forumID;
                $crumbs = 38;
                $stage = 0;

                if ($bbuserinfo[styleid] == 0) {
                        $styleinfo = $DB_site->query_first("SELECT csscolors FROM style WHERE styleid=".$vboptions[styleid]);
                } else {
                        $styleinfo = $DB_site->query_first("SELECT csscolors FROM style WHERE styleid=".$bbuserinfo[styleid]);
                }
                $styleinfo = unserialize($styleinfo[csscolors]);
                if ($isdebug) { echo "<pre>".print_r($styleinfo, true)."</pre>"; }

                break;
	case "1":
                $_REQUEST['uploadType'] = $forumID;
                $template = "upload_selectionbox";
                $crumbs = 38;
                $stage = 1;
                //$navbits[""] = "Select Area for Upload";

		if ($bbuserinfo[styleid] == 0) {
			$styleinfo = $DB_site->query_first("SELECT csscolors FROM style WHERE styleid=".$vboptions[styleid]);
		} else {
			$styleinfo = $DB_site->query_first("SELECT csscolors FROM style WHERE styleid=".$bbuserinfo[styleid]);
		}
		$styleinfo = unserialize($styleinfo[csscolors]);
		if ($isdebug) { echo "<pre>".print_r($styleinfo, true)."</pre>"; }

		cache_forums(-1, 0, 1);
	
                $listsize = build_text_array(38);

                break;
/*
	case "1":
                $listsize = build_text_array($forumID);
                $listsize++;
                $_REQUEST['uploadType'] = $forumID;
                $template = "upload_selectionbox";
                //$navbits[""] = "Select Area for Upload";
                break;
*/
	case "2":

		if ($uppertext == '') {
			$uppertext = $uploadstore[uppertext];
		}

		// Last sub-section - should be categories if they exist
                $template = "upload_stage2";
		$stagetitles[1]['enabled'] = true;
                //$navbits[""] = "Select Category for Upload";

		$foruminfo = $forumcache[$forumID];
                if ($foruminfo['category'])
                {
                        $threadcategories = explode("\r\n", unhtmlspecialchars($foruminfo['category']));
		        if (!empty($threadcategories))
		        {
		                foreach ($threadcategories AS $category)
                		{
		                        $category = htmlspecialchars(trim($category));

                                                if ($gameselect == 4) {
                                                        switch ($category) {
                                                        case "Teen":
                                                        case "Young Adult":
                                                        case "Elder":
                                                                $category = "";
                                                                break;
                                                        default:
                                                                break;
                                                        }

                                                }

					if ($category != '') {

						if ($isdebug) { echo "--".$category."==<br />"; }
						if ($category == $uploadstore[category]) { $selected = "selected"; } else { $selected = ''; }

		                                $threadcategories .= "\t\t<option value=\"$category\" $selected>$category</option>\n";
						$listsize++;	
					}
        	                }
				$listsize++;
                	}
                }

		if ($threadcategories == '') {
			// Skip to step 3 and update blank category 
			if ($uploadstore['category'] != "") {
				$DB_site->query("UPDATE uploadstore SET category='' WHERE id=".$uploadstore[id]);
			}
			$stage = 3;
	                $template = "upload_stage3";
        	        $navbits[""] = "Announcements";
                	$showAnnouncements = true;
		}

		break;

	case "3":

		$stagetitles[1]['enabled'] = true;
		if ($uploadstore['category'] != "") { $stagetitles[2]['enabled'] = true; }
                $template = "upload_stage3";
                //$navbits[""] = "Announcements";
		$showAnnouncements = true;		
		break;

	case "4":

                $stagetitles[1]['enabled'] = true;
                if ($uploadstore['category'] != "") { $stagetitles[2]['enabled'] = true; }
                $stagetitles[3]['enabled'] = true;

                $template = "upload_stage4";
                //$navbits[""] = "Upload Files";

	        // get attachment options

		$forumperms = fetch_permissions($forumID);
	        //require_once('./includes/functions_file.php');
	        //$inimaxattach = fetch_max_attachment_size();

	        //$maxattachsize = vb_number_format($inimaxattach, 1, true);

	        if ($forumperms & CANPOSTATTACHMENT AND $bbuserinfo['userid'])
	        {
			/*
                	if (!$posthash OR !$poststarttime)
        	        {
                        	$poststarttime = TIMENOW;
	                        $posthash = md5($poststarttime . $bbuserinfo['userid'] . $bbuserinfo['salt']);
        	        }
                	else
	                {
        	                $currentattaches = $DB_site->query("
                	                SELECT filename, filesize
                        	        FROM " . TABLE_PREFIX . "attachment
                                		WHERE posthash = '" . addslashes($newpost['posthash']) . "'
	                                        AND userid = $bbuserinfo[userid]
        	                ");

                	        while ($attach = $DB_site->fetch_array($currentattaches))
                        	{
	                                $attach['extension'] = strtolower(file_extension($attach['filename']));
        	                        $attach['filename'] = htmlspecialchars_uni($attach['filename']);
                	                $attach['filesize'] = vb_number_format($attach['filesize'], 1, true);
                       		        $show['attachmentlist'] = true;
	                                eval('$attachments .= "' . fetch_template('newpost_attachmentbit') . '";');
        	                }
	                }
			*/
        	        $attachurl = "f=429";
                	//eval('$attachmentoption = "' . fetch_template('newpost_attachment') . '";');
			$attachmentoption = "Yes";
	        }
        	else
	        {
        	        $attachmentoption = '';
	        }

		$poststarttime = $uploadstore[poststarttime];

		$query = "SELECT postid, title, pagetext from post where threadid=219775 and (title like '".$forumcache[$forumID]['npcat']." - %' or ";
		$query .= "title like '1 - %') order by title";

		if ($isdebug) { echo $query; }
		$result = $DB_site->query($query);

		while ($row = $DB_site->fetch_array($result)) {
			$guides .= parse_bbcode($row[pagetext], 429, 1);
		}

                break;

	/* Stage 5 Main */
	case "5":

                if ($isdebug) {  echo "Processing stage 5...<br />"; }

                $stagetitles[1]['enabled'] = true;
                if ($uploadstore['category'] != "") { $stagetitles[2]['enabled'] = true; }
                $stagetitles[3]['enabled'] = true;
                $stagetitles[4]['enabled'] = true;

                // Custom Content Lists
                $template = "upload_stage5";
                //$navbits[""] = "Custom Content Included";

		$cctype = 0;
		if (!isset($_REQUEST['stuff'])) {
			if ($uploadstore[stuffser] != '' && $uploadstore['stuffser'] !== 'N;') {

				if ($_REQUEST['nextb'] == "Next ->") {
           			$contentlist = getContentList($posthash);
				} else {
					$contentlist = unserialize($uploadstore[stuffser]);
				}

				$cctype = 1;
			} else {
				$contentlist = getContentList($posthash);
				$cctype = 2;
			}
		} else {
			$contentlist = $_REQUEST['stuff'];
			$cctype = 3;
		}

                $bgcolor = "#ffffff";
                $linknum = 0;

		if ($bbuserinfo[userid] == 1) {
			echo "<pre>".print_r($cctype, true)."</pre>";
		}

		$alreadydone = array();
		if (count($contentlist) > 0) {
                foreach ($contentlist as $item) {

                        $item['filename'] = trim($item['filename'],"\x7f..\xff\x0..\x1f");
                        $item['filesize'] = trim($item['filesize'],"\x7f..\xff\x0..\x1f");
                        $item['title'] = trim($item['title'],"\x7f..\xff\x0..\x1f");
                        $item['creator'] = trim($item['creator'],"\x7f..\xff\x0..\x1f");
                        $item['link'] = trim($item['link'],"\x7f..\xff\x0..\x1f");
			$item['description'] = trim($item['description'],"\x7f..\xff\x0..\x1f");

			if (!isset($alreadydone[$item['filename'].$item['filesize']])) { $alreadydone[$item['filename'].$item['filesize']] = 1; } else { continue; }

			if ($item['title'] == "&amp;nbsp;") { $item['title'] = ''; }

			//echo "--".$item['title']."==<br />";

	                if ($isdebug) { echo $linknum." - ".print_r($item, true)."<br />"; }

                        if (is_int($linknum / 8)) { $formstuff .= "<tr><th></th><th style='font-size:1.3em; font-weight:bold;'>Package Description</th><th style='font-size:1.3em; font-weight:bold;'>Creator / Site</th><th style='font-size:1.3em; font-weight:bold;'>Link URL</th></tr>"; }
                        if ($bgcolor == "#cceeee") { $bgcolor = "#ffffff"; } else { $bgcolor = "#cceeee"; }

                        $formstuff .= "<tr style='background-color:".$bgcolor."'>\n";
                        $formstuff .= "<td valign='top' class='smallfont' rowspan='2'>\n";
                        $formstuff .= "<span style='font-size:2.0em; font-style:bold;'>".($linknum + 1)."</span>\n";
			$formstuff .= "</td>\n";
			$formstuff .= "<td valign='top' class='smallfont'>\n";

                        $formstuff .= "<input type='hidden' name='stuff[$linknum][filename]' value='".$item['filename']."'>\n";
                        $formstuff .= "<input type='hidden' name='stuff[$linknum][filesize]' value='".$item['filesize']."'>\n";
                        $formstuff .= "<input type='hidden' name='stuff[$linknum][description]' value='".htmlspecialchars($item['description'], ENT_QUOTES)."'>\n";
			$formstuff .= "<input type='hidden' name='stuff[$linknum][type]' value='".$item['type']."'>\n";

                        $formstuff .= "<input class='bginput' type='text' size='35' name='stuff[$linknum][title]' value='".htmlspecialchars($item['title'], ENT_QUOTES)."' /><br />\n";

                        $formstuff .= "</td>\n";
                        $formstuff .= "<td valign='top' class='smallfont'><input class='bginput' type='text' size='40' name='stuff[$linknum][creator]' value='".htmlspecialchars($item['creator'])."'\n";
                        if ($item['meauthor'] == "on") { $formstuff .= " disabled"; }
                        $formstuff .= "/><br /><input type='checkbox' name='stuff[$linknum][meauthor]' \n";
                        if ($item['meauthor'] == "on") { $formstuff .= "checked"; }
                        $formstuff .= " onClick='javascript:disableField(".$linknum.")'>I am the creator of this package. (Disables the box above and to the right)</input></td>\n";
                        $formstuff .= "<td valign='top' class='smallfont'><input class='bginput' type='text' size='40' name='stuff[$linknum][link]'  value='".$item['link']."'\n";
                        if ($item['meauthor'] == "on") { $formstuff .= " disabled"; }
                        $formstuff .= " /></td>\n";
                        $formstuff .= "</tr>\n";
			$formstuff .= "<tr style='background-color:".$bgcolor."'>\n";
			$formstuff .= "<td valign='top' class='smallfont' colspan='3'>\n";
			$formstuff .= "Description from ".$item[filename];
			if ($item['type'] <> '') { $formstuff .= ", of type ".$item['type']; }
			$formstuff .= ":\n<br /><b>".htmlspecialchars_decode($item['description'], ENT_QUOTES)."</b>";
			$formstuff .= "</td></tr>\n";

                        $linknum++;
                }
		}

		break;
	case "6":

		$uppertext = $uploadstore[uppertext];

                $stagetitles[1]['enabled'] = true;
                if ($uploadstore['category'] != "") { $stagetitles[2]['enabled'] = true; }
                $stagetitles[3]['enabled'] = true;
		$stagetitles[4]['enabled'] = true;
                $stagetitles[5]['enabled'] = true;

		$textArray = "myText['1'] = 'This upload includes clothing changes done purely in BodyShop, Makeup, or existing Maxis objects recoloured using the CEP - basically anything that already exists in the game.';\n
myText['2'] = 'This upload contains a brand new mesh that adds new items for your Sims to play with.  If you make new Hair, brand new Objects or otherwise use a 3d editor to create your item, check this.';\n
myText['3'] = 'This upload is a recolour of an existing mesh by somebody else, for example if you find a great mesh on MTS2 and have done a pretty recolour for it.';\n";

		$meshtype = $uploadstore[meshtype];
	
		$template = "upload_stage6";
		//$navbits[""] = "Type of Upload";

		break;
	case "7":


                $stagetitles[1]['enabled'] = true;
                if ($uploadstore['category'] != "") { $stagetitles[2]['enabled'] = true; }
                $stagetitles[3]['enabled'] = true;
                $stagetitles[4]['enabled'] = true;
                $stagetitles[5]['enabled'] = true;
		if ($forumcache[$forumID]['mrm'] == "1") {
			$stagetitles[6]['enabled'] = true;
		}

		$mesh1 = $uploadstore[mesh1];
		$mesh2 = $uploadstore[mesh2];
		$mesh3 = $uploadstore[mesh3];
		$mesh4 = $uploadstore[mesh4];
		$mesh5 = $uploadstore[mesh5];

		$template = "upload_stage7";
		//$navbits[""] = "Mesh Links";
		break;
	case "8":

                $stagetitles[1]['enabled'] = true;
                if ($uploadstore['category'] != "") { $stagetitles[2]['enabled'] = true; }
                $stagetitles[3]['enabled'] = true;
                $stagetitles[4]['enabled'] = true;
                $stagetitles[5]['enabled'] = true;
                if ($forumcache[$forumID]['mrm'] == "1") {
                        $stagetitles[6]['enabled'] = true;
                }
		if (($forumcache[$forumID]['npcat'] == 2) || (($forumcache[$forumID]['mrm'] == "1") && ($uploadstore['meshtype'] == 3))) {
			$stagetitles[7]['enabled'] = true;
		}

		$showPatch = 0;
		if ($forumcache[$forumID]['npcat'] == 11 || $forumcache[$forumID]['npcat'] == 28) {
			$showPatch = 1;
		}

                        // Special Compatibility for particular forums
                        switch ($uploadstore[forumID]) {
                                case 432: // Automotive
                                        $gametype['gameEP2'] = true; break;
                                case 486: // Cats
                                case 487: // Dogs
                                        $gametype['gameEP4'] = true; break;
                        }


		if ($uploadstore[epsbitwise] != "0") {

		        if (isset($expansionpacks)) {

		                foreach($expansionpacks AS $option => $bitfield) {
                		        //define(strtoupper($option), $bitfield);
		                        if ($uploadstore['epsbitwise'] & $bitfield) {
                		                $gametype[$option] = true;
		                        } else {
						$gametype[$option] = false;
					}
                		}
                		unset($option, $bitfield);
		        }
		}

		if ($isdebug) { echo "Gametype: $uploadstore[epsbitwise] <pre>".print_r($gametype, true)."</pre>"; }


        	eval('$epsrequired = "' . fetch_template('upload_eps_required') . '";');
	        eval('$spsrequired = "' . fetch_template('upload_sps_required') . '";');


		$template = "upload_stage8";
		//$navbits[""] = "Compatibility";
		break;

	case "9":

                $stagetitles[1]['enabled'] = true;
                if ($uploadstore['category'] != "") { $stagetitles[2]['enabled'] = true; }
                $stagetitles[3]['enabled'] = true;
                $stagetitles[4]['enabled'] = true;
                $stagetitles[5]['enabled'] = true;
                if ($forumcache[$forumID]['mrm'] == "1") {
                        $stagetitles[6]['enabled'] = true;
                }
                if (($forumcache[$forumID]['npcat'] == 2) || (($forumcache[$forumID]['mrm'] == "1") && ($uploadstore['meshtype'] == 3))) {
                        $stagetitles[7]['enabled'] = true;
                }
		// Temporary Sims 3
		if ($gameselect == 1) {
			$stagetitles[8]['enabled'] = true;
		}

		if ($uploadstore[uploadpolicy] == 0) {
			$policyselected = "checked";

			if (isset($creatorpolicies)) {
			       foreach($creatorpolicies AS $option => $bitfield) {
				                if ($bbuserinfo['policies'] & $bitfield) {
			                        $policy[$option] = 1;
			                } else {
			                        $policy[$option] = 0;
			                }
			       }
			       unset($option, $bitfield);
			}

		} else {
			$policyselected2 = "checked";

                        if (isset($creatorpolicies)) {
                               foreach($creatorpolicies AS $option => $bitfield) {
                                                if ($uploadstore['uploadpolicy'] & $bitfield) {
                                                $policy[$option] = 1;
                                        } else {
                                                $policy[$option] = 0;
                                        }
                               }
                               unset($option, $bitfield);
                        }
		}

		$template = "upload_stage9";
		break;

	case "10":

                $stagetitles[1]['enabled'] = true;
                if ($uploadstore['category'] != "") { $stagetitles[2]['enabled'] = true; }
                $stagetitles[3]['enabled'] = true;
                $stagetitles[4]['enabled'] = true;
                $stagetitles[5]['enabled'] = true;
                if ($forumcache[$forumID]['mrm'] == "1") {
                        $stagetitles[6]['enabled'] = true;
                }
                if (($forumcache[$forumID]['npcat'] == 2) || (($forumcache[$forumID]['mrm'] == "1") && ($uploadstore['meshtype'] == 3))) {
                        $stagetitles[7]['enabled'] = true;
                }
                // Temporary Sims 3
                if ($gameselect == 1) {
                        $stagetitles[8]['enabled'] = true;
                }
//                $stagetitles[8]['enabled'] = true;
		$stagetitles[9]['enabled'] = true;

		require_once('./includes/functions_newpost.php');
		require_once('./includes/functions_editor.php');
		require_once('./includes/functions_bigthree.php');

                $addcredits = htmlspecialchars($uploadstore['addcredits'], ENT_QUOTES);
		$polycounttext = htmlspecialchars($uploadstore['polycounts'], ENT_QUOTES);
                if (!isset($dimx)) {
                                $llsize = explode("x", $uploadstore[lotsize]);
                                $dimx[$llsize[0]] = "selected";
                }

        	if ($uploadstore[custominstalltext] != '') {

	                $custominstalltext = $uploadstore[custominstalltext];

        	        switch ($uploadstore[custominstalltext])
	                {
                        	case "Install Instructions - Scriptorium:":
                	        case "Install Instructions - Panties:":
        	                case "Install Instructions - Custom:":
	                                $uploadstore[custominstalltexttext] = "";
                                	break;
                        	default:
                	                $uploadstore[custominstalltexttext] = $uploadstore[custominstalltext];
        	        }

	        }


                if (!isset($dimy)) {
                        if ($uploadstore[lotsize] != '') {
                                $llsize = explode("x", $uploadstore[lotsize]);
                                $dimy[$llsize[1]] = "selected";
                        }
                }

		$subject = htmlspecialchars($uploadstore[subject], ENT_QUOTES, "ISO-8859-1");
			if (isset($_GET['debug'])) { echo $uploadstore['message']."<br />"; }
		$newpost['message'] = htmlspecialchars($uploadstore['message'], ENT_QUOTES, "ISO-8859-1" );
			if (isset($_GET['debug'])) { var_dump($newpost['message'])."<br />"; }

		//$blah = unserialize($uploadstore[stuffser]);
		$blah = getContentList($posthash);
		foreach ($blah as $value) {
			if ($value['type'] == "Mesh") {
				$polyinfo .= $value['filename'].": ".$value['title']."<br />";
			}
		}

        // Does this forum have search parameters?
        $fsearchparms = array();
        if ($forumcache[$forumID]['searchparms'] != '') {
                $fsearchparms = unserialize($forumcache[$forumID]['searchparms']);
        } else {
                // Check forums parent
                if ($forumcache[$forumcache[$forumID]['parentid']]['searchparms'] != '') {
                        $fsearchparms = unserialize($forumcache[$forumcache[$forumID]['parentid']]['searchparms']);
                }
        }

        if (count($fsearchparms) > 0) {

                // Get thread search paramters
  //              $searchquery = $DB_site->query_first("SELECT * FROM threadsearch WHERE threadid=".$threadinfo['threadid']);
		$searchquery = $uploadstore['searchparms'];
                if ($searchquery == '') {
                        // No search parameters found
                } else {
			$searchquery = unserialize($searchquery);
		}

                if ($isdebug) {
                echo "Fsearchparms: <pre>".print_r($fsearchparms, true)."</pre>";
                echo "Search Query: <pre>".print_r($searchquery, true)."</pre>";
                }

                $searchp = array();

                for($i = 1; $i <= 10; $i++) {

                if ($fsearchparms['t'.$i] != '') {

                $searchparms .= "<b>".$fsearchparms['t'.$i].":</b><br />\n";

                $searchp['p'.$i] = explode("\n", $fsearchparms['p'.$i]);
                $tempactual = array();
                $parmno = 0;
                foreach ($searchp['p'.$i] as $key => $value) {
                        $parmno++;
                        $blah = explode(" - ", $value);
//                        if (trim($blah[0]) != "Doesn't matter") {
                                $searchparms .= "<input type='";
//                              echo "--".$fsearchparms['y'.$i]."++<br />";
                                if ($fsearchparms['y'.$i] == "1") { $searchparms .= "checkbox"; } else { $searchparms .= "radio"; }
                                $searchparms .= "' name='searchp[p".$i."]";
                                if ($fsearchparms['y'.$i] == "1") {
                                        $searchparms .= "[".$parmno."]";
                                }
                                $searchparms .= "' value=\"".trim($blah[0])."\" ";
                          //    echo $i."-+".trim($blah[0])."==".$searchquery['p'.$i]."+-<br />";

				if (!is_array($searchquery['p'.$i])) {
                                        if (trim($blah[0]) == $searchquery['p'.$i]) {
//						if ($fsearchparms['y'.$i] == "1") { 
							$searchparms .= "checked "; 
//						} else { 
//							$searchparms .= "selected ";
//						}
					}
                                } else {
			//		echo print_r($searchquery['p'.$i], true)."<br />";
//					if (count($searchquery['p'.$i]) == 1) {
						foreach ($searchquery['p'.$i] as $dd) {
			//				echo "++".trim($blah[0])."--".$dd."++<br />";
							if (trim($blah[0]) == trim($dd)) { $searchparms .= "checked ";  }
						}
//					} else {
/*
	                                $xkcd = explode(", ", $searchquery['p'.$i]);
        	                       echo count($xkcd).": ".print_r($xkcd, true)." -- ".print_r($xkcd[0])."<br />";

                                        foreach ($xkcd as $qc) {
						echo print_r($qc, true)."<br />";
                                                if (trim($blah[0]) == $qc[0]) { 
							if ($fsearchparms['y'.$i] == "1") {
								$searchparms .= "checked "; 
							} else {
								$searchparms .= "selected ";
							}
						}
                                        }
                                        }
*/
                                }

                                $newvalue = trim(str_replace($blah[0]." - ", "", $value));
                                $searchparms .= ">\n".trim($blah[0]);
                                if (($newvalue != '') && ($newvalue != trim($blah[0])))  {
//                                      echo "-+".trim($blah[0])."==".$newvalue."+-<br />";
                                        $searchparms .= "<br /><small style='margin-left:20px;'>".$newvalue."</small>\n";
                                }
                                $searchparms .= "</input><br />\n";
//                        }
                }

                $searchparms .= "<br />";


                }
                }

        }

		// Check if Browser is Chrome, and if so, turn off the 'enhanced' editor
		//if ((strpos($_SERVER['HTTP_USER_AGENT'], 'AppleWebKit') !== false) && (strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome') !== false)) {
		//	$bbuserinfo['showvbcode'] = 0;
		//}


		if ($bbuserinfo['userid'] == 1) { 
			var_dump($forumcache[$forumID]); 
		}
	

	        construct_edit_toolbar($newpost['message'], 0, $forumID, 1);

        	$posticons = construct_icons(intval($newpost['iconid']), $forumcache[$forumID]['allowicons']);

                $attachquery = "SELECT userid, symlink, symlink_thumb, filename, filesize, visible, attachmentid, counter, postid, IF(thumbnail_filesize > 0, 1, 0) AS hasthumbnail, thumbnail_filesize
                        FROM " . TABLE_PREFIX . "attachment
                        WHERE posthash='".$uploadstore[posthash]."' AND thumbnail_filesize > 0
                        ORDER BY postid
                        ";

                $attachments = $DB_site->query($attachquery);
                $postattach = array();

                while ($attach = $DB_site->fetch_array($attachments))
                {

			if ($isdebug) { echo $attach[attachmentid]."<br />"; }
                                $attachcount++;
                                $attach['extension'] = strtolower(file_extension($attach['filename']));
                                $attach['filename'] = htmlspecialchars_uni($attach['filename']);
                                $attach['filesize'] = vb_number_format($attach['filesize'], 1, true);
                                $show['attachmentlist'] = true;
                                $attachment = $attach;
                                if ($attach['thumbnail_filesize'] > 0) {
                                        if ($attach[attachmentid] == $threadinfo[defaultpic]) { $achecked = "checked"; } else { $achecked = ""; }
                                        eval('$attachpreview .= "' . fetch_template('postbit_attachmentthumbnail3') . '<br />";');
                                }

                }

		$template = "upload_stage10";
		break;

	case "11":

                $stagetitles[1]['enabled'] = true;
                if ($uploadstore['category'] != "") { $stagetitles[2]['enabled'] = true; }
                $stagetitles[3]['enabled'] = true;
                $stagetitles[4]['enabled'] = true;
                $stagetitles[5]['enabled'] = true;
                if ($forumcache[$forumID]['mrm'] == "1") {
                        $stagetitles[6]['enabled'] = true;
                }
                if (($forumcache[$forumID]['npcat'] == 2) || (($forumcache[$forumID]['mrm'] == "1") && ($uploadstore['meshtype'] == 3))) {
                        $stagetitles[7]['enabled'] = true;
                }
                $stagetitles[8]['enabled'] = true;
                $stagetitles[9]['enabled'] = true;
		$stagetitles[10]['enabled'] = true;
/*
		if (!isset($dimx)) {
                                $llsize = explode("x", $uploadstore[lotsize]);
                                $dimx[$llsize[0]] = "selected";
		}

		if (!isset($dimy)) {
			if ($uploadstore[lotsize] != '') {
				$llsize = explode("x", $uploadstore[lotsize]);
				$dimy[$llsize[1]] = "selected";
			}
		}
*/
                $attachquery = "SELECT qxpress, userid, symlink, symlink_thumb, filename, filesize, visible, attachmentid, counter, postid, IF(thumbnail_filesize > 0, 1, 0) AS hasthumbnail, thumbnail_filesize
                        FROM " . TABLE_PREFIX . "attachment
                        WHERE posthash='".$uploadstore[posthash]."' AND thumbnail_filesize > 0
                        ORDER BY postid, attachmentid
                        ";

                $attachments = $DB_site->query($attachquery);
                $postattach = array();

		

                while ($attach = $DB_site->fetch_array($attachments))
                {
                                $attachcount++;
                                $attach['extension'] = strtolower(file_extension($attach['filename']));
                                $attach['filename'] = htmlspecialchars_uni($attach['filename']);
                                $attach['filesize'] = vb_number_format($attach['filesize'], 1, true);
                                $show['attachmentlist'] = true;
                                $attachment = $attach;
                                        if ($attach[attachmentid] == $uploadstore[defaultpic]) { $achecked = "checked"; } else { $achecked = ""; }
					if (($uploadstore[defaultpic] == 0) && ($attachcount == 1)) { $achecked = "checked"; }
                                        eval('$attachpreview .= "<input type=\"radio\" name=\"defaultpic\" ".$achecked." value=\"".$attach[attachmentid]."\">' . fetch_template('postbit_attachmentthumbnail2') . '<br />";');
                }


		$template = "upload_stage11";
		break;

	case "12":
		// Preview!

                $stagetitles[1]['enabled'] = true;
                if ($uploadstore['category'] != "") { $stagetitles[2]['enabled'] = true; }
                $stagetitles[3]['enabled'] = true;
                $stagetitles[4]['enabled'] = true;
                $stagetitles[5]['enabled'] = true;
                if ($forumcache[$forumID]['mrm'] == "1") {
                        $stagetitles[6]['enabled'] = true;
                }
                if (($forumcache[$forumID]['npcat'] == 2) || (($forumcache[$forumID]['mrm'] == "1") && ($uploadstore['meshtype'] == 3))) {
                        $stagetitles[7]['enabled'] = true;
                }
                $stagetitles[8]['enabled'] = true;
                $stagetitles[9]['enabled'] = true;
                $stagetitles[10]['enabled'] = true;
                $stagetitles[11]['enabled'] = true;

		$thread[title] = $uploadstore[subject];
		$firstpost[postdate] = "Today";
		$firstpost[posttime] = date("g:ia", time());
		$thread[views] = 0;

		$firstpost[username] = $bbuserinfo[username];
		$threadinfo[keywords] = $uploadstore[keywords];


                        if ($threadinfo[keywords]) {


                                $tag = explode(",", $thread[keywords]);

                                if (count($tag) == 1) {
                                        // Check if less than 3 words
                                        $temptags = explode(" ", $tag[0]);
                                        if (count($temptags) > 2) {
                                                $tag = $temptags;
                                        }
                                }

				if (count($tag) > 0) {

                                foreach ($tag as $value) {
                                        $i++;

                                        $ttag = trim($value);
                                        if ($ttag <> '') {
                                                $newkwords[] = "<a href='/browse.php?tag=".htmlentities($ttag)."'>".$ttag."</a>";
                                        }
                                }
				if (count($newkwords) > 0) {
                                	$thread[keywords] = implode(", ", $newkwords);
				}


				}

/*
                                $kwords = explode(",", $threadinfo[keywords]);
                                $newkwords = array();
                                foreach ($kwords as $value) {
                                        $value = trim($value);
                                        $newkwords[] = "<a href='/browse.php?tag=".htmlentities($value)."'>".$value."</a>";
                                }
                                $threadinfo[keywords] = implode(", ", $newkwords);

                                unset($newkwords);
                                unset($kwords);
*/

                        }


                $attachquery = "SELECT zipinfo, qxpress, userid, symlink, symlink_thumb, filename, filesize, visible, attachmentid, counter, postid, IF(thumbnail_filesize > 0, 1, 0) AS hasthumbnail, thumbnail_filesize
                        FROM " . TABLE_PREFIX . "attachment
                        WHERE posthash='".$uploadstore[posthash]."'
                        ORDER BY postid, attachmentid
                        ";

                $attachments = $DB_site->query($attachquery);
                $postattach = array();
                while ($attachment = $DB_site->fetch_array($attachments))
                {
			$attachment[counter] = 0;
                        $postattach["$attachment[attachmentid]"] = $attachment;
                        $firstpost['numattachments']++;
                }


                if (is_array($postattach))
                {
                        if (can_moderate($foruminfo['forumid'], 'canmoderateattachments') OR $firstpost['userid'] == $bbuserinfo['userid'])
                        {
                                $show['modattachmentlink'] = true;
                        }
                        else
                        {
                                $show['modattachmentlink'] = false;
                        }
                        $firstpostshow['attachments'] = true;
                        $firstpostshow['moderatedattachment'] = $firstpostshow['thumbnailattachment'] = $firstpostshow['otherattachment'] = false;
                        $firstpostshow['imageattachment'] = $firstpostshow['imageattachmentlink'] = false;
                        $attachcount = sizeof($firstpost['attachments']);
                        $thumbcount = 0;
                        if (!$vboptions['attachthumbs'] AND !$vboptions['viewattachedimages'])
                        {
                                $showimagesprev = $bbuserinfo['showimages'];
                                $bbuserinfo['showimages'] = false;
                        }

                                        $attachedimages = 0;
                                        $attachedfiles = 0;
                                        $qxpressfiles = 0;
                        $firstpostshow['qxpressall'] = 1;

                        foreach($postattach AS $attachmentid => $attachment)
                        {

                                if($attachment['thumbnail_filesize'] == $attachment['filesize'])
                                { // This is an image that is already thumbnail sized..
                                        $attachment['hasthumbnail'] = 0;
                                        $attachment['forceimage'] = 1;
                                }

                                $attachment['filename'] = fetch_censored_text(htmlspecialchars_uni($attachment['filename']));
                                $attachment['attachmentextension'] = strtolower(file_extension($attachment['filename']));
                                $attachment['filesize'] = vb_number_format($attachment['filesize'], 1, true);
                                $attachment['counter'] = number_format($attachment['counter']);

                                if ($attachment['visible'])
                                {
                                        switch($attachment['attachmentextension'])
                                        {
                                                case 'gif':
                                                case 'jpg':
                                                case 'jpeg':
                                                case 'jpe':
                                                case 'png':
                                                case 'bmp':
                                                        if ($isdebug) { echo "Is image file...<br />"; }
                                                        $attachedimages++;
                                                        if (!$bbuserinfo['showimages'])
                                                        {
                                                                eval('$firstpost[\'imageattachmentlinks\'] .= "' . fetch_template('postbit_attachment2') . '";');
                                                                $firstpostshow['imageattachmentlink'] = true;
                                                        }
                                                        else if ($vboptions['attachthumbs'])
                                                        {
                                                                if ($attachment['hasthumbnail'])
                                                                {
                                                                        $thumbcount++;
                                                                        if ($thumbcount >= $vboptions['attachrow'])
                                                                        {
                                                                                $thumbcount = 0;
                                                                                $show['br'] = true;
                                                                        }
                                                                        else
                                                                        {
                                                                                $show['br'] = false;
                                                                        }
                                                                        eval('$firstpost[\'thumbnailattachments\'] .= "' . fetch_template('postbit_attachmentthumbnail2') . '";');
                                                                        $firstpostshow['thumbnailattachment'] = true;
									$attachedimages++;
                                                                }
                                                                else if ($attachment['forceimage'])
                                                                {
                                                                        eval('$firstpost[\'imageattachments\'] .= "' . fetch_template('postbit_attachmentimage2') . '";');
                                                                        $firstpostshow['imageattachment'] = true;
                                                                }
                                                                else
                                                                {
                                                                        //eval('$firstpost[\'imageattachmentlinks\'] .= "' . fetch_template('postbit_attachment2') . '";');
                                                                        eval('$firstpost[\'thumbnailattachments\'] .= "' . fetch_template('postbit_attachmentthumbnail2') . '";');
                                                                        //$firstpostshow['imageattachmentlink'] = true;
                                                                        $firstpostshow['thumbnailattachment'] = true;
									$attachedimages++;
                                                                }
                                                        }
                                                        else if ($vboptions['viewattachedimages'] == 2 OR ($vboptions['viewattachedimages'] == 1 AND $attachcount == 1))
                                                        {
                                                                eval('$firstpost[\'imageattachments\'] .= "' . fetch_template('postbit_attachmentimage2') . '";');
                                                                $firstpostshow['imageattachment'] = true;
								$attachedimages++;
                                                        }
                                                        else
                                                        {
                                                                //eval('$firstpost[\'imageattachmentlinks\'] .= "' . fetch_template('postbit_attachment2') . '";');
                                                                eval('$firstpost[\'thumbnailattachments\'] .= "' . fetch_template('postbit_attachmentthumbnail2') . '";');
                                                                $firstpostshow['imageattachmentlink'] = true;
                                                        }
                                                        break;
                                                default:
                                                        $attachedfiles++;
                                                        if ($attachment['qxpress'] == 1) { $qxpressfiles++; }
                                                        eval('$firstpost[\'otherattachments\'] .= "' . fetch_template('postbit_attachment2') . '";');
                                                        $firstpostshow['otherattachment'] = true;
                                        }
                                }
                                else
                                {
                                        $attachedfiles++;
                                        eval('$firstpost[\'moderatedattachments\'] .= "' . fetch_template('postbit_attachmentmoderated') . '";');
                                        $firstpostshow['moderatedattachment'] = true;
                                }
                        }
                        if (!$vboptions['attachthumbs'] AND !$vboptions['viewattachedimages'])
                        {
                                $bbuserinfo['showimages'] = $showimagesprev;
                        }
                        if ($qxpressfiles == 0) { $firstpostshow['qxpressall'] = 0; }
                }
                else
                {
                        $firstpostshow['attachments'] = false;
                }

                $firstpostshow['numattachedfiles'] = $attachedfiles;
                $firstpostshow['numattachedimages'] = $attachedimages;

		if ($_GET['debug'] == 1) { echo "After process attachments..."; }


/*
                        if (isset($vboptions['expansionpacks'])) {

                                foreach($vboptions['expansionpacks'] AS $option => $bitfield) {
                                        //define(strtoupper($option), $bitfield);
                                        if ($uploadstore['epsbitwise'] & $bitfield) {
                                                $gametype[$option] = true;
                                        } else {
                                                $gametype[$option] = false;
                                        }
                                }
                                unset($option, $bitfield);
                        }
*/
                        foreach ($expansionpacks as $epname => $epcode) {
                                if ($uploadstore[epsbitwise] & $epcode) {
                                        $row[$epname] = 1;
                                }
                        }

			$gametype = $gameselect;
			$largeicons = 1;
		        eval('$epicons = "' . fetch_template('epicons') . '";');

		if ($_GET['debug'] == 1) { echo "After epicons..."; }

		/*
		if ($gametype['original']) { $threadinfo[gameOrig] = 1; }
                if ($gametype['ep1_university']) { $threadinfo[gameUni] = 1; }
                if ($gametype['ep2_nightlife']) { $threadinfo[gameNL] = 1; }
                if ($gametype['ep3_openforbusiness']) { $threadinfo[gameOFB] = 1; }
                if ($gametype['ep4_pets']) { $threadinfo[gamePets] = 1; }
                if ($gametype['ep5_seasons']) { $threadinfo[gameSeasons] = 1; }
		if ($gametype['ep6_bonvoyage']) { $threadinfo[gameBV] = 1; }
		if ($gametype['ep7_freetime']) { $threadinfo[gameFT] = 1; }
		if ($gametype['ep8_apartment']) { $threadinfo[gameAP] = 1; }
		if ($gametype['ep0_sims2store']) { $threadinfo[gameS2S] = 1; }

                if ($gametype['sp1_familyfun']) { $threadinfo[gameFFS] = 1; }
                if ($gametype['sp2_glamourlife']) { $threadinfo[gameGLS] = 1; }
		if ($gametype['sp3_celebration']) { $threadinfo[gameCLS] = 1; }
		if ($gametype['sp4_hmfashion']) { $threadinfo[gameHMS] = 1; }
		if ($gametype['sp5_teenstyle']) { $threadinfo[gameTSS] = 1; }
		if ($gametype['sp6_kitchenandbath']) { $threadinfo[gameKBS] = 1; }
                if ($gametype['sp0_holiday']) { $threadinfo[gameHHS] = 1; }
                if ($gametype['sp7_ikeahome']) { $threadinfo[gameIKS] = 1; }
		if ($gametype['sp8_mansionandgarden']) { $threadinfo[gameMGS] = 1; }
		*/

		if (($forumcache[$forumID]['npcat'] == 2) || ($forumcache[$forumID]['npcat'] == 11) || ($forumcache[$forumID]['npcat'] == 50) ) {
		if (isset($uploadstore[stuffser]) && $uploadstore[stuffser] ) {
			$cclist = unserialize($uploadstore[stuffser]);
			if (count($cclist) > 0) {
			foreach ($cclist as $ccpackage) {
				if ($ccpackage[meauthor] == "on") {
					$cctextme .= "\n- ".$ccpackage[title];
				} else {
					$cctext .= "\n- ".$ccpackage[title]." by [url=".$ccpackage[link]."]".$ccpackage[creator]."[/url]";
				}
			}
			}

		}
		}

		// Policy Exception

		if ($uploadstore[uploadpolicy] > 0) {

		if ($isdebug) { echo "Original Policy: ".$bbuserinfo[policies]."<br />"; }
		if ($isdebug) { echo "Thread Policy: ".$uploadstore[uploadpolicy]."<br />"; }

		if (isset($creatorpolicies)) {
			foreach($creatorpolicies AS $option => $bitfield) {
				if ($uploadstore[uploadpolicy] & $bitfield) {
					$policy[$option] = 1;
				} else {
					$policy[$option] = 0;
				}
			}
			unset($option, $bitfield);

                        foreach($creatorpolicies AS $option => $bitfield) {
                                if ($bbuserinfo[policies] & $bitfield) {
                                        $opolicy[$option] = 1;
                                } else {
                                        $opolicy[$option] = 0;
                                }
                        }
                        unset($option, $bitfield);

			if ($isdebug) { echo "<pre>".print_r($policy, true).print_r($opolicy, true)."</pre>"; }

			foreach ($policy as $key => $value) {

				if ($value != $opolicy[$key]) {

				if ($isdebug) {  echo $key." is different...<br />"; }

			        switch ($key) {
			        case "lotpolicym":
			                if ($value == 1) { $policyiconsm .= "<img src='http://www.sims2wiki.info/images/b/b2/Lots-yes.jpg' /> "; } else {
			                $policyiconsm .= "<img src='http://www.sims2wiki.info/images/7/7e/Lots-no.jpg' /> ";
			                }
			                break;
			        case "lotpolicyr":
			                if ($value == 1) { $policyiconsr .= "<img src='http://www.sims2wiki.info/images/b/b2/Lots-yes.jpg' /> "; } else {
			                $policyiconsr .= "<img src='http://www.sims2wiki.info/images/7/7e/Lots-no.jpg' /> ";
			                }
			                break;
			        case "lotpolicyw":
			                if ($value == 1) { $policyiconsw .= "<img src='http://www.sims2wiki.info/images/b/b2/Lots-yes.jpg' /> "; } else {
			                $policyiconsw .= "<img src='http://www.sims2wiki.info/images/7/7e/Lots-no.jpg' /> ";
			                }
			                break;
			        case "simspolicym":
			                if ($value == 1) { $policyiconsm .= "<img src='http://www.sims2wiki.info/images/e/e7/Sims-yes.jpg' /> "; } else {
			                $policyiconsm .= "<img src='http://www.sims2wiki.info/images/6/6f/Sims-no.jpg' /> ";
			                }
			                break;
			        case "simspolicyr":
			                if ($value == 1) { $policyiconsr .= "<img src='http://www.sims2wiki.info/images/e/e7/Sims-yes.jpg' /> "; } else {
			                $policyiconsr .= "<img src='http://www.sims2wiki.info/images/6/6f/Sims-no.jpg' /> ";
			                }
			                break;
			        case "reusetexturepolicym":
			                if ($value == 1) { $policyiconsrr .= "<img src='http://www.sims2wiki.info/images/2/28/Textures-yes.jpg' /> "; } else {
			                $policyiconsrr .= "<img src='http://www.sims2wiki.info/images/6/6d/Textures-no.jpg' /> ";
			                }
			                break;
			        case "mesh1policym":
			                if ($value == 1) { $policyiconsm1 .= "<img src='http://www.sims2wiki.info/images/c/ce/Mesh-yes.jpg' /> "; } else {
			                $policyiconsm1 .= "<img src='http://www.sims2wiki.info/images/4/4f/Mesh-no.jpg' /> ";
			                }
			                break;
			        default:
			                if ($value == 1) {
			                        $policyicons .= "<img src='http://www.sims2wiki.info/images/".$policyiconsimages[$key]."' /> ";
			                }
			                break;
			        }
                                $haspolicyicons = true;

				}
			}

			if ($haspolicyicons) {
			        $policyicontext = "<table>";

			        if ($policyiconsm <> "") {
			                $policyicontext .= "<tr><td valign='top'>Meshes</td><td>".$policyiconsm."</td></tr>";
			        }
			        if ($policyiconsr <> "") {
			                $policyicontext .= "<tr><td valign='top'>Recolours</td><td>".$policyiconsr."</td></tr>";
			        }
			        if ($policyiconsw <> "") {
			                $policyicontext .= "<tr><td valign='top'>Walls/Floors</td><td>".$policyiconsw."</td></tr>";
			        }

				if (($policyiconsrr <> "") || ($policyiconsm1 <> "")) {
				        $policyicontext .= "<tr><td valign='top'>General</td><td>";

				        if ($policyiconsrr <> "") {
				                $policyicontext .= $policyiconsrr;
				        }
				        if ($policyiconsm1 <> "") {
			        	        $policyicontext .= $policyiconsm1;
				        }
				}
			        $policyicontext .= $policyicons."</td></tr></table>";
			}

                }

		}

		if ($_GET['debug'] == 1) { echo "After policy stuff...."; }

		$value2 = array($uploadstore[mesh1], $uploadstore[mesh2], $uploadstore[mesh3], $uploadstore[mesh4], $uploadstore[mesh4]);
		$meshcount = 0;
		$bulletPoint = "&nbsp;<img src='".$vboptions[staticimagehost]."e107_images/newsicons/icon5.png' border='0' />&nbsp;";

                foreach ($value2 as $value) {
                if ($value != "") {
                        if (strpos(strtolower($value), $mydomain."/") === false) {
                                                $linkname = $value;
                                                $linkname = str_replace('http://', '', $linkname);
                                                $linkname = str_replace('www.', '', $linkname);
                                                $meshbits .= $bulletPoint."<a target=\"_blank\" class=\"autolink\" href=\"".$value."\">".$linkname."</a> (non-MTS2 link)<br />";				
                        } else {
                                $value = str_replace("threadid", "t", $value);
                                $pos = strstr(strtolower($value), "t=");
                                //echo $pos."<br />";
                                if ($pos === false)   {
					if (is_numeric($value)) {
		                                $meshes[] = $value;
		                                $meshcount++;
					}
                                } else {
					$value = str_replace("modthesims.info/d/", "modthesims.info/download.php?t=", $value);
                                        $value = str_replace("modthesims.info/t/", "modthesims.info/download.php?t=", $value);

                                        $value = substr($value, strrpos(strtolower($value), "t=")+2);
                                        $value = str_replace("&c=1", "", $value);
					if (is_numeric($value)) {
						$meshes[] = $value;
						$meshcount++;
					}
                                }
                        }
                        $hasmeshes = 1;
                }
		}

                                if ($meshcount > 0) {

                                        $tempquery = "SELECT postusername, postuserid, threadid, title FROM thread WHERE threadid";
                                        if ($meshcount == 1) { $tempquery .= "=".implode(", ", $meshes); } else { $tempquery .= " IN (".implode(", ", $meshes).")"; }

                                        $meshthreads = $DB_site->query($tempquery);
                                        $numthreads = 0;
                                        while ($mesh = $DB_site->fetch_array($meshthreads)) {
                                                $numthreads++;
                                                        $meshbits .= $bulletPoint."<a target=\"_blank\" href=\"/download.php?t=".$mesh[threadid]."\">".$mesh[title]."</a> by <a href='/member.php?u=".$mesh[postuserid]."'>".$mesh[postusername]."</a><br />";
                                                        $buildquery = "(mesh1 = '".$mesh[threadid]."')";
                                        }
                                        $DB_site->free_result($meshthreads);
                                }
		
		if ($_GET['debug'] == 1) { echo "After mesh stuff...."; }

		$actualmessage = $uploadstore['message'];

		if ($forumcache[$forumID]['npcat'] == 11) {
			$actualmessage .= "\n\n[b]Lot Size:[/b] ".$uploadstore[lotsize];
			$actualmessage .= "\n[b]Lot Price (Furnished):[/b] ".$uploadstore[lotprice];
			if (!empty($uploadstore[lotprice_unfurnished])) {
				$actualmessage .= "\n[b]Lot Price (Unfurnished):[/b] ".$uploadstore[lotprice_unfurnished];
			}
		}

		if ($uploadstore[meshtype] == 2) {
			if ($uploadstore[polycounts] != '') { $actualmessage .= "\n\n[b]Polygon Counts:[/b]\n".$uploadstore[polycounts]; }
		}
		if ($cctextme != '') { $actualmessage .= "\n\n[b]Custom Content by Me:[/b]".$cctextme; }
		if ($cctext != '') { $actualmessage .= "\n\n[b]Custom Content Included:[/b]".$cctext; }
		if ($uploadstore[addcredits] != '') { $actualmessage .= "\n\n[b]Additional Credits:[/b]\n".$uploadstore[addcredits]; }

        $fsearchparms = array();
        if ($forumcache[$forumID]['searchparms'] != '') {
                $fsearchparms = unserialize($forumcache[$forumID]['searchparms']);
        } else {
                // Check forums parent
                if ($forumcache[$forumcache[$forumID]['parentid']]['searchparms'] != '') {
                        $fsearchparms = unserialize($forumcache[$forumcache[$forumID]['parentid']]['searchparms']);
                }
        }

        if (count($fsearchparms) > 0) {
		$searchquery = unserialize($uploadstore['searchparms']);

                $searchp = array();
                $searchparms = '';

                for($i = 1; $i <= 10; $i++) {

                if (($fsearchparms['d'.$i] != 1) && ($fsearchparms['t'.$i] != '') && ($searchquery['p'.$i] != '')) {

//			echo "<pre>".print_r($searchquery, true)."</pre>";

                        $searchparms .= $fsearchparms['t'.$i].": ";

                        $searchp = explode("\n", $fsearchparms['p'.$i]);
                        foreach ($searchp as $value) {

                                $blah = explode(" - ", $value);
	                        if (!is_array($searchquery['p'.$i])) {
					if (trim($blah[0]) == $searchquery['p'.$i]) { $searchparms .= "<em><a href='#' title=\"".trim($value)."\" style='border-bottom:1px dotted; text-decoration:none'>".trim($blah[0])."</a></em> "; }
        	                } else {
                                foreach($searchquery['p'.$i] as $wark) {
                                        if (trim($blah[0]) == $wark) { $searchparms .= "<em><a href='#' title=\"".trim($value)."\" style='border-bottom:1px dotted; text-decoration:none'>".trim($blah[0])."</a></em> "; }
                                }
				}
                        }
                        $searchparms .= "<br />";

                        //$searchparms .= "<em>".$searchquery['parm'.$i]."</em><br />";

                }

                }
        }

	if ($_GET['debug'] == 1) { echo "After searchparms stuff..."; }


                $instructions = array();

                $installs = $DB_site->query("SELECT title, postid, pagetext FROM post WHERE threadid=311335");
                while ($instructpost = $DB_site->fetch_array($installs)) {

                        $instructions[$instructpost[title]] = parse_bbcode($instructpost[pagetext], 429, 1);
                }

	if ($_GET['debug'] == 1) { echo "After instructions..."; }

        // Install instructions
        $installtext = '';


//      if ($bbuserinfo[userid] == 1) { echo "<pre>".print_r($instructions, true)."</pre>"; }


        switch ($forumcache[$uploadstore[forumID]][npcat])
        {
                case "2":
                case "11":
                case "21":
                        $installtext = $instructions["Install Instructions - Sims2Pack:"];
                        break;

        }

        if ($showCEPinfo == true) {
                $installtext = $instructions["Install Instructions - Standard + CEP:"];
        }
/*
        if ($forumid == 151) {
                if ($threadinfo[category] == "Maps Only") { $installtext = $instructions["Install Instructions - SC4:"]; }
                if ($threadinfo[category] == "Neighbourhood") { $installtext = $instructions["Install Instructions - Full Neighborhood:"]; }
        }
*/


        if ($uploadstore[custominstalltext] != '') {

                switch ($uploadstore[custominstalltext])
                {
                        case "Install Instructions - Scriptorium:":
                                $installtext = $instructions["Install Instructions - Scriptorium:"];
                                break;
                        case "Install Instructions - SC4:":
                                $installtext = $instructions["Install Instructions - SC4:"];
                                break;
                        case "Install Instructions - Panties:":
                                $installtext = $instructions["Install Instructions - Panties:"];
                                break;
                        case "Install Instructions - Full Neighborhood:":
                                $installtext = $instructions["Install Instructions - Full Neighborhood:"];
                                break;
                        default:
                                $installtext = str_replace("##CUSTOMINSTALLTEXT##", parse_bbcode($uploadstore[custominstalltext], 429, 0), $instructions['Install Instructions - Custom Install:']);
                }

        }

        if ($installtext == '') {
		if ($uploadstore[gameselect] == 2) { 
		        switch ($forumcache[$uploadstore[forumID]][npcat])
		        {
		                case "28":
		                        $installtext = $instructions["Install Instructions - Sims 3 Global Mods:"];
		                        break;
				default:
					$installtext = $instructions["Install Instructions - Sims 3:"];
					break;
		        }
		} else {
	                $installtext = $instructions["Install Instructions - Standard Install:"];
		}
        }

        if ($threadextra[multiposttext] != '') {
                $uploadstore['multiposttext'] = parse_bbcode($uploadstore['multiposttext'], 429, 0);
        }
        /*
        if ($threadextra[custominstalltext] != '') {
                $threadextra['custominstalltext'] = parse_bbcode($threadextra['custominstalltext'], 429, 0);
        }
        */
        if ($uploadstore[relateduploadtext] != '') {
                $uploadstore['relateduploadtext'] = parse_bbcode($uploadstore['relateduploadtext'], 429, 0);
        }


		if ($bbuserinfo['userid'] == 1) { echo "Dumping actualmessage..."; var_dump($actualmessage); }
                $firstpost[message] = parse_bbcode($actualmessage, $forumID, 1);
		eval("\$extracss = \"".fetch_template('extracss')."\";");

                $template = "upload_stage12";
                break;

	case "13":

                $stagetitles[1]['enabled'] = true;
                if ($uploadstore['category'] != "") { $stagetitles[2]['enabled'] = true; }
                $stagetitles[3]['enabled'] = true;
                $stagetitles[4]['enabled'] = true;
                $stagetitles[5]['enabled'] = true;
                if ($forumcache[$forumID]['mrm'] == "1") {
                        $stagetitles[6]['enabled'] = true;
                }
                if (($forumcache[$forumID]['npcat'] == 2) || (($forumcache[$forumID]['mrm'] == "1") && ($uploadstore['meshtype'] == 3))) {
                        $stagetitles[7]['enabled'] = true;
                }
                $stagetitles[8]['enabled'] = true;
                $stagetitles[9]['enabled'] = true;
                $stagetitles[10]['enabled'] = true;
                $stagetitles[11]['enabled'] = true;

		$userinfo = fetch_userinfo($uploadstore['userid']);

                $queueBypassArray = calcQueueBypass($userinfo['userid'], $userinfo['username'], $gameselect);
                $canBypass = $queueBypassArray['fastpass'];

                if (isset($_REQUEST['dontBypass'])) {
                        $canBypass = false;
                }

                $template = "upload_stage13";
		break;

	default:
                break;

}

if ($isdebug) { echo $template."<br />"; }

	if ($showAnnouncements)  {

                // Check to see if we have a specific link between this forum npcat and the guidelines
                $npcat = $forumcache[$forumID]['npcat'];
                $guidelines = $DB_site->query("SELECT pagetext FROM post WHERE threadid=352539 AND title='".$npcat." - ".$gameselect."'");
				if ($gameselect == 4) $gameName = 'TS4';
				if ($gameselect == 3) $gameName = 'TS3';
				if ($gameselect == 2) $gameName = 'TS3';
				if ($gameselect == 1) $gameName = 'TS2';

                $guidelinebits .= '<p style="align:center;text-align:center;"><iframe height="400" src="/rubrics/forum/'.$forumID.'/'.$gameName.'/" width="100%"></iframe></p>';

				/*
                if ($DB_site->num_rows($guidelines) > 0) {
                        while ($guideline = $DB_site->fetch_array($guidelines))
                        {
				$guideline[pagetext] = str_replace("[url]", "", $guideline[pagetext]);
				$guideline[pagetext] = str_replace("[/url]", "", $guideline[pagetext]);
				if ($bbuserinfo[userid] == 1) { echo "<pre>".print_r($guideline, true)."</pre>"; }
                                $lines = explode("\n", $guideline[pagetext]);
                                foreach ($lines as $line) {
                                        $stuff = explode(" ", $line);
                                        $guidelinebits .= '<p style="align:center;text-align:center;">';
                                        //if ($stuff[1] != "") { $guidelinebits .= $stuff[1]."<br />"; }
                                        $guidelinebits .= '<iframe height="300" src="'.$stuff[0].'" width="100%"></iframe>';
                                        $guidelinebits .= "</p>";
                                }
                        }
                }
					*/

                if ($isdebug) {  echo "Getting announcements...<br />"; }
                $forumlist = fetch_forum_clause_sql($forumID, 'announcement.forumid');
                if ($isdebug) {  echo $forumlist."<br />"; }

                $announcements = $DB_site->query("
                SELECT announcementid, startdate, enddate, announcement.title, pagetext, allowhtml, allowbbcode, allowsmilies, views,
                user.*,
                IF(displaygroupid=0, user.usergroupid, displaygroupid) AS displaygroupid
                FROM  " . TABLE_PREFIX . "announcement AS announcement
                LEFT JOIN " . TABLE_PREFIX . "user AS user ON(user.userid=announcement.userid)
                " . iif($announcementid, "WHERE announcementid = $announcementid", "
                        WHERE startdate <= " . (TIMENOW - $vboptions['hourdiff']) . "
                                AND enddate >= " . (TIMENOW - $vboptions['hourdiff']) . "
                                AND $forumlist
                        ORDER BY startdate DESC LIMIT 2
                ")
                );
                if ($DB_site->num_rows($announcements) > 0)
                {

                        require_once('./includes/functions_showthread.php');
                        while ($post = $DB_site->fetch_array($announcements))
                        {

                                $post['musername'] = fetch_musername($post);

                                $post['dateline'] = $post['startdate'];

                                $post['startdate'] = vbdate($vboptions['dateformat'], $post['startdate'], false, true, false);
                                $post['enddate'] = vbdate($vboptions['dateformat'], $post['enddate'], false, true, false);

                                if ($post['startdate'] > $bbuserinfo['lastvisit'])
                                {
                                        $post['statusicon'] = 'new';
                                }
                                else
                                {
                                        $post['statusicon'] = 'old';
                                }

                                $announcebits .= construct_postbit($post, 'postbit', 'announcement');
                                $anncids .= ", $post[announcementid]";
                                $announcetitle = $post[title];
                                $announcedate = $post['startdate'];
                                $announceicon = $post[statusicon];
                        }

                }

	}

$maxstage = $uploadstore[maxstage];
if ($maxstage >= 1) { $stagetitles[1]['enabled'] = true; }
if ($maxstage >= 2) { if ($uploadstore['category'] != "") { $stagetitles[2]['enabled'] = true; } }
if ($maxstage >= 3) { $stagetitles[3]['enabled'] = true; }
if ($maxstage >= 4) { $stagetitles[4]['enabled'] = true; }
if ($maxstage >= 5) { $stagetitles[5]['enabled'] = true; }
if ($maxstage >= 6) {
	if ($forumcache[$forumID]['mrm'] == "1") {
		$stagetitles[6]['enabled'] = true;
	}
}
if ($maxstage >= 7) {
	if (($forumcache[$forumID]['npcat'] == 2) || (($forumcache[$forumID]['mrm'] == "1") && ($uploadstore['meshtype'] == 3))) {
		$stagetitles[7]['enabled'] = true;
	}
}
if ($maxstage >= 8) {
	if (($forumID == 406) || ($forumID == 407)) {
	} else {
		$stagetitles[8]['enabled'] = true;
	}
}
if ($maxstage >= 9) {
	$stagetitles[9]['enabled'] = true;
}
if ($maxstage >= 10) {
        $stagetitles[10]['enabled'] = true;
	$stagetitles[11]['enabled'] = true;
	$stagetitles[12]['enabled'] = true;
}

$mytitle = $stagetitles[$stage]['title'];

if ($uppertext == '') { $uppertext = $uploadstore[uppertext]; }

$ahref = "<a href='/upload.php?posthash=".$posthash."&stage=";

$stagemenu = "<ol>";

for($i=0; $i < count($stagetitles); $i++) {

	if ($i <> 9) { 

	$stagemenu .= "<li style='font-size:0.9em;'>";
	if ($stagetitles[$i]['enabled'] == true) { 
		$stagemenu .= $ahref.$i;
		$stagemenu .= "'>"; 
	}
	if ($i == $stage) { $stagemenu .= "<strong>"; }
	$stagemenu .= $stagetitles[$i]['title'];
	if ($i == $stage) { $stagemenu .= "</strong>"; }
	if ($stagetitles[$i]['enabled'] == true) { $stagemenu .= "</a>"; }
	$stagemenu .= "</li>";

	}
}

$stagemenu .= "</ol>";

// Done processing so output stuff.
$navbits = construct_navbits($navbits);

eval("\$headinclude = \"".fetch_template('headinclude')."\";");
eval("\$navbar = \"".fetch_template('navbar')."\";");

eval("\$contenttext = \"".fetch_template($template)."\";");

eval("print_output(\"".fetch_template('upload_frontpage')."\");");

?>
