Security patches from upstream - and general cleanup of old hacks
Security patches from upstream - and general cleanup of old hacks

file:a/admin.php -> file:b/admin.php
--- a/admin.php
+++ b/admin.php
@@ -40,6 +40,25 @@
 
 // check that user has permissions to perform this action before going further.  Otherwise kick 'em
 	if(!isADMIN) accessDenied( );
+	// The admin panels put these values straight into SQL. They are all ids, so anything
+	// else (other than the few words the panels use) is refused here once for all panels.
+	$ef_idkeys = array('uid', 'sid', 'rid', 'chapid', 'catid', 'parentcatid', 'charid', 'class', 'type_id', 'subof', 'field', 'displayorder',
+		'after', 'orderafter', 'revoke', 'lock', 'unlock', 'validate', 'release', 'retire', 'remove', 'feature', 'level', 'adlevel', 'category',
+		'cat', 'delete', 'edit', 'warning', 'reviewid', 'seriesid', 'inorder', 'message_id', 'link_id', 'nid', 'cid', 'panel_level');
+	// "type" is used by admin/classifications.php (delete=type)
+	$ef_words = array('', 'new', 'class', 'type', 'yes', 'no', 'all', '-1', 'on');
+	// these are posted as text (category name in admin/categories.php, warning text in admin/warnings.php)
+	$ef_posttext = array('category', 'warning');
+	foreach(array('_GET' => $_GET, '_POST' => $_POST) as $ef_src => $ef_vals) {
+		foreach($ef_idkeys as $ef_k) {
+			if(!isset($ef_vals[$ef_k])) continue;
+			if($ef_src == '_POST' && in_array($ef_k, $ef_posttext, true)) continue;
+			foreach((array)$ef_vals[$ef_k] as $ef_v) {
+				if(is_array($ef_v) || (!in_array((string)$ef_v, $ef_words, true) && !preg_match('/^-?[0-9]+(,-?[0-9]+)*$/', (string)$ef_v))) accessDenied(_ERROR." (".$ef_k.")");
+			}
+		}
+	}
+	unset($ef_idkeys, $ef_words, $ef_posttext, $ef_src, $ef_vals, $ef_k, $ef_v);
 	$adminquery = dbquery("SELECT categories FROM ".TABLEPREFIX."fanfiction_authorprefs WHERE uid = '".USERUID."' LIMIT 1");
 	list($admincats) = dbrow($adminquery);
 	if(empty($admincats)) $admincats = "0";

--- a/blocks/poll/poll.php
+++ b/blocks/poll/poll.php
@@ -32,6 +32,8 @@
 	$poll = isset($_POST['poll_id']) && isNumber($_POST['poll_id']) ? $_POST['poll_id'] : false;
 	$opt = isset($_POST['opt']) && isNumber($_POST['opt']) ? $_POST['opt'] : false;
 	if(!$poll || !$opt) accessDenied( ); // could only be a hack attempt.
+	if(!isMEMBER || !$currentpoll || (int)$poll !== (int)$currentpoll['poll_id'] || (int)$opt < 1 || (int)$opt > count(explode("|#|", $currentpoll['poll_opts']))) accessDenied( );
+	$poll = (int)$poll; $opt = (int)$opt;
 	$voted = dbquery("SELECT vote_id FROM ".TABLEPREFIX."fanfiction_poll_votes WHERE vote_poll = '".$currentpoll['poll_id']."' AND vote_user = '".USERUID."'");
 	list($voter) = dbrow($voted);
         if(!$voter) $cast = dbquery("INSERT INTO ".TABLEPREFIX."fanfiction_poll_votes(`vote_user`, `vote_opt`, `vote_poll`) VALUES('".USERUID."', '$opt', '$poll')");
@@ -79,3 +81,4 @@
 }
 	$content .= "<div style='text-align: center;'><a href='"._BASEDIR."blocks/poll/pollarchive.php'>"._POLLARCHIVE."</a></div>";
 ?>
+

--- a/blocks/shoutbox/shoutbox.php
+++ b/blocks/shoutbox/shoutbox.php
@@ -8,11 +8,12 @@
 	http_response_code(202);
 	if(isMEMBER) $shout_name = USERUID;
 	else {
-		$shout_name = trim(descript($_POST['shoutname']));
-		if(isNumber($shout_name)) $shout_name = _GUEST;
+		$shout_name = isset($_POST['shoutname']) && is_string($_POST['shoutname']) ? trim(strip_tags($_POST['shoutname'])) : "";
+		$shout_name = function_exists('mb_substr') ? mb_substr($shout_name, 0, 30) : substr($shout_name, 0, 30);
+		if($shout_name === "" || isNumber($shout_name)) $shout_name = _GUEST;
 		if($captcha && !captcha_confirm()) $shout_name = false;
 	}
-	$shout_message = trim($_POST['shout_message']);
+	$shout_message = isset($_POST['shout_message']) && is_string($_POST['shout_message']) ? trim($_POST['shout_message']) : "";
 	$shout_message = preg_replace("/^(.{200}).*$/", "$1", $shout_message);
 	$shout_message = preg_replace("/[^\s]{25}/", "$1\n", $shout_message);
 	$search = array("\"", "'", "\\", '\"', "\'", "<", ">", "&nbsp;", "\n");
@@ -20,7 +21,7 @@
 	$shout_message = str_replace($search, $replace, replace_naughty(trim($shout_message)));
 	$shout_message = str_replace("\n", "<br />", $shout_message);
 	if(!empty($shout_name) && !empty($shout_message)) {
-		dbquery("INSERT INTO ".TABLEPREFIX."fanfiction_shoutbox(`shout_name`, `shout_message`, `shout_datestamp`) VALUES('$shout_name', '$shout_message', '".time()."')");
+		dbquery("INSERT INTO ".TABLEPREFIX."fanfiction_shoutbox(`shout_name`, `shout_message`, `shout_datestamp`) VALUES('".escapestring($shout_name)."', '".escapestring($shout_message)."', '".time()."')");
 	}
 
 }

--- a/modules/betareader/install.php
+++ b/modules/betareader/install.php
@@ -28,7 +28,7 @@
 $tpl->assignInclude( "footer", "$skindir/footer.tpl" );
 include(_BASEDIR."includes/pagesetup.php");
 include_once(_BASEDIR."languages/".$language."_admin.php");
-if(!isADMIN) accessDenied( );       
+if(!isADMIN || uLEVEL > 1) accessDenied( );     
 $confirm = isset($_GET['confirm']) ? $_GET['confirm'] : false;
 if($confirm == "yes") {
 	list($installed) = dbrow(dbquery("SELECT COUNT(code_module) FROM ".TABLEPREFIX."fanfiction_codeblocks WHERE code_module = 'betareader'"));
@@ -49,3 +49,4 @@
 $tpl->assign("output", $output);
 $tpl->printToScreen( );
 ?>
+

--- a/modules/betareader/uninstall.php
+++ b/modules/betareader/uninstall.php
@@ -28,7 +28,7 @@
 $tpl->assignInclude( "footer", "$skindir/footer.tpl" );
 include(_BASEDIR."includes/pagesetup.php");
 include_once(_BASEDIR."languages/".$language."_admin.php");
-if(!isADMIN) accessDenied( );
+if(!isADMIN || uLEVEL > 1) accessDenied( );
 $confirm = isset($_GET['confirm']) ? $_GET['confirm'] : false;
 if($confirm == "yes") {
 	include("version.php");
@@ -47,3 +47,4 @@
 $tpl->assign("output", $output);
 $tpl->printToScreen( );
 ?>
+

--- a/modules/betareader/update.php
+++ b/modules/betareader/update.php
@@ -34,7 +34,7 @@
 else include_once(_BASEDIR."languages/en_admin.php");
 if(file_exists(_BASEDIR."languages/".$language.".php")) include_once(_BASEDIR."languages/".$language.".php");
 else include_once(_BASEDIR."languages/en.php");
-if(!isADMIN) accessDenied( );
+if(!isADMIN || uLEVEL > 1) accessDenied( );
 $confirm = isset($_GET['confirm']) ? $_GET['confirm'] : false;
 include("version.php");
 list($currentVersion) = dbrow(dbquery("SELECT version FROM ".TABLEPREFIX."fanfiction_modules WHERE name = '$moduleName' LIMIT 1"));
@@ -56,3 +56,4 @@
 $tpl->assign("output", $output);
 $tpl->printToScreen( );
 ?>
+

--- a/modules/challenges/challenges.php
+++ b/modules/challenges/challenges.php
@@ -34,8 +34,8 @@
 $tpl->assignInclude( "footer", "$skindir/footer.tpl" );
 include(_BASEDIR."includes/pagesetup.php");
 
-$chalid = isset($_GET['chalid']) ? $_GET['chalid'] : false;
-if($chalid && !isNumber($chalid)) unset($chalid, $action);
+$chalid = isset($_GET['chalid']) && is_string($_GET['chalid']) && isNumber($_GET['chalid']) ? (int)$_GET['chalid'] : false;
+if(isset($_GET['chalid']) && !$chalid) { unset($chalid); $action = false; }
 
 // security check
 	$admin = 0;
@@ -47,7 +47,7 @@
 			$challenge = dbquery("SELECT uid, catid from ".TABLEPREFIX."fanfiction_challenges WHERE chalid='$chalid' LIMIT 1");
 			list($chaluid, $catid) = dbrow($challenge);
 			if(uLEVEL == 3 && $admincats != 0) {
-				$seriescats = explode(",", $catid);
+				$seriescats = explode(",", $catid ?? "");
 				$adcats = explode(",", $admincats);
 				foreach($seriescats as $cat) {
 					if(in_array($cat, $adcats)) $admin = 1;
@@ -55,6 +55,21 @@
 			}
 			if($chaluid != USERUID &&  $admin != 1 && uLEVEL > 2) accessDenied( );
 		}
+	}
+	// Editing and deleting: only the challenge's owner or an admin. Removing a response:
+	// also the author of that story or series. (Before 3.5.78 the check above only
+	// covered level-3 admins, so any member could edit, delete or strip any challenge.)
+	if(in_array($action, array("edit", "delete", "remove"), true)) {
+		if(empty($chalid)) accessDenied( );
+		$ef_chal = dbrow(dbquery("SELECT uid FROM ".TABLEPREFIX."fanfiction_challenges WHERE chalid = '".(int)$chalid."' LIMIT 1"));
+		if(!$ef_chal) accessDenied( );
+		$ef_ok = $admin || (USERUID && (int)$ef_chal[0] === (int)USERUID);
+		if(!$ef_ok && $action == "remove" && USERUID) {
+			// same order as the removal below: a series when one is named, otherwise the story
+			if(isset($seriesid)) $ef_ok = !empty($seriesid) && (bool)dbrow(dbquery("SELECT seriesid FROM ".TABLEPREFIX."fanfiction_series WHERE seriesid = '".(int)$seriesid."' AND uid = '".(int)USERUID."' LIMIT 1"));
+			else if(!empty($sid)) $ef_ok = (bool)dbrow(dbquery("SELECT s.sid FROM ".TABLEPREFIX."fanfiction_stories AS s LEFT JOIN ".TABLEPREFIX."fanfiction_coauthors AS c ON c.sid = s.sid AND c.uid = '".(int)USERUID."' WHERE s.sid = '".(int)$sid."' AND (s.uid = '".(int)USERUID."' OR c.uid IS NOT NULL) LIMIT 1"));
+		}
+		if(!$ef_ok) accessDenied( );
 	}
 
 // end security check
@@ -68,16 +83,16 @@
 		if(isset($seriesid)) {
 			$chalinfo =dbquery("SELECT challenges FROM ".TABLEPREFIX."fanfiction_series WHERE seriesid = '$seriesid'");
 			list($challenges) = dbrow($chalinfo);
-			$challenges = explode(",", $challenges);
-			$result = dbquery("UPDATE ".TABLEPREFIX."fanfiction_series SET challenges = '".array_diff($challenges, explode(",", $chalid))."' WHERE seriesid = '$seriesid'");
+			$challenges = explode(",", $challenges ?? "");
+			$result = dbquery("UPDATE ".TABLEPREFIX."fanfiction_series SET challenges = '".implode(",", array_diff($challenges, array((string)$chalid)))."' WHERE seriesid = '".(int)$seriesid."'");
 		}
 		else {
 			$chalinfo = dbquery("SELECT challenges FROM ".TABLEPREFIX."fanfiction_stories WHERE sid = '$sid'");
 			list($challenges) = dbrow($chalinfo);
-			$challenges = explode(",", $challenges);
+			$challenges = explode(",", $challenges ?? "");
 			$result = dbquery("UPDATE ".TABLEPREFIX."fanfiction_stories SET challenges = '".implode(",", array_diff($challenges, explode(",", $chalid)))."' WHERE sid = '$sid'");
 		}
-		if($result) dbquery("UPDATE ".TABLEPREFIX."fanfiction_challenges SET responses = responses - 1 WHERE chalid = '$chalid'");
+		if($result && $GLOBALS['dbconnect']->affected_rows > 0) dbquery("UPDATE ".TABLEPREFIX."fanfiction_challenges SET responses = GREATEST(responses - 1, 0) WHERE chalid = '".(int)$chalid."'");
 		$output .= write_message(_ACTIONSUCCESSFUL);
 	}
 }
@@ -90,15 +105,15 @@
 
 	$output .= "<div id=\"pagetitle\">".($action == "edit" ? _EDITCHALLENGE : _ADDCHALLENGE)."</div>";
 	if(isset($_POST['submit'])) {
-		$title = escapestring(descript($_POST['title'], $allowed_tags));
-		$summary = escapestring(replace_naughty(strip_tags(descript($_POST['summary']), $allowed_tags)));
-		$challenger = escapestring(strip_tags(descript($_POST['challenger']), $allowed_tags));
+		$title = escapestring(descript($_POST['title'] ?? '', $allowed_tags));
+		$summary = escapestring(replace_naughty(strip_tags(descript($_POST['summary'] ?? ''), $allowed_tags)));
+		$challenger = escapestring(strip_tags(descript($_POST['challenger'] ?? ''), $allowed_tags));
 		if(!$challenger) $challenger = _ANONYMOUS;
 		$challengeruid = isset($_POST['challengeruid']) && isNumber($_POST['challengeruid']) ? $_POST['challengeruid'] : 0;
-		$catid = isset($_POST['catid']) ? array_filter(explode(",", $_POST['catid']), "isNumber") : array( );
+		$catid = isset($_POST['catid']) ? array_filter(is_array($_POST['catid']) ? $_POST['catid'] : explode(",", $_POST['catid']), "isNumber") : array( );
 		$category = implode(",", $catid);
 		if(!$category) $category = -1;
-		$characters = isset($_POST['charid']) ? array_filter($_POST['charid'], "isNumber") : array( );
+		$characters = isset($_POST['charid']) ? array_filter((array)$_POST['charid'], "isNumber") : array( );
 		$charid = implode(",", $characters);
 		if(empty($title) || empty($summary)) {
 			$output .= write_error(_REQUIREDINFO);
@@ -188,10 +203,13 @@
 			dbquery("DELETE FROM ".TABLEPREFIX."fanfiction_challenges WHERE chalid = '$chalid'");
 			$responses = dbquery("SELECT challenges, sid FROM  ".TABLEPREFIX."fanfiction_stories WHERE FIND_IN_SET($chalid, challenges) > 0");
 			while($response = dbassoc($responses)) {
-				$challenges = explode(",", $response[challenges]);
-				if(is_array($challenges)) 
-					foreach($challenges as $key=>$value) { if($value == $chalid) unset($challenges[$key]); }
-				dbquery("UPDATE  ".TABLEPREFIX."fanfiction_stories SET challenges = '".implode(",", $challenges)."' WHERE sid = $response[sid] LIMIT 1");
+				$challenges = array_diff(explode(",", $response['challenges']), array((string)$chalid));
+				dbquery("UPDATE  ".TABLEPREFIX."fanfiction_stories SET challenges = '".escapestring(implode(",", $challenges))."' WHERE sid = '".(int)$response['sid']."' LIMIT 1");
+			}
+			$responses = dbquery("SELECT challenges, seriesid FROM  ".TABLEPREFIX."fanfiction_series WHERE FIND_IN_SET($chalid, challenges) > 0");
+			while($response = dbassoc($responses)) {
+				$challenges = array_diff(explode(",", $response['challenges']), array((string)$chalid));
+				dbquery("UPDATE  ".TABLEPREFIX."fanfiction_series SET challenges = '".escapestring(implode(",", $challenges))."' WHERE seriesid = '".(int)$response['seriesid']."' LIMIT 1");
 			}
 			$output .=  write_message(_ACTIONSUCCESSFUL."  <a href=\"challenges.php\">"._BACK2PREVIOUS."</a>");
 		}
@@ -279,9 +297,9 @@
 
 		$challenge = dbquery("SELECT * FROM  ".TABLEPREFIX."fanfiction_challenges WHERE chalid = '$chalid' LIMIT 1");
 		list($chalid, $challenger, $uid, $title, $cat, $chars, $summary, $responses) = dbrow($challenge);
-		$challenger = stripslashes($challenger);
-		$title = stripslashes($title);
-		$summary= stripslashes($summary);
+		$challenger = stripslashes($challenger ?? "");
+		$title = stripslashes($title ?? "");
+		$summary= stripslashes($summary ?? "");
 
 		$challenges->newBlock("titleblock");
 		if(isADMIN || USERUID == $uid) $challenges->assign("adminoptions", "<div class=\"adminoptions\">".($admin ? _ADMINOPTIONS : _OPTIONS).": [<a href=\"challenges.php?action=edit&amp;chalid=$chalid\">"._EDIT."</a>] [<a href=\"challenges.php?action=delete&amp;chalid=$chalid\">"._DELETE."</a>]</div>");

--- a/modules/challenges/install.php
+++ b/modules/challenges/install.php
@@ -11,7 +11,7 @@
 include_once(_BASEDIR."languages/".$language."_admin.php");
 if(file_exists("languages/".$language.".php")) include_once("languages/".$language.".php");
 else include_once("languages/en.php");
-if(!isADMIN) accessDenied( );
+if(!isADMIN || uLEVEL > 1) accessDenied( );
 $confirm = isset($_GET['confirm']) ? $_GET['confirm'] : false;
 $table = dbassoc(dbquery("SHOW TABLES LIKE '".TABLEPREFIX."challenges'"));
 if($table) $output .= write_message(_ALREADYINSTALLED);
@@ -77,3 +77,4 @@
 $tpl->assign("output", $output);
 $tpl->printToScreen( );
 ?>
+

--- a/modules/challenges/otherresults.php
+++ b/modules/challenges/otherresults.php
@@ -51,8 +51,9 @@
 	if(!empty($cats)) $chalquery[] = "(".implode(" OR ", $cats).")";
 }
 if($searchterm) {
-	if($searchtype == "title") $chalquery[] = "title LIKE '%$searchterm%'";
-	if($searchtype == "summary") $chalquery[] = "summary LIKE '%$searchterm%'";
+	$ef_st = escapestring(str_replace(array('\\', '%', '_'), array('\\\\', '\\%', '\\_'), stripslashes($searchterm)));
+	if($searchtype == "title") $chalquery[] = "title LIKE '%$ef_st%'";
+	if($searchtype == "summary") $chalquery[] = "summary LIKE '%$ef_st%'";
 }
 if(count($chalquery) > 0) {
 	$chalquery = "WHERE ".implode(" AND ", $chalquery);
@@ -64,3 +65,4 @@
 	unset($where, $query, $chars, $cats);
 }
 ?>
+

--- a/modules/challenges/uninstall.php
+++ b/modules/challenges/uninstall.php
@@ -9,7 +9,7 @@
 $tpl->assignInclude( "footer", "$skindir/footer.tpl" );
 include(_BASEDIR."includes/pagesetup.php");
 include_once(_BASEDIR."languages/".$language."_admin.php");
-if(!isADMIN) accessDenied( );
+if(!isADMIN || uLEVEL > 1) accessDenied( );
 $confirm = isset($_GET['confirm']) ? $_GET['confirm'] : false;
 if($confirm == "yes") {
 	dbquery("DELETE FROM `".TABLEPREFIX."fanfiction_codeblocks` WHERE code_module = 'challenges'");
@@ -34,3 +34,4 @@
 $tpl->assign("output", $output);
 $tpl->printToScreen( );
 ?>
+

--- a/modules/challenges/update.php
+++ b/modules/challenges/update.php
@@ -11,7 +11,7 @@
 include_once(_BASEDIR."languages/".$language."_admin.php");
 if(file_exists("languages/".$language.".php")) include_once("languages/".$language.".php");
 else include_once("languages/en.php");
-if(!isADMIN) accessDenied( );
+if(!isADMIN || uLEVEL > 1) accessDenied( );
 $confirm = isset($_GET['confirm']) ? $_GET['confirm'] : false;
 include("version.php");
 list($currentVersion) = dbrow(dbquery("SELECT version FROM ".TABLEPREFIX."fanfiction_modules WHERE name = 'Challenges' LIMIT 1"));
@@ -43,3 +43,4 @@
 $tpl->assign("output", $output);
 $tpl->printToScreen( );
 ?>
+

--- a/modules/notifications/install.php
+++ b/modules/notifications/install.php
@@ -28,7 +28,7 @@
 $tpl->assignInclude( "footer", "$skindir/footer.tpl" );
 include(_BASEDIR."includes/pagesetup.php");
 include_once(_BASEDIR."languages/".$language."_admin.php");
-if(!isADMIN) accessDenied( );       
+if(!isADMIN || uLEVEL > 1) accessDenied( );     
 $confirm = isset($_GET['confirm']) ? $_GET['confirm'] : false;
 if($confirm == "yes") {
 	list($installed) = dbrow(dbquery("SELECT COUNT(name) FROM ".TABLEPREFIX. "fanfiction_modules WHERE name = 'notifications'"));

--- a/modules/notifications/uninstall.php
+++ b/modules/notifications/uninstall.php
@@ -28,7 +28,7 @@
 $tpl->assignInclude( "footer", "$skindir/footer.tpl" );
 include(_BASEDIR."includes/pagesetup.php");
 include_once(_BASEDIR."languages/".$language."_admin.php");
-if(!isADMIN) accessDenied( );
+if(!isADMIN || uLEVEL > 1) accessDenied( );
 $confirm = isset($_GET['confirm']) ? $_GET['confirm'] : false;
 if($confirm == "yes") {
 	include("version.php");

file:a/news.php -> file:b/news.php
--- a/news.php
+++ b/news.php
@@ -51,16 +51,18 @@
 if($nid) {
 
 	$output .= "<div id=\"pagetitle\">"._NEWS."</div>";
-	if(isset($_POST['submit']))
+	if(isset($_POST['submit']) && isset($_POST['comment']) && is_string($_POST['comment']))
 	{
 		$comment = escapestring(format_story(replace_naughty(strip_tags($_POST['comment'], $allowed_tags))));
-		if(!$cid && USERUID) {
-			$insert = dbquery("INSERT INTO ".TABLEPREFIX."fanfiction_comments (nid, uid, comment, time) VALUES ('$nid', '".(USERUID ? USERUID : 0)."', '$comment', '" . time() . "')");
+		$ef_news_ok = (bool)dbrow(dbquery("SELECT nid FROM ".TABLEPREFIX."fanfiction_news WHERE nid = '$nid' LIMIT 1"));
+		if(!$cid && USERUID && $newscomments && $ef_news_ok && trim($comment) !== "") {
+			$insert = dbquery("INSERT INTO ".TABLEPREFIX."fanfiction_comments (nid, uid, comment, time) VALUES ('$nid', '".(int)USERUID."', '$comment', now())");
 			if($insert) dbquery("UPDATE ".TABLEPREFIX."fanfiction_news SET comments = comments + 1 WHERE nid = '$nid' LIMIT 1");
 		}
-		else if($cid) {
-			dbquery("UPDATE ".TABLEPREFIX."fanfiction_comments SET comment = '$comment' WHERE cid = '$cid'");
+		else if($cid && isADMIN && uLEVEL < 4) {
+			dbquery("UPDATE ".TABLEPREFIX."fanfiction_comments SET comment = '$comment' WHERE cid = '$cid' AND nid = '$nid'");
 		}
+		else accessDenied( );
 		unset($comment);
 	}
 	if(isset($_GET['del']) && isADMIN && uLEVEL < 4 && !empty($cid)) {

--- a/reviews.php
+++ b/reviews.php
@@ -38,6 +38,15 @@
 
 include("includes/pagesetup.php");
 
+function ef_review_story_ok($sid) {
+	$st = dbassoc(dbquery("SELECT uid, validated FROM ".TABLEPREFIX."fanfiction_stories WHERE sid = '".(int)$sid."' LIMIT 1"));
+	if(!$st) return false;
+	if($st['validated'] > 0 || isADMIN) return true;
+	if(!USERUID) return false;
+	if((int)$st['uid'] === (int)USERUID) return true;
+	return (bool)dbrow(dbquery("SELECT uid FROM ".TABLEPREFIX."fanfiction_coauthors WHERE sid = '".(int)$sid."' AND uid = '".(int)USERUID."' LIMIT 1"));
+}
+
 $reviewid = isset($_REQUEST['reviewid']) ? $_REQUEST['reviewid'] : false;
 if(!isNumber($reviewid)) unset($reviewid);
 $type = isset($_REQUEST['type']) ? $_REQUEST['type'] : false;
@@ -59,6 +68,7 @@
 	}
 	$authorquery = dbquery($query2);
 	list($author) = dbrow($authorquery);
+	if(empty($reviewid) || $reviewuid === null) accessDenied( );
 	if($author != USERUID && !$notauthor && ($revdelete < 2 || ($revdelete == 1 && $reviewuid))) accessDenied( );
 	$delete = isset($_GET['delete']) ? $_GET['delete'] : false;
 	$output .= "<div id=\"pagetitle\">"._DELETEREVIEW."</div>";
@@ -124,9 +134,24 @@
 else if($action == "edit" || $action == "add") {
 	if(isset($_GET['next']) && isNumber($_GET['next'])) $nextchapter = $_GET['next'];
 	if(!isMEMBER && !$anonreviews) accessDenied( );
-	if(!isset($chapid) && $type == "ST") { 
-		$chapquery = dbquery("SELECT chapid FROM ".TABLEPREFIX."fanfiction_chapters WHERE sid = '$item' AND inorder = '1' LIMIT 1");
-		list($chapid) = dbrow($chapquery);
+	if($action == "edit") {
+		if(empty($reviewid)) accessDenied( );
+		$ef_r = dbassoc(dbquery("SELECT uid FROM ".TABLEPREFIX."fanfiction_reviews WHERE reviewid = '".(int)$reviewid."' LIMIT 1"));
+		if(!$ef_r || !((isADMIN && uLEVEL < 4) || (USERUID && (int)$ef_r['uid'] === (int)USERUID))) accessDenied( );
+	}
+	if($action == "add") {
+		if(!$reviewsallowed) accessDenied( );
+		if($type == "ST") {
+			if(empty($item) || !ef_review_story_ok($item)) accessDenied( );
+			$ef_ch = isset($_POST['chapid']) && is_string($_POST['chapid']) && isNumber($_POST['chapid']) ? (int)$_POST['chapid'] : (isset($chapid) ? (int)$chapid : 0);
+			$chapid = 0;
+			if($ef_ch) list($chapid) = array_pad((array)dbrow(dbquery("SELECT chapid FROM ".TABLEPREFIX."fanfiction_chapters WHERE chapid = '$ef_ch' AND sid = '".(int)$item."' AND validated > 0 LIMIT 1")), 1, 0);
+			if(!$chapid) list($chapid) = array_pad((array)dbrow(dbquery("SELECT chapid FROM ".TABLEPREFIX."fanfiction_chapters WHERE sid = '".(int)$item."' AND validated > 0 ORDER BY inorder LIMIT 1")), 1, 0);
+			$chapid = (int)$chapid;
+		}
+		else if($type == "SE") {
+			if(empty($item) || !dbrow(dbquery("SELECT seriesid FROM ".TABLEPREFIX."fanfiction_series WHERE seriesid = '".(int)$item."' LIMIT 1"))) accessDenied( );
+		}
 	}
 	$tpl->assign("pagetitle", "<div id =\"pagetitle\">"._REVIEW."</div>");
 	if(isset($_POST['submit'])) {
@@ -289,11 +314,11 @@
 		list($type, $item) = dbrow(dbquery("SELECT type, item FROM ".TABLEPREFIX."fanfiction_reviews WHERE reviewid = '$reviewid' LIMIT 1"));
 	}
 	if($type == "ST") {
-		$storyquery = dbquery("SELECT s.title, s.uid, s.rid, s.sid, s.coauthors FROM ".TABLEPREFIX."fanfiction_stories as s WHERE s.sid = '".(isset($item) ? $item : null)."' LIMIT 1");
+		if(empty($item) || !ef_review_story_ok($item)) accessDenied( );
+		$storyquery = dbquery("SELECT s.title, s.uid, s.rid, s.sid, s.coauthors FROM ".TABLEPREFIX."fanfiction_stories as s WHERE s.sid = '$item' LIMIT 1");
 		$story = dbassoc($storyquery);
 		$title = title_link($story);
-		$authoruid = (isset($story['uid']) ? $story['uid'] : null);
-		if(empty($story)) accessDenied();
+		$authoruid = $story['uid'];
 		if(!empty($story['coauthors'])) {
 			$colist = dbquery("SELECT uid FROM ".TABLEPREFIX."fanfiction_coauthors WHERE sid = '$item'");
 			while($c = dbassoc($colist)) {
@@ -302,17 +327,18 @@
 		}
 	}
 	else if($type == "SE") {
-		$storyquery = dbquery("SELECT title, uid FROM ".TABLEPREFIX."fanfiction_series WHERE seriesid = '".(isset($item) ? $item : null)."' LIMIT 1");
+		$if(empty($item)) accessDenied( );
+		$storyquery = dbquery("SELECT title, uid FROM ".TABLEPREFIX."fanfiction_series WHERE seriesid = '$item' LIMIT 1");
 		list($title, $authoruid) = dbrow($storyquery);
 		$titletext = $title;
-		$title = "<a href=\"series.php?seriesid=".(isset($item) ? $item : null)."\">".stripslashes($title)."</a>";
-		if(empty($title && $authoruid)) accessDenied();
+		$title = "<a href=\"series.php?seriesid='$item'\">".stripslashes($title)."</a>";
 	}
 	else { 
 		$titlequery = dbquery("SELECT * FROM ".TABLEPREFIX."fanfiction_codeblocks WHERE code_type = 'revtitle'");
 		while($code = dbassoc($titlequery)) {
 			eval($code['code_text']);
 		}
+		if(!isset($title)) accessDenied( );
 	}
 	$tpl->assign("pagetitle", "<div id=\"pagetitle\">"._REVIEWSFOR." $title</div>");
 	if($type == "SE") {

--- a/user/editbio.php
+++ b/user/editbio.php
@@ -46,8 +46,13 @@
 	$uid = isset($_REQUEST['uid']) ? $_REQUEST['uid'] : false;
 	if(!$uid) $uid = USERUID;
 
-	if($uid && !isNumber($uid)) accessDenied( );
-	if((!isADMIN || uLEVEL > 2) && $uid != USERUID && $action == "editbio") accessDenied( );
+	if($action == "editbio" && $uid != USERUID && (!isADMIN || uLEVEL > 2)) {
+		$output .= write_error(_NOTAUTHORIZED);
+		$tpl->assign("output", $output);
+		$tpl->printToScreen( );
+		dbclose( );
+		exit( );
+	}
 	if(isMEMBER) $output .= "<div id=\"pagetitle\">"._EDITPERSONAL."</div>";
 	else $output .= "<div id=\"pagetitle\">"._NEWACCOUNT."</div>";