<?php

require_once "/var/www/vhosts/supercheats.com/php/commonfunctions.php";


if ($uid=="testuser") {
#error_reporting(E_ALL);
#ini_set('display_errors', 1);

}

function plural( $amount, $singular = '', $plural = 's' ) {
    if ( $amount == 1 )
        return $singular;
    else
        return $plural;
}

function countdown($cutoff) {



}

function inarticle_textinsert($text,$limit=1500) {
	$l=0;$c=0;
	$blocks=preg_split("/<br \/><br \/>/",$text);
	foreach ($blocks as $block) {
		$l=$l+strlen($block);
		$c++;
		if (($l>$limit) or ($c>=12)) { 
			$newblocks[]='<div class="pw-in-article"><div></div></div>';
			$l=0; $c=0;
		}	
		$newblocks[]=$block;
	}
	$newtext=implode("<br /><br />",$newblocks);

return($newtext);
}

function checkGAPageCount($url) {
	$url=preg_replace("/.+www\.supercheats\.com/","",$url);
	$query="SELECT view_count FROM ga_count_urls WHERE url='".addslashes($url)."'";
        $result = mysql_query($query);
        $row = mysql_fetch_array($result, MYSQL_ASSOC);	
	if ($row["view_count"]>10) { return 0; } else { return 1; }
}

function parseVariable($text,$item,$value) {
	$text = str_replace('{{' . $item . '}}', $value, $text);
	return($text);
}

function submissionLinkText($subtype,$gamevars) {
$cheatchoices=array(
"We have more cheats and tips for this game here, <a href=\"{{CHEAT_URL}}\">{{GAMENAME}} cheats</a>",
"Don't stop here... Check out our complete collection of <a href=\"{{CHEAT_URL}}\">{{GAMENAME}} cheats</a>",
"More tricks, tips and cheats for this game are right here - <a href=\"{{CHEAT_URL}}\">{{GAMENAME}} cheats</a>",
"Head back to our <a href=\"{{CHEAT_URL}}\">{{GAMENAME}} cheats</a> page for a load more cheats and tips for {{GAMENAME}}.",
"More cheats, codes, tips and tricks for {{GAMENAME}} are on <a href=\"{{CHEAT_URL}}\">this page</a> of our website."
);
if ($gamevars["questions"]) {
$cheatchoices[]="If you need more help, we've got more <a href=\"{{CHEAT_URL}}\">{{GAMENAME}} cheats</a> and also check out all of the <a href=\"{{QUESTION_URL}}\">answers</a> for this game";
}
if ($gamevars["guide"]) {
$cheatchoices[]="Boost your gameplay in this game with our <a href=\"{{GUIDE_URL}}\">{{GAMENAME}} walkthrough</a>, more <a href=\"{{CHEAT_URL}}\">cheats and tips</a> and loads of <a href=\"{{QUESTION_URL}}\">answers</a>.";
$cheatchoices[]="More great content for this game is just a click away, we've got a <a href=\"{{GUIDE_URL}}\">{{GAMENAME}} walkthrough</a>, more <a href=\"{{CHEAT_URL}}\">tips and cheats</a> and loads of <a href=\"{{QUESTION_URL}}\">answers</a>.";
$cheatchoices[]="Theres loads more info this game, right here, with some <a href=\"{{CHEAT_URL}}\">cheats and tips</a>, <a href=\"{{QUESTION_URL}}\">answers</a> and <a href=\"{{GUIDE_URL}}\">{{GAMENAME}} walkthrough</a>.";
}
$gscodechoices=array(
"Head back to our index for more <a href=\"{{GSCODES_URL}}\">{{GAMENAME}} GameShark Codes</a> for loads more cheats.",
"We have more codes for this game here, <a href=\"{{GSCODES_URL}}\">{{GAMENAME}} GameShark Codes</a>",
"Head back to our <a href=\"{{GSCODES_URL}}\">{{GAMENAME}} GameShark Codes</a> page for a load more codes and tips for {{GAMENAME}}.",
"More cheats, codes, tips and tricks for {{GAMENAME}} are on <a href=\"{{CHEAT_URL}}\">this page</a> of our website."
);
$arcodechoices=array(
"More codes for this game on our <a href=\"{{ARCODES_URL}}\">{{GAMENAME}} Action Replay Codes</a> index",
"Head back to our <a href=\"{{ARCODES_URL}}\">{{GAMENAME}} Action Replay Codes</a> page for a load more codes and tips for {{GAMENAME}}.",
"Find more codes and cheats for {{GAMENAME}} on <a href=\"{{ARCODES_URL}}\">this page</a> of our website."
);
	if ($subtype=="gamesharkcodes") {
		$text=$gscodechoices[array_rand($gscodechoices)];
	} elseif ($subtype=="Action Replay Codes") {
		$text=$arcodechoices[array_rand($arcodechoices)];
	} else { 
		$text=$cheatchoices[array_rand($cheatchoices)];
	}
	return ($text);
}

function guideParseKeywords($text,$links,$pageurl,$guideurl) {
        $lines=preg_split("/\n/",$text);
        foreach ($lines as $line) {
                if ((preg_match("/\[(pagelist|securl|url|h2|h3|img|video)/i",$line)) or (preg_match("/==/i",$line)) or (preg_match("/http(s|):/i",$line)))  {
                        $newlines[]=$line;
                } else {
                        $found=1;
                        $testlinks=$links;$newline="";
                        while ($found) {
                                $posarray=array();
                                foreach ($testlinks as $i=>$varray) {
                                        if ($varray["url"]!=$pageurl) {
                                                if (preg_match("~\b$i\b~i",$line, $matches, PREG_OFFSET_CAPTURE)) {
                                                        $posarray[$matches[0][1]]=$i;
                                                }
                                        }
                                }
                                if (count($posarray)) {
                                        ksort($posarray);
                                        $pos=key($posarray);
                                        $replace=array_shift($posarray);
                                        $d=preg_split("/$replace\b/i",$line,2);
                                        $newline.=$d[0].'[url=https://www.supercheats.com/'.$guideurl.'/walkthrough/'.$links[$replace]["url"].'][u]'.$links[$replace]["replace"].'[/u][/url]';
                                        $line=$d[1]; unset($testlinks[$replace]);
                                } else { $found=0; $newline.=$line; }
                        }
                        $newlines[]=$newline;
                }
        }
        $newtext=implode("\n",$newlines);
        return($newtext);
}

function getGuideLinks($lchyphname) {
        $query="SELECT id,title,baseurl FROM guides WHERE lchyphname='".$lchyphname."'";
        $result = mysql_query($query);
        $guide = mysql_fetch_array($result, MYSQL_ASSOC);
        $query="SELECT id,title,h1title,lchyphtitle,subdate,updatetime,status,keywords FROM guides_pages WHERE guideid='".$guide["id"]."' ORDER BY id DESC";
        $result = mysql_query($query) or die(mysql_error());
        while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
                $pages[]=$row;
        }
        if ($pages) {
        foreach ($pages as $p) {
                        if ($p["status"]=="ACTIVE") {
				$keywordlinks[strtolower($p["title"])]=array("replace"=>$p["title"],"url"=>$p["lchyphtitle"]);
				if (($p["h1title"]) and ($p["h1title"] != $p["title"])) {
                                $keywordlinks[strtolower($p["h1title"])]=array("replace"=>$p["h1title"],"url"=>$p["lchyphtitle"]);
				}
                        }
        }
        foreach ($pages as $p) {
                        if ($p["status"]=="ACTIVE") {
                                $ks=preg_split("/,/",$p["keywords"]);
                                if ($ks) {
                                        foreach ($ks as $k) {
                                                $k=trim($k);
                                                $t=strtolower($k);
                                                if (($k) and (! $keywordlinks[$t])) { $keywordlinks[$t]=array("replace"=>$k,"url"=>$p["lchyphtitle"]); }
                                        }
                                }
                        }
        }
        $guide["keywordlinks"]=$keywordlinks;
        }
        return($guide);
}

function getguidedetails($gamerow,$name) {

## check guide
#if (preg_match("/guides\//",$gamerow["guide"])) {
#        $query="SELECT * FROM guide_associations WHERE LOCATE(association,'".addslashes($name)."') >0 ORDER BY LENGTH(association) DESC LIMIT 1";
#        $result = mysql_query($query) or die(mysql_error());
#        if (mysql_num_rows($result)) {
#                $guiderow= mysql_fetch_array($result, MYSQL_ASSOC);
#        }
#} else {
        connect(supercheats_walkthrough);
        $query="SELECT id,title,description as details, image as thumburl, baseurl,lchyphname FROM guides WHERE gamename='".addslashes($name)."'";
        $result = mysql_query($query) or die(mysql_error());
        if (mysql_num_rows($result)) {
                $guiderow= mysql_fetch_array($result, MYSQL_ASSOC);
                if (preg_match("/http(s|):/",$pagevars["guiderow"]["baseurl"])) {
                $guiderow["guideurl"]=$pagevars["guiderow"]["baseurl"];
                } else {
                $guiderow["guideurl"]="/".$guiderow["baseurl"]."/walkthrough/";
                }
        }
        connect(supercheats);
	if (! $guiderow) {
		$query="SELECT * FROM guide_associations WHERE LOCATE(association,'".addslashes($name)."') >0 ORDER BY LENGTH(association) DESC LIMIT 1";
        	$result = mysql_query($query) or die(mysql_error());
        	if (mysql_num_rows($result)) {
                	$guiderow= mysql_fetch_array($result, MYSQL_ASSOC);
        	}
	}
#}
	return($guiderow);
}

function keywordparse($text) {
        $query="SELECT * FROM keyword_links ORDER BY length(keyword) DESC";
                $result = mysql_query($query);
                while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
                        if ($row["keyword"]) {
                        $links[$row["keyword"]]=$row["url"];
                        }
                }
	$text=parseforkeywords($text,$links);
	return($text);
}

function parseforkeywords($text,$links) {
        $lines=preg_split("/\n/",$text);
        foreach ($lines as $line) {
                if (preg_match("/\[(url|h2|h3|img)/i",$line)) {
                        $newlines[]=$line;
                } else {
			$found=1;
			$testlinks=$links;$newline="";
			while ($found) {
				$posarray=array();
                        	foreach ($testlinks as $i=>$v) {
					$pos=stripos($line,$i);
					if ($pos===false) {} else { $posarray[$pos]=$i; }
				}
				if (count($posarray)) {
					ksort($posarray);
					$replace=array_shift($posarray);
					if (preg_match("/\b$replace\b/i",$line)) {
					$d=preg_split("/\b$replace\b/i",$line,2);
					$newline.=$d[0].'<a href="'.$links[$replace].'" target="_blank" class="keywordlink">'.$replace.'</a>';
					$line=$d[1]; unset($testlinks[$replace]);
					} else { $found=0; $newline.=$line; }
				} else { $found=0; $newline.=$line; }
			}
                        $newlines[]=$newline;
                }
        }
        $newtext=implode("\n",$newlines);
        return($newtext);
}


function geturl($gamename,$platform,$subtype,$platforms) {
	$lcsubtype=sc($subtype);
	if ($lcsubtype=="hintsandtips") { $lcsubtype="hints"; $subtype="Hints";  } 
	$lcplatform=sc($platform);
	if ($lcsubtype=="screenshots") {
		$url='https://www.supercheats.com/'.lchyph($gamename).'/screenshots';
	} elseif ($lcsubtype=="videos") {
		$url='https://www.supercheats.com/'.lchyph($gamename).'/videos/';
	} elseif ($platforms[sc($platform)]["pageformat"]=="new") {
		$url='https://www.supercheats.com/'.$lcplatform."/".lchyph($gamename)."/";
		if (($lcsubtype=="questions") or ($lcsubtype=="answers") or ($lcsubtype=="questionsanswers")) {
			$url.='questions-answers.php';
		} elseif ($lcsubtype=="index") { 
		} else { 
			$url.=$lcsubtype.'.htm';
		}
	} else {
		$url='https://www.supercheats.com/'.$lcplatform."/".sc($gamename);
		if (($lcsubtype=="questions") or ($lcsubtype=="answers") or ($lcsubtype=="questionsanswers")) {
                        $url.='questions.php';
		} elseif ($lcsubtype=="index") { 
			$url.='.htm';
                } else {
                        $url.=$lcsubtype.'.htm';
                }
	}	

	return($url);
}

function game_optional_videos($name,$type,$t) {
        $filename='/var/www/vhosts/supercheats.com/php/intergi/games/videos/'.sc($name).'.'.sc($type);
        if (file_exists($filename)) {
                $videodata=preg_split("/\n/",file_get_contents($filename));
        }
        if ($videodata) {
        list($videoid,$t)=preg_split("/::/",trim($videodata[0]));

        $text='
        <div class="optional_video">
        <div class="header hand" onclick="jQuery(\'#'.sc($name).'_'.$type.'_video\').slideDown();Bolt.renderPlayer(\'myPlayer\');">'.$t.'</div>
        <div class="video" id="'.sc($name).'_'.$type.'_video" style="display:none;">
        <script type="text/javascript" charset="utf-8" src="//cdn.playwire.com/bolt/js/zeus/embed.js" data-autoload="false" data-container="myPlayer" data-width="640" data-height="360" data-config="//config.playwire.com/11665/videos/v2/'.$videoid.'/zeus.json"></script>
        </div>
        </div>
        <div class="cboth">&nbsp;</div>
        ';
        return($text);
        }
}

function game_specific_videos($name,$type,$id="") {
	## on hold
	#$text="";
	#return($text);

	$filename='/var/www/vhosts/supercheats.com/php/intergi/games/videos/'.sc($name).'.'.sc($type);
        $allpagesfilename='/var/www/vhosts/supercheats.com/php/intergi/games/videos/'.sc($name).'.allpages';
        $alltypesfilename='/var/www/vhosts/supercheats.com/php/intergi/games/videos/allgames.'.sc($type);
        $allsubsfilename='/var/www/vhosts/supercheats.com/php/intergi/games/videos/allsubs.'.sc($type);
        if (file_exists($filename)) {
                $videodata=preg_split("/\n/",file_get_contents($filename));
                $cookie=sc($name).'_'.sc($type).'_done';
        } elseif (file_exists($allpagesfilename)) {
                $videodata=preg_split("/\n/",file_get_contents($allpagesfilename));
                $cookie=sc($name).'_all_done';
        } elseif (file_exists($alltypesfilename)) {
                $videodata=preg_split("/\n/",file_get_contents($alltypesfilename));
                $cookie='generic_done';
                $timeout=time()+(86400*14);
        } elseif ((file_exists($allsubsfilename)) and ($id)) {
                $videodata=preg_split("/\n/",file_get_contents($allsubsfilename));
                $cookie='generic_done';
                $timeout=time()+(86400*14);
        }
	if (! $_COOKIE[$cookie]) {
        	if ($videodata) {
        		$videoid=trim($videodata[0]);	
			if ($videodata[1]=="replay"){
                		$text='<div>'.$videodata[2].'<span class="fright">Replay</span></div><div style="display:none;">';
        		}
			$text.="<script>document.write('<div class=\"playwire_vid\"><scr'+'ipt data-config=\"https://config.playwire.com/11665/videos/v2/".$videoid."/zeus.json\" data-width=\"100%\" src=\"//cdn.playwire.com/bolt/js/zeus/embed.js\" data-autoplay=\"true\" type=\"text/javascript\"></scr'+'ipt></div>');</script>";
		}
		if ($videodata[1]=="replay"){
                	$text.='</div>';
        	}
	#	setcookie($cookie,"played",$timeout,"/",".supercheats.com");
		$text.='<script type="text/javascript">document.cookie="'.$cookie.'=played; ';
        	if ($timeout) {
                	$text.='expires='.date("D, M j Y G:i:s T",$timeout).';';
        	}
        	$text.='path=/";</script>';
	}
	return($text);
}
function game_specific_videos_old($name,$type,$id="") {
        $filename='/var/www/vhosts/supercheats.com/php/intergi/games/videos/'.sc($name).'.'.sc($type);
        $allpagesfilename='/var/www/vhosts/supercheats.com/php/intergi/games/videos/'.sc($name).'.allpages';
        $alltypesfilename='/var/www/vhosts/supercheats.com/php/intergi/games/videos/allgames.'.sc($type);
        $allsubsfilename='/var/www/vhosts/supercheats.com/php/intergi/games/videos/allsubs.'.sc($type);
        if (file_exists($filename)) {
                $videodata=preg_split("/\n/",file_get_contents($filename));
                $cookie=sc($name).'_'.sc($type).'_done';
        } elseif (file_exists($allpagesfilename)) {
                $videodata=preg_split("/\n/",file_get_contents($allpagesfilename));
                $cookie=sc($name).'_all_done';
        } elseif (file_exists($alltypesfilename)) {
                $videodata=preg_split("/\n/",file_get_contents($alltypesfilename));
                $cookie='generic_done';
                $timeout=time()+(86400*14);
        } elseif ((file_exists($allsubsfilename)) and ($id)) {
                $videodata=preg_split("/\n/",file_get_contents($allsubsfilename));
                $cookie='generic_done';
                $timeout=time()+(86400*14);
        }
        if ($videodata) {
        $videoid=trim($videodata[0]);

        $text='
        <script type="text/javascript">
        if (getCookie("'.$cookie.'")) {
        ';
        if ($videodata[1]=="replay"){
                $text.='document.write(\'<div>'.$videodata[2].'<span class="fright">Replay</span></div><div style="display:none;">\');';
        }
        $text.='
        } else {
document.write(\'<scr\'+\'ipt data-config="//config.playwire.com/11665/videos/v2/'.$videoid.'/zeus.json" data-css="//cdn.playwire.com/bolt/js/zeus/skins/default.css" data-height="100%" data-width="100%" data-id="'.sc($name).'_'.sc($type).'" src="//cdn.playwire.com/bolt/js/zeus/embed.js" type="text/javascript"></scr\'+\'ipt><div class="cboth">&nbsp;</div>\');
        ';
        if ($videodata[1]=="replay"){
                $text.='document.write(\'</div>\');';
        }
        $text.='
        document.cookie="'.$cookie.'=played; ';
        if ($timeout) {
                $text.='expires='.date("D, M j Y G:i:s T",$timeout).';';
        }
        $text.='path=/";
        }
        </script>
        ';
        $text.='
                <script>
                jQuery(document).ready(function() {
                Bolt.playMedia("'.sc($name).'_'.sc($type).'");
                });
                </script>
        ';
$text1="<div id=\"boltPlayerHolder\"></div>
<script>
if(!getCookie('".$cookie."')){

        try{
                _boltscript = document.createElement('script');
                _boltscript.src = '//cdn.playwire.com/bolt/js/zeus/embed.js';
                _boltscript.type = 'text/javascript';
                _boltscript.id = 'boltscript';
                _boltscript.setAttribute('data-config', '//config.playwire.com/11665/videos/v2/".$videoid."/zeus.json');
                _boltscript.setAttribute('data-css', 'https://cdn.playwire.com/bolt/js/zeus/skins/default.css');
                _boltscript.setAttribute('data-width', '100%');
                _boltscript.setAttribute('data-height', '100%');
                _boltscript.setAttribute('data-id', '".sc($name)."_".sc($type)."');
                _boltscript.setAttribute('data-onready', '_renderBolt');
                document.getElementById('boltPlayerHolder').appendChild(_boltscript);
                _renderBolt = function(player){ document.cookie=\"".$cookie."=played; ";
if ($timeout) {
                $text1.='expires='.date("D, M j Y G:i:s T",$timeout).';';
        }
$text1.="path=/\"; "; 
$text1.="Bolt.playMedia(player); ";  ## Set To Auto Play Videos on desktop.
$text1.="}
        }catch(e){
                console.error('Error loading Bolt:', e);
        }

};
</script>
";

        return($text1);
        }
}

function oldgame_specific_videos($name,$type) {
        $filename='/var/www/vhosts/supercheats.com/php/intergi/games/videos/'.sc($name).'.'.sc($type);
        $allpagesfilename='/var/www/vhosts/supercheats.com/php/intergi/games/videos/'.sc($name).'.allpages';
        if (file_exists($filename)) {
        $videodata=preg_split("/\n/",file_get_contents($filename));
        $cookie=sc($name).'_'.sc($type).'_done';
        } elseif (file_exists($allpagesfilename)) {
        $videodata=preg_split("/\n/",file_get_contents($allpagesfilename));
        $cookie=sc($name).'_all_done';
        }
        if ($videodata) {
        $videoid=trim($videodata[0]);

        $text='
        <script type="text/javascript">
        if (getCookie("'.$cookie.'")) {
        ';
        if ($videodata[1]=="replay"){
                $text.='document.write(\'<div>'.$videodata[2].'<span class="fright">Replay</span></div><div style="display:none;">\');';
        }
        $text.='
        } else {
document.write(\'<scr\'+\'ipt data-config="//config.playwire.com/11665/videos/v2/'.$videoid.'/zeus.json" data-css="//cdn.playwire.com/bolt/js/zeus/skins/default.css" data-height="100%" data-width="100%" data-id="'.sc($name).'_'.sc($type).'" src="//cdn.playwire.com/bolt/js/zeus/embed.js" type="text/javascript"></scr\'+\'ipt><div class="cboth">&nbsp;</div>\');
        ';
        if ($videodata[1]=="replay"){
                $text.='document.write(\'</div>\');';
        }
        $text.='
        document.cookie="'.$cookie.'=played; path=/";
        }
        </script>
        ';
        $text.='
                <script>
                jQuery(document).ready(function() {
                Bolt.playMedia("'.sc($name).'_'.sc($type).'");
                });
                </script>
        ';
        return($text);
        }
}

function listcomments($comments,$replyto,$indent,$start,$max,$level,$uid="") {
        $text='<div style="margin-left:'.$indent.'px">';
        $showcomments=array_slice($comments[$replyto],$start,$max);
        foreach ($showcomments as $row) {
                if ($row["abusecount"]>=3) { $row["comment"]="[i]This comment has been referred for moderation[/i]"; }
                $text.='
                <div class="" id="commentid'.$row["id"].'">
                <div class="comments" style="position:relative;" >
		<span class="fright smalltext">'.date("M jS Y",$row["timestamp"]).'</span><b>
		';
                if ($row["submittedby"]) {
                        if (! $userdetails[$row["submittedby"]]) {
                        $userdetails[$row["submittedby"]]=getuseravatar($row["submittedby"]);
                        }
                        #$text.='
                        #<div class="userinfoBox" id="userBox'.$row["id"].'" style="display:none;"></div>
                        #<a class="hand" onclick="showUserBox(\''.$row["submittedby"].'\',\''.$row["id"].'\',\'2\');"><img src="'.$userdetails[$row["submittedby"]]["avatar"].'" class="comments_img" align="left" alt="'.$row["submittedby"].' Avatar" /></a>
                       #<a class="hand" onclick="showUserBox(\''.$row["submittedby"].'\',\''.$row["id"].'\',\'2\');">'.$row["submittedby"].'</a><br />';
			$text.='<a>'.$row["submittedby"].'</a><br />';
                } else {
                        #$text.='
                        #<img src="https://www.supercheats.com/images/guestavatar.png" class="comments_img" align="left" alt="Guest Avatar" />Guest</a><br />';
			$text.='Guest<br />';
                }

                $text.='</b>	
		'.bbcparse($row["comment"]).'<span class="speech"></span></div>
                <div class="comment_foot">
                <div class="fright"><span id="comment'.$row["id"].'">';
                #if (in_array($uid,$commentadmins)) {
                #$text.='<a onclick="admindeletecomment(\''.$row["id"].'\');" id="admindeletecomment'.$row["comment"].'" class="hand">ADMIN DELETE</a> | ';
                #}
                if (($level<=5) and ($uid)) {
                $text.='
                <a class="hand" onclick="document.getElementById(\'replyto\').value=\''.$row["id"].'\';jQuery(\'#commentRespond\').hide().detach().insertAfter(jQuery(\'#commentid'.$row["id"].'\')).slideDown();" title="Reply to this comment">REPLY</a> |
                ';
                }
                $text.='
                <a href="#reportcomment" rel="modal:open" onclick="document.getElementById(\'commentid\').value=\''.$row["id"].'\';">REPORT</a>
                </span>
                </div>
                <div>
                ';
                $text.='
                        ID #'.$row["id"];
                        $text.='
                        ';
                $text.='
                </div>
                </div>
                </div>
                <div class="cboth">&nbsp;</div>
                ';
	if ($comments[$row["id"]]) {
                        $text.=listcomments($comments,$row["id"],"30",0,10,($level+1),$uid);
                }
        }
        $text.='</div>';
	return($text);
}

function mainfuzzysearch($text) {
        $atext=strtolower(preg_replace("/ +/","",$text));
        $stext=preg_replace("/[^a-z0-9]+/","",strtolower($text));
        $terms=array(
'paycheck',
'dollar',
'resources',
'simoleons',
'diamonds',
'coins',
'longtime',
'http',
'tinyurl',
'download',
'unlimited',
'tool',
'hack',
'remove',
'between',
'delete',
'space',
'link',
'gold',
'gems',
'elixir',
'free',
'spell',
'wife',
'husband',
'password',
'scam',
'make',
'money',
'bank',
'fox81',
'fox81',
'hackscommunity',
'hackscomm',
'customercare',
'supportservice',
'1833',
'online'
);
        if (preg_match("/\.[a-z]{2,3}\//",$atext)) { $score=$score+2; }
        foreach ($terms as $word) {
                if (strpos($stext,$word)!==false) { $score++; }
        }
	if ($score>=3) { return(1); } else { return(0); }

}

function bbcodebuttons($textfield,$type="media") {

        if (! $textfield) { $textfield="commentform.comment"; }
        $text='
                <button type="button" class="bb" onclick="javascript:add(\''.$textfield.'\',\'[b]\',\'[/b] \');"><b>B</b></button>

                <button type="button" class="bb" onclick="javascript:add(\''.$textfield.'\',\'[i]\',\'[/i] \');"><em>i</em></button>
                <button type="button" class="bb" onclick="javascript:add(\''.$textfield.'\',\'[u]\',\'[/u] \');">u</button>
                <button type="button" class="bb" onclick="javascript:add(\''.$textfield.'\',\'[size=12]\',\'[/size] \');">Font Size</button>
                <button type="button" class="bb" onclick="javascript:add(\''.$textfield.'\',\'[color=red]\',\'[/color] \');">Font color</button>
                <button type="button" class="bb" onclick="javascript:add(\''.$textfield.'\',\'[strike]\',\'[/strike] \');">Strikeout</button>
                <button type="button" class="bb" onclick="javascript:add(\''.$textfield.'\',\'[spoiler]\',\'[/spoiler] \');">Spoiler</button>

                <button type="button" class="bb" onclick="javascript:add(\''.$textfield.'\',\'[quote]\',\'[/quote] \');">Quote</button>
                <button type="button" class="bb" onclick="javascript:add(\''.$textfield.'\',\'[center]\',\'[/center] \');">Align</button>
                <button type="button" class="bb" onclick="javascript:add(\''.$textfield.'\',\'[url]\',\'[/url] \');">Link</button>
                <button type="button" class="bb" onclick="javascript:add(\''.$textfield.'\',\'[list]\n[*] \',\'\n[/list] \');">List</button>
	';
	if ($type=="media") {
		$text.='
                <button type="button" class="bb" onclick="javascript:add(\''.$textfield.'\',\'[img]\',\'[/img] \');">Add Pic</button>
                <button type="button" class="bb" onclick="javascript:add(\''.$textfield.'\',\'[video]\',\'[/video] \');" title="Enter the url for a SuperCheats or YouTube video page">Add Video</button>
		';
	}
	$text.='
		<br /><a href="/calls/bbcodeguide.htm" rel="modal:open">BB Codes Guide</a>
<style>.bb {
    font-size: 12px;
    padding: 1px 5px;
    border: 1px solid #167ac6;
    background-color: #63a7da;
    margin: 3px 0;
    border-radius: 3px;
}
</style>
';
        return($text);
}

function testshowguidecomments($set,$subid,$p=1,$uid="") {
        $text='
        <a name="comments"></a>
        <div id="comment_area">
        ';
        $commentplatform=$platform;
include $pathadjust."js-includes/jquery.maxlength.js";
        $text.='
        <h4>Comments for this ';
        if ($subtype=="hints and tips") { echo 'hint'; } else {
        echo preg_replace("/s$/","",$subtype);
        }
        echo '.</h4>';
?>
        <div id="commentbox">
<?php
        require $pathadjust."includes/commentbox.new2.php";
       	$text.='</div>';
        $text.='
        <div class="cboth">&nbsp;</div>
        <div id="comments">
        Load Comments';
        $text.='</div></div>';
        $text.='<script>
document.addEventListener("DOMContentLoaded", function() {
  const itemsLoad = function() {
                var blockid=document.getElementById("comment_area");
          if ((blockid.getBoundingClientRect().top <= window.innerHeight && blockid.getBoundingClientRect().bottom >= 0)) {
            document.removeEventListener("scroll", itemsLoad);
                showguidecomments(\'comments\',\''.$subid.'\',\''.$commentplatform.'\',\'1\');
          }
  };
  document.addEventListener("scroll", itemsLoad);
});
</script>';
	return($text);
}
function showguidecomments($set,$subid,$p=1,$uid="") {
	$max=30;
	$start=($p-1)*$max;
	if (is_numeric($subid)) {
		if ($set=="Video") {
			$reporttype="video";
			$query="SELECT * FROM videos_comments WHERE videoid='".$subid."' ORDER BY id DESC";
		} else {
			$query="SELECT id,replyto,submittedby,comment,timestamp,abusecount FROM submission_comments WHERE platform='".addslashes($set)."' and subid='".$subid."' ORDER BY id DESC";
		}
		$result = mysql_query($query);
		$totalcomments=mysql_num_rows($result);
		while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
        		$comments[$row["replyto"]][]=$row;
		}
		if (isset($_COOKIE['nscLogin'])) {
       				list($uid,$sid,$remember,$rank,$subs,$avatar,$ranking,$collection,$currentplay,$wish,$watchlist,$scuserid)=preg_split("/::/",$_COOKIE["nscLogin"]);
		}

		if ($comments) {
			$pages=ceil($totalcomments/$max);
			if ($p>$pages)  { $p=$pages; }
			$text.=$totalcomments.' comments, latest first. ';
			if ($pages>1) {
        			$text.='<div class="pageing">
				<div class="fleft" style="height:1.5em;"><span class="blob">Page '.$p.' of '.$pages.'</span></div>
				<div class="fleft" style="height:1.5em;">';
        			$page=1;
        			$s=$p - 3; if ($s < 0) { $s=0; }
        			$e=$s+6;
        			if ($p>3) { ## first
                			$text.='<a class="hand blob" onclick="showguidecomments(\'comments\',\''.$subid.'\',\''.$set.'\',\'1\');"><<</a>';
        			}
        			while ($page<=$pages) {
                			if (($page  > $s) and ($page<=$e)) {
                				if ($p==$page) {
                        				$text.='<span class="blob" style="color:#000;">'.$page .'</span>';
                				} else {
                        				$text.='<a class="hand blob" onclick="showguidecomments(\'comments\',\''.$subid.'\',\''.$set.'\',\''.$page.'\');">'.$page.'</a>';
                				}
                			}
                			$page++;
        			}
        			if ($p<($pages-3)) { ## last
                			$text.='<span>&nbsp;</span><a class="hand blob" onclick="showguidecomments(\'comments\',\''.$subid.'\',\''.$set.'\',\''.$pages.'\');">>></a>';
        			}

			$text.='</div></div>';
			$text.='<div class="cboth">&nbsp;</div>';
			}

        $text.='
        <div style="display:none; color:#000;" id="reportcomment" class="lightview-pop">
        <div class="lightview-pop-inner">
        <input type="hidden" name="commentid" id="commentid" />
        <i>This is to report a problem with the comment to the staff for moderation. It <b>does not</b> reply to the comment.<br />
        </i><br /><br />

        Why are you reporting this comment? <br />
        <input type="text" maxlength="140" name="reportreason" id="reportreason" size="50" /> <input type="button" name="report" class="sc-button" value="Report" onclick="reportcomment(document.getElementById(\'commentid\').value,document.getElementById(\'reportreason\').value,\''.$reporttype.'\');" />
        </div>
        </div>

<div class="replyCommentBox cboth" id="commentRespond" style="display:none;">
        <div id="replyresult"></div>
        <b>Reply to this comment</b>
        <form name="replyForm" action="" method="post">
        <input type="hidden" name="replyto" id="replyto" value="" />
        <div style="position:relative;width:100%;">
        <textarea name="commentReply" id="commentReply" cols="55" rows="4"></textarea>
        </div>
        <div class="smalltext">
        <b>Please do not be rude, what may be obvious to you may not be to others.</b></div>
	';
	$textfield="replyForm.commentReply";
	$text.=bbcodebuttons($textfield);
	$text.='
         <div id="replysubmit">
<input type="button" class="sc-button fright" value="Close" onclick="jQuery(\'#commentRespond\').slideUp(\'slow\');" />
	';
	if ($commentplatform=="Video") {
	$text.='
<input name="send" type="button" value="Add Reply" class="sc-button" onclick=\'addvideoreply("commentsubmit","'.$videoid.'",this.form.commentReply.value,"'.urlencode($_SERVER["HTTP_REFERER"]).'");return false;\' />
';
	} else {
$text.='
<input name="send" value="Add Reply" type="button" class="sc-button" onclick=\'addnewreply("'.$set.'","'.$subid.'",this.form.commentReply.value); return false;\' />
';
	}
	$text.='
        </div>
        </form>
        <script type="text/javascript">
                $(\'textarea.limited\').maxlength({
                \'feedback\' : \'.charsLeft\',
                \'useInput\' : true
                });
        </script>
	</div>
<style>
#commentbox {
    font-size: .9em;
}
.addCommentBox {
    margin: 8px 0;
    background-color: #f0f6fb;
    padding: 6px;
    border: 1px solid #a1c4de;
}
.addCommentBox #comment {
    font-size: 12px;
    border-radius: 3px;
    box-sizing: border-box;
    width: 100%;
    padding: 4px;
}
#comment_area .comments {
    color: #333;
    position: relative;
    height: auto;
    padding: 5px;
    background-color: #dadada;
    border-radius: 3px;
    border: 4px solid #ccc;
}
#comments .comment_foot {
    font-size: .9em;
    font-weight: 700;
    color: #666;
}
        </style>
        ';
        $replyto="0";
        $text.= listcomments($comments,$replyto,"0",$start,$max,1,$uid);
} else {
$text.='<div class="tcenter"><i>No comments yet. Tell us what you think to be the first.</i></div>';
}
}
return($text);
}

function commentbox($type,$subid,$uid="") {
	$text='
        <div class="addCommentBox">
	<h4>Add a comment</h4>
	';
	if ($uid) {
	$text.='
                <div id="commentresult"></div>
                Please do not be rude, what may be obvious to you may not be to others.<br />
                <form name="commentForm" action="post">
                        <p class="small">Characters left: <span class="charsLeft">1000</span></p>
        <div style="position:relative;width:100%;">
                        <textarea name="comment" id="comment" cols="55" rows="8" class="limited"></textarea>
        </div>
	';
	$textfield="commentForm.comment";
	$text.=bbcodebuttons($textfield);
	$text.='
                        <input type="hidden" name="maxlength" value="1000" />
                        <div id=commentsubmit>
	';
if ($type=="Video") {
	$text.='
<input name="addc" type="button" class="sc-button" value="Add Comment" onclick=\'addvideocomment("commentsubmit","'.$subid.'",this.form.comment.value,"'.urlencode($_SERVER["REQUEST_URI"]).'");return false;\' />
';
} else {
	$text.='
<input name="addc" type="button" class="sc-button" value="Add Comment" onclick=\'addnewcomment("commentsubmit","'.$type.'","'.$subid.'",this.form.comment.value); return false;\' />
	';
}
	$text.='
	</div>
                </form>
                <script type="text/javascript">
                jQuery(\'textarea.limited\').maxlength({
                \'feedback\' : \'.charsLeft\',
                \'useInput\' : true
                });
                </script>
	';
	} else {
		$text.='Please log in above or sign up for free to post comments';
	}
	$text.='
        </div>
        <div class="cboth">&nbsp;</div>
	';
	return($text);
}

function lengthsort($a,$b){
    return strlen($b)-strlen($a);
}

function ituneslink($url) {

$text='
<div style="text-align:center; width:100%;">
<a href="'.$url.'&at=10lGxL" target="itunes_store" style="display:inline-block;overflow:hidden;background:url(https://linkmaker.itunes.apple.com/htmlResources/assets/en_us//images/web/linkmaker/badge_appstore-lrg.png) no-repeat;width:135px;height:40px;@media only screen{background-image:url(https://linkmaker.itunes.apple.com/htmlResources/assets/en_us//images/web/linkmaker/badge_appstore-lrg.svg);}"></a>
';
$text.='</div>';
return ($text);
}

function getRudeWords() {

$pquery="SELECT word FROM rudewords";
$pstuff = mysql_query($pquery);
while ($prow = mysql_fetch_array($pstuff, MYSQL_ASSOC)) {
        $rudewords[]=preg_replace("/\'/","",$prow["word"]);
}
return($rudewords);
}
function sendanyemail($uid,$semail,$subject,$text) {
	$text.=file_get_contents("/var/www/vhosts/supercheats.com/php/emailfooter.txt");
        if ($uid) {
        	$query="SELECT email FROM users WHERE screenname='".addslashes($uid)."'";
        	$stuff = mysql_query($query) or die(mysql_error());
        	$row = mysql_fetch_array($stuff, MYSQL_ASSOC);
        	$email=$row["email"];
	} elseif($semail) {
		$email=$semail;
	}
        if ($email) {
		 $headers = 'From: SuperCheats <webmaster@supercheats.com>' . "\r\n" .
    		'Reply-To: webmaster@supercheats.com' . "\r\n" .
    		'X-Mailer: PHP/' . phpversion();
                mail($email,$subject, $text,$headers,"-f webmaster@supercheats.com");
        }
}

function bannedwords($text) {

$bannedwords=array('hack','hacks','h@ack','hackz','warez','minecraftnow.us');
        $wordfound=0;
        foreach ($bannedwords as $word) {
                if (preg_match("/\b".$word."\b/i",$text)) { $wordsfound[]=$word; }
        }
	if ($wordsfound) { $wordfound=implode(" - ",$wordsfound); }
        return ($wordfound);
}


function long_url($url) {
  $longURL = get_headers($url, 7);
  return $longURL['Location'];
}

function expandshorturl($text) {
        $words=preg_split("/( |\/)+/",$text);
        foreach ($words as $word) {
                if (preg_match("/(goo\.gl|bit\.ly)/i",$word)) {
			$realurl=long_url($url);
			preg_replace($word,$realurl,$text);
                }
	}
	return ($text);
}

function checkforlink($text,$any="") {
$oklinks=array('supercheats.com','codejunkies.com','youtu.be','youtube.com','serebii.net',
'appgamer.com',
'teamphotoshop.com',
'juegoz.com',
'fogu.com',
'gamefaqs.com',
'apointlessplace.com',
'imgur.com',
'photobucket.com',
'pokemon.com',
'Amazon.co.uk',
'Amazon.com',
'ebay.com',
'wikipedia.org',
'gamestop.com',
'gameshark.com',
'facebook.com',
'deviantart.com',
'runescape.com',
'smashbros.com',
'nintendo.com',
'modthesims.com',
'google.com',
'rockstargames.com',
'argos.co.uk',
'worldofwarcraft.com',
'roblox.com',
'ea.com',
'imageshack.us',
'bit.ly',
'bungie.com',
'ask.com',
'yahoo.com',
'wikipedia.com',
'easports.com',
'battlefield.com',
'apple.com',
'tinypic.com',
'activision.com',
'origin.com',
'lifeinvader.com',
'dictionary.com',
'help.firemonkeys.com.au',
'caws.ws'
);
$tlds=array('.ac','.ad','.ae','.aero','.af','.ag','.ai','.al','.am','.an','.ao','.aq','.ar','.arpa','.as','.asia','.at','.au','.aw','.ax','.az','.ba','.bb','.bd','.be','.bf','.bg','.bh','.bi','.biz','.bj','.bm','.bn','.bo','.br','.bs','.bt','.bv','.bw','.by','.bz','.ca','.cat','.cc','.cd','.cf','.cg','.ch','.ci','.ck','.cl','.cm','.cn','.co','.com','.coop','.cr','.cu','.cv','.cw','.cx','.cy','.cz','.de','.dj','.dk','.dm','.do','.dz','.ec','.edu','.ee','.eg','.er','.es','.et','.eu','.fi','.fj','.fk','.fm','.fo','.fr','.ga','.gb','.gd','.ge','.gf','.gg','.gh','.gi','.gl','.gm','.gn','.gov','.gp','.gq','.gr','.gs','.gt','.gu','.gw','.gy','.hk','.hm','.hn','.hr','.ht','.hu','.id','.ie','.il','.im','.in','.info','.int','.io','.iq','.ir','.is','.it','.je','.jm','.jo','.jobs','.jp','.ke','.kg','.kh','.ki','.km','.kn','.kp','.kr','.kw','.ky','.kz','.la','.lb','.lc','.li','.lk','.lr','.ls','.lt','.lu','.lv','.ly','.ma','.mc','.md','.me','.mg','.mh','.mil','.mk','.ml','.mm','.mn','.mo','.mobi','.mp','.mq','.mr','.ms','.mt','.mu','.museum','.mv','.mw','.mx','.my','.mz','.na','.name','.nc','.ne','.net','.nf','.ng','.ni','.nl','.no','.np','.nr','.nu','.nz','.om','.org','.pa','.pe','.pf','.pg','.ph','.pk','.pl','.pm','.pn','.post','.pr','.pro','.ps','.pt','.pw','.py','.qa','.re','.ro','.rs','.ru','.rw','.sa','.sb','.sc','.sd','.se','.sg','.sh','.si','.sj','.sk','.sl','.sm','.sn','.so','.sr','.st','.su','.sv','.sx','.sy','.sz','.tc','.td','.tel','.tf','.tg','.th','.tj','.tk','.tl','.tm','.tn','.to','.tp','.tr','.travel','.tt','.tv','.tw','.tz','.ua','.ug','.uk','.us','.uy','.uz','.va','.vc','.ve','.vg','.vi','.vn','.vu','.wf','.ws','.xn--0zwm56d','.xn--11b5bs3a9aj6g','.xn--3e0b707e','.xn--45brj9c','.xn--80akhbyknj4f','.xn--80ao21a','.xn--90a3ac','.xn--9t4b11yi5a','.xn--clchc0ea0b2g2a9gcd','.xn--deba0ad','.xn--fiqs8s','.xn--fiqz9s','.xn--fpcrj9c3d','.xn--fzc2c9e2c','.xn--g6w251d','.xn--gecrj9c','.xn--h2brj9c','.xn--hgbk6aj7f53bba','.xn--hlcj6aya9esc7a','.xn--j6w193g','.xn--jxalpdlp','.xn--kgbechtv','.xn--kprw13d','.xn--kpry57d','.xn--lgbbat1ad8j','.xn--mgb9awbf','.xn--mgbaam7a8h','.xn--mgbayh7gpa','.xn--mgbbh1a71e','.xn--mgbc0a9azcg','.xn--mgberp4a5d4ar','.xn--o3cw4h','.xn--ogbpf8fl','.xn--p1ai','.xn--pgbs0dh','.xn--s9brj9c','.xn--wgbh1c','.xn--wgbl6a','.xn--xkc2al3hye2a','.xn--xkc2dl3a5ee0h','.xn--yfro4i67o','.xn--ygbi2ammx','.xn--zckzah','.xxx','.ye','.yt','.za','.zm','.zw');
        $linkfound=0;
	$words=preg_split("/( |\/)+/",$text);
	foreach ($words as $word) {
		$link=0; $linkok=0;
                foreach ($tlds as $tld) {
			$tld="\\".$tld;
                        if (preg_match("/[a-z0-9]+".$tld."$/i",$word)) { 
				$link=1; break;
			}
		}
		if ($link) {
			if ($any!="any") {
			foreach ($oklinks as $oklink) { 
				if (preg_match("/".$oklink."/i",$word)) { $link=0; }
			}
			}
                }
		if ($link) { $linkfound=$word;break; }
	}
return ($linkfound);
}

if ( !function_exists('json_decode') ){
    function json_decode($content, $assoc=false){
                require_once 'Services/JSON.php';
                if ( $assoc ){
                    $json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
        } else {
                    $json = new Services_JSON;
                }
        return $json->decode($content);
    }
}

if ( !function_exists('json_encode') ){
    function json_encode($content){
                require_once 'Services/JSON.php';
                $json = new Services_JSON;

        return $json->encode($content);
    }
}

function gu2sclinks($text) {
	$text=preg_replace("/gamingupdate/","supercheats",$text);
	



	return($text);
}

if( !function_exists( "bcdiv" ) )
{
    function bcdiv( $first, $second, $scale = 0 )
    {
        $res = $first / $second;
        return round( $res, $scale );
    }
}

if( !function_exists( "bcmul" ) )
{
    function bcmul( $first, $second, $scale = 0 )
    {
        $res = $first * $second;
        return round( $res, $scale );
    }
}

function blogpreview($text,$length) {
	$text=strip_tags(bbcparse($text));
        $text=preg_replace("/\AIntroduction/","",$text);
	if (strlen($text)>$length) {
        $text=trim(shorten($text,$length));
	$text=substr($text, 0, strrpos($text, ' '));
	$text.=' [..]';
	}
        return($text);
}

function previewtext($text,$length) {
        $text=strip_tags(bbcparse($text));
        $text=preg_replace("/\AIntroduction/","",$text);
        $text=trim(shorten($text,$length));
        return($text);
}

function newspreview($text,$length,$np) {
	$text=trim($text);
	$lines=preg_split("/\n/",$text);
	foreach ($lines as $line) { 
		if ((preg_match("/\[h2\]/",$line)) and (! $title)) { $title=$line;  }
	} 
	if (! $title) { 
		$title=$lines[0];
	}
	$text=strip_tags(bbcparse($title));
        $text=preg_replace("/\AIntroduction/","",$text);
	if ($text) {
        $text=trim(shorten($text,$length));
	} else { $text=$np." Page"; }
        return($text);

}

function convertsubtype($subtype,$plural=false) {
	$subtype=ucfirst(strtolower($subtype));
	$subtype=preg_replace("/andtips/","",$subtype);
	$subtype=preg_replace("/s$/","",$subtype);
	if ($plural) {
	$subtype.="s";
	}
	return($subtype);
}

function parsetext($text) {
$search = array ("'<script[^>]*?>.*?</script>'si",  // Strip out javascript
                 "'&(lt|#60);'i",
                 "'&(gt|#62);'i",
		"'@<script[^>]*?>.*?</script>@si'",	
                 "'<[\/\!]*?[^<>]*?>'si",          // Strip out HTML tags
		"'@<![\s\S]*?--[ \t\n\r]*>@'",
                 "'&(quot|#34);'i",                // Replace HTML entities
                 "'&(amp|#38);'i",
                 "'&(nbsp|#160);'i",
                 "'&(iexcl|#161);'i",
                 "'&(cent|#162);'i",
                 "'&(pound|#163);'i",
                 "'&(copy|#169);'i",
                 "'<embed.*'",
                 "'&#(\d+);'e");                    // evaluate as php

$replace = array ("",
                 "<",
                 ">",
		"",
		"",
                 "",
                 "\"",
                 "&",
                 " ",
                 chr(161),
                 chr(162),
                 chr(163),
                 chr(169),
                 "",
                 "chr(\\1)");

$text = preg_replace($search, $replace, $text);
return ($text);
}

function rwcheck($comment,$rudewords,$type="comment") {
        foreach ($rudewords as $rw) {
                if (preg_match("/(\W|\A)($rw)(\W|$)/i",$comment)) { $comment="[i]This $type has been referred for moderation.[/i]";last; }
        }

return($comment);
}

function setsubowner($cookiedata,$uid) {
	global $ipaddress;
                $scSubData=preg_split("/::/",$cookiedata);
                switch ($scSubData[0]) {
                case "Vote":
			$sql="SELECT pollid FROM daily_poll_responses WHERE dateadded='".$scSubData[1]."' and ipaddress='$ipaddress' LIMIT 1";
			$result = mysql_query($sql) or die ("func1 Unable to get results.");
			if (mysql_num_rows($result)) {
				$row=mysql_fetch_array($result, MYSQL_ASSOC);
				$sql="SELECT dateadded FROM daily_poll_responses WHERE pollid='".$row["pollid"]."' and screenname='".addslashes($uid)."'";
                        	$nresult = mysql_query($sql) or die ("func2 Unable to get results.");
                        	if (!mysql_num_rows($nresult)) {
                        		$sql = "UPDATE daily_poll_responses SET screenname='".addslashes($uid)."' WHERE dateadded='".$scSubData[1]."' and ipaddress='$ipaddress' LIMIT 1";
                        		$result = mysql_query($sql) or die ("func3 Unable to get results.");
				}
			}
                        break;
                case "Thumb":
			$sql="SELECT type,subid FROM submission_thumbs WHERE timestamp='".$scSubData[1]."' and screenname='' and ipaddress='$ipaddress' LIMIT 1";
                        $result = mysql_query($sql) or die ("func4 Unable to get results.");
                        if (mysql_num_rows($result)) {
                                $row=mysql_fetch_array($result, MYSQL_ASSOC);
                                $sql="SELECT timestamp FROM submission_thumbs WHERE type='".$row["type"]."' and subid='".$row["subid"]."' and screenname='".addslashes($uid)."'";
                                $nresult = mysql_query($sql) or die ("func5 Unable to get results.");
                                if (!mysql_num_rows($nresult)) {
                        $sql = "UPDATE submission_thumbs SET screenname='".addslashes($uid)."' WHERE timestamp='".$scSubData[1]."' and screenname='' and ipaddress='$ipaddress' LIMIT 1";
                        $result = mysql_query($sql) or die ("func6 Unable to get results.");
				}
			}
                        break;
                case "Rating":
			$sql="SELECT gameid FROM game_ratings WHERE id='".$scSubData[1]."' and uid=''";
                        $result = mysql_query($sql) or die ("func7 Unable to get results.");
                        if (mysql_num_rows($result)) {
                                $row=mysql_fetch_array($result, MYSQL_ASSOC);
                                $sql="SELECT id FROM game_ratings WHERE gameid='".$row["gameid"]."' and uid='".addslashes($uid)."'";
                                $nresult = mysql_query($sql) or die ("func8 Unable to get results.");
                                if (!mysql_num_rows($nresult)) {	
                        $sql = "UPDATE game_ratings SET uid='".addslashes($uid)."' WHERE id='".$scSubData[1]."' and uid='' LIMIT 1";
                        $result = mysql_query($sql) or die ("func9 - Unable to get results.");
				}
			}
                        break;
                case "Video Comment":
                        $sql = "UPDATE videos_comments SET submittedby='".addslashes($uid)."' WHERE id='".$scSubData[1]."' and submittedby='' LIMIT 1";
                        $result = mysql_query($sql) or die ("func10 - Unable to get results.");
                        break;
                case "Bio Comment":
                        $sql = "UPDATE user_bio_comments SET submittedby='".addslashes($uid)."' WHERE id='".$scSubData[1]."' and submittedby='' LIMIT 1";
                        $result = mysql_query($sql) or die ("func11 - Unable to get results.");
                        break;
                case "Question":
                        $sql = "UPDATE questions SET submittedby='".addslashes($uid)."' WHERE subid='".$scSubData[1]."' and submittedby='' LIMIT 1";
                        $result = mysql_query($sql) or die ("func12 - Unable to get results.");
                        $sql = "UPDATE incoming_main SET submittedby='".addslashes($uid)."' WHERE id='".$scSubData[1]."' and submittedby='' LIMIT 1";
                        $result = mysql_query($sql) or die ("func13 - Unable to get results.");
                        break;
                case "Answer":
                        $sql = "UPDATE answers SET submittedby='".addslashes($uid)."' WHERE subid='".$scSubData[1]."' and submittedby='' and ipaddress='$ipaddress' LIMIT 1";
                        $result = mysql_query($sql) or die ("func14 - Unable to get results.");
                        $sql = "UPDATE incoming_main SET submittedby='".addslashes($uid)."' WHERE id='".$scSubData[1]."' and submittedby='' LIMIT 1";
                        $result = mysql_query($sql) or die ("func15 - Unable to get results.");
                        break;
                case "Comment":
                        $sql = "UPDATE submission_comments SET submittedby='".addslashes($uid)."' WHERE id='".$scSubData[1]."' and submittedby='' LIMIT 1";
                        $result = mysql_query($sql) or die ("func16 - Unable to get results.");
                        break;
                case "Video":
                        break;
                case "Action Replay Code":
                        $sql = "UPDATE action_replay_codes SET submittedby='".addslashes($uid)."' WHERE submittedon='".$scSubData[1]."' and submittedby='' LIMIT 1";
                        $result = mysql_query($sql) or die ("func17 - Unable to get results.");
                        $sql = "UPDATE incoming_main SET submittedby='".addslashes($uid)."' WHERE id='".$scSubData[1]."' and submittedby='' LIMIT 1";
                        $result = mysql_query($sql) or die ("func18 - Unable to get results.");
                        break;
                default:
                        $sql = "SELECT status,platform FROM incoming_main WHERE id='".$scSubData[1]."'";
                        $result = mysql_query($sql) or die ("func19 - Unable to get results.");
                        $row=mysql_fetch_array($result, MYSQL_ASSOC);
                        if ($row["status"]=="ACCEPTED") {
                                $sql = "UPDATE ".sc($row["platform"])." SET submittedby='".addslashes($uid)."' WHERE submittedon='".$scSubData[1]."' and submittedby='' LIMIT 1";
                                $result = mysql_query($sql) or die ("func20 - Unable to get results.");
                        }
                        $sql = "UPDATE incoming_main SET submittedby='".addslashes($uid)."' WHERE id='".$scSubData[1]."' and submittedby='' LIMIT 1";
                        $result = mysql_query($sql) or die ("func21 - Unable to get results.");
                }


}

function getthumbs($type,$subid) {

	$thumbs["up"]=0; $thumbs["down"]=0;
        $query="SELECT thumb FROM submission_thumbs WHERE type='$type' and subid='$subid'";
        $result = mysql_query($query);
        $totalratings=mysql_num_rows($result);
        while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
                $thumbs[$row["thumb"]]++;
        }

	return($thumbs);
}

function getthumb($type,$subid) {

        $query="SELECT thumb FROM submission_thumbs WHERE type='$type' and subid='$subid'";
        $result = mysql_query($query);
        $totalratings=mysql_num_rows($result);
        while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
                $thumbs[$row["thumb"]]++;
        }

	if ($totalratings) {
		$rating=$thumbs["up"]-$thumbs["down"];
		if ($type=="answer") {
		#$query="UPDATE answers SET thumb='$rating' WHERE id='".$subid."'";
        	#$result = mysql_query($query);
		}
		if ($rating<=0) { $rating="0"; }
	} else {
		$rating='-';
	}
return ($rating);
}


function getUser($uid) {
	$query = "SELECT rec_id,screenname,signupdate,pro,avatar FROM users WHERE screenname = '".addslashes($uid)."'";
	$result = mysql_query($query) or die("</select>$query<BR>error:". mysql_error());
	$user = mysql_fetch_array($result, MYSQL_ASSOC);
	if (preg_match("/\//",$user["signupdate"])) {
		$d=preg_split("/\//",$user["signupdate"]);
		$user["signupdate"]=mktime(12,0,0,$d[1],$d[0],$d[2]);
	}
	return($user);
}

function checkpro($id) {
$query = "SELECT pro FROM users WHERE screenname = '$id'";
$result = mysql_query($query) or die("</select>$query<BR>error:". mysql_error());
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
        $pro=$row["pro"];
}
return($pro);
}

function getmvps() {
# nned to be connected to forums
$query="SELECT name,type,topic,winner FROM mvp_competitions WHERE winner!=''";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
        $mvpwinners[$row["winner"]][]=$row;
}
return($mvpwinners);
}

function bbcremoveall($text) {
	$text=preg_replace("/\[([^\]]+)\]([^\[]*)\[([^\]]+)\]/i","",$text);
	return($text);
}

function testbbcparse($text,$width=420,$opentag='<p class="main">',$closetag="</p>") {
$debug=$text."\n-------------2-------------------\n2";
        $text=htmlspecialchars($text);
$debug.=$text."\n-------------3-------------------\n3";
        $text=bbcodeparse($text,$width,$opentag,$closetag);
$debug.=$text."\n-------------4-------------------\n4";
        while ((preg_match("/\[[^\n]+\]/",$text)) and ($num<=4)) {
                $text=bbcodeparse($text,$width,$opentag,$closetag);
$debug.=$text."\n-------------5-------------------\n5";
                $num++;
        }
        $text=preg_replace("/(\r\n|\n\r|\r|\n)/","<br />",$text);
$debug.=$text."\n--------------end------------------\n";
        return($debug.$text);

}
function bbcparse($text,$width=420,$opentag='<p>',$closetag="</p>",$cr="br") {
	#$text=htmlspecialchars($text); ## breaks &pound; etc...
	$text=bbcodeparse($text,$width,$opentag,$closetag);
	while ((preg_match("/\[[^\n]+\]/",$text)) and ($num<=4)) {
		$text=bbcodeparse($text,$width,$opentag,$closetag);
		$num++;
	}
	
	if ($cr=="p") {
	$text='<p>'.preg_replace("/(\r\n\r\n|\n\r\n\r|\r\r|\n\n)/","</p><p>",$text).'</p>';
	} 
	$text=preg_replace("/(\r\n|\n\r|\r|\n)/","<br />",$text);
	return($text);

}

function bbcodeparse($text,$width=420,$opentag,$closetag) {
$opentag=""; $closetag="";
#$text=parsetext($text);
#$text=utf8_encode($text);

#smilies
$text=preg_replace("/\:\)/i","<img src='https://resource.supercheats.com/smilies/40pzosh.gif' alt='Smile' />",$text);
$text=preg_replace("/\:anxious\:/i","<img src='https://resource.supercheats.com/smilies/2yoa3v6.gif' alt='Anxious' />",$text);
$text=preg_replace("/\:applause\:/i","<img src='https://resource.supercheats.com/smilies/47nslt3.gif' alt='Applause' />",$text);
$text=preg_replace("/\:bounce\:/i","<img src='https://resource.supercheats.com/smilies/4gq6nf9.gif' alt='Bounce' />",$text);
$text=preg_replace("/\:brickwall\:/i","<img src='https://resource.supercheats.com/smilies/30d9mb7.gif' alt='Brick Wall' />",$text);
$text=preg_replace("/\:cool\:/i","<img src='https://resource.supercheats.com/smilies/2ldfz1g.gif' alt='Cool' />",$text);
$text=preg_replace("/\:dancing\:/i","<img src='https://resource.supercheats.com/smilies/3y3j705.gif' alt='Dancing' />",$text);
$text=preg_replace("/\:doh\:/i","<img src='https://resource.supercheats.com/smilies/33bz75z.gif' alt='Doh' />",$text);
$text=preg_replace("/\:drool\:/i","<img src='https://resource.supercheats.com/smilies/454zm38.gif' alt='Drool' />",$text);
$text=preg_replace("/\:eh\:/i","<img src='https://resource.supercheats.com/smilies/4gxo57r.gif' alt='Eh' />",$text);
$text=preg_replace("/\:evil\:/i","<img src='https://resource.supercheats.com/smilies/2e2p2k5.gif' alt='Evil' />",$text);
$text=preg_replace("/\:liar\:/i","<img src='https://resource.supercheats.com/smilies/402ympz.gif' alt='Liar' />",$text);
$text=preg_replace("/\:nottalking\:/i","<img src='https://resource.supercheats.com/smilies/2nlef47.gif' alt='Not Talking' />",$text);
$text=preg_replace("/\:pray\:/i","<img src='https://resource.supercheats.com/smilies/2yvo4t0.gif' alt='Pray' />",$text);
$text=preg_replace("/\:rock\:/i","<img src='https://resource.supercheats.com/smilies/2cfzhuh.gif' alt='Rock' />",$text);
$text=preg_replace("/\:salute\:/i","<img src='https://resource.supercheats.com/smilies/2gue8tg.gif' alt='Salute' />",$text);
$text=preg_replace("/\:shame\:/i","<img src='https://resource.supercheats.com/smilies/2w3cb3b.gif' alt='Shame' />",$text);
$text=preg_replace("/\:shhh\:/i","<img src='https://resource.supercheats.com/smilies/2elb3gz.gif' alt='Shhh' />",$text);
$text=preg_replace("/\:sick\:/i","<img src='https://resource.supercheats.com/smilies/3y2uwaw.gif' alt='Sick' />",$text);
$text=preg_replace("/\:silenced\:/i","<img src='https://resource.supercheats.com/smilies/300em38.gif' alt='Silenced' />",$text);
$text=preg_replace("/\:smile\:/i","<img src='https://resource.supercheats.com/smilies/40pzosh.gif' alt='Smile' />",$text);
$text=preg_replace("/\:speaktothehand\:/i","<img src='https://resource.supercheats.com/smilies/3yzegk7.gif' alt='Speak to the hand' />",$text);
$text=preg_replace("/\:think\:/i","<img src='https://resource.supercheats.com/smilies/30rtn9k.gif' alt='Think' />",$text);
$text=preg_replace("/\:thumbsup\:/i","<img src='https://resource.supercheats.com/smilies/2wfk49l.gif' alt='Thumbs Up' />",$text);
$text=preg_replace("/\:violin\:/i","<img src='https://resource.supercheats.com/smilies/33o6x07.gif' alt='Violin' />",$text);
$text=preg_replace("/\:whistle\:/i","<img src='https://resource.supercheats.com/smilies/3zi4m5s.gif' alt='Whistle' />",$text);
$text=preg_replace("/\:wiseguy\:/i","<img src='https://resource.supercheats.com/smilies/4getq2e.gif' alt='Wiseguy' />",$text);

$text=preg_replace("/\[\*\]([^\n]+)\n/","<li>\\1</li>",$text);
$text=preg_replace("/\[list\]([^\[]+)\[\/list\]/i","$closetag<ul>\\1</ul>$opentag",$text);
$text=preg_replace("/\[list=num\]([^\[]+)\[\/list\]/i","$closetag<ol>\\1</ol>$opentag",$text);
$text=preg_replace("/\[list=alpha\]([^\[]+)\[\/list\]/i","<ol style=\"list-style-type: lower-alpha\">\\1</ul>",$text);

$text=preg_replace("/\[line\]/i","$closetag<hr size='1'>$opentag",$text);
$text=preg_replace("/\[h2\]([^\[]+)\[\/h2\]/i","$closetag<h2>\\1</h2>$opentag",$text);
$text=preg_replace("/\[li\]([^\[]+)\[\/li\]/i","<li>\\1</li>",$text);
$text=preg_replace("/\[ul\]([^\[]+)\[\/ul\]/i","$closetag<ul>\\1</ul>$opentag",$text);
$text=preg_replace("/\[b\]([^\[]+)\[\/b\]/i","<b>\\1</b>",$text);
$text=preg_replace("/\[i\]([^\[]+)\[\/i\]/i","<i>\\1</i>",$text);
$text=preg_replace("/\[u\]([^\[]+)\[\/u\]/i","<u>\\1</u>",$text);
$text=preg_replace("/\[size=2[8-9]\]([^\[]+)\[\/size\]/i","[size=28]\\1[/size]",$text);
$text=preg_replace("/\[size=[3-9][0-9]\]([^\[]+)\[\/size\]/i","[size=28]\\1[/size]",$text);
$text=preg_replace("/\[size=\d{3,}\]([^\[]+)\[\/size\]/i","[size=28]\\1[/size]",$text);
$text=preg_replace("/\[size=([^\]]+)\]([^\[]+)\[\/size\]/i","<span style='font-size:\\1pt'>\\2</span>",$text);
$text=preg_replace("/\[color=([^\]]+)\]([^\[]+)\[\/color\]/i","<span style='color:\\1'>\\2</span>",$text);
$text=preg_replace("/\[font=([^\]]+)\]([^\[]+)\[\/font\]/i","<span style='font-family:\\1'>\\2</span>",$text);
$text=preg_replace("/\[left\]([^\[]+)\[\/left\]/i","<div align=left>\\1</div>",$text);
$text=preg_replace("/\[center\]([^\[]+)\[\/center\]/i","$closetag<div align='center'>\\1</div>$opentag",$text);
$text=preg_replace("/\[right\]([^\[]+)\[\/right\]/i","<div align='right'>\\1</div>",$text);
$text=preg_replace("/\[strike\]([^\[]+)\[\/strike\]/i","<strike>\\1</strike>",$text);

$text=preg_replace("/\[xboxavatar\]([^\[]+)\[\/xboxavatar\]/i","<img src='http://avatar.xboxlive.com/avatar/\\1/avatar-body.png'>",$text);
$text=preg_replace("/\[xboxcard\]([^\[]+)\[\/xboxcard\]/i","<iframe src=\"http://gamercard.xbox.com/\\1.card\" scrolling=\"no\" frameBorder=\"0\" height=\"140\" width=\"204\">\\1</iframe>",$text);
$text=preg_replace("/\[reveal\]([^\[]+)\[\/reveal\]/i","<div class='spoiler hand' onclick='this.firstChild.style.display=(this.firstChild.style.display != \"none\" ? \"none\" : \"\" );this.lastChild.style.display=(this.lastChild.style.display != \"none\" ? \"none\" : \"\" );'><div id='thetext' style='display:none;'>\\1</div><div><i>Click to reveal</i></div></div>",$text);
$text=preg_replace("/\[spoiler\]([^\[]+)\[\/spoiler\]/i","<b><i>Spoiler: </i></b><div class='forumspoiler hand' onclick='this.firstChild.style.display=(this.firstChild.style.display != \"none\" ? \"none\" : \"\" );this.lastChild.style.display=(this.lastChild.style.display != \"none\" ? \"none\" : \"\" );'><div id='thetext' style='display:none;'>\\1</div><div><i>click to reveal</i></div></div>",$text);
#$text=preg_replace("/\[quoteby=(([^\]]+)+|)\]([^\[]+)\[\/quote\]/i","<fieldset><legend><strong>\\2</strong> said:</legend>\\3</fieldset>",$text);
$text=preg_replace("/\[quoteby=([^\]]*)\]([^\[]+)\[\/quote\]/i","<fieldset><legend><strong>\\1</strong> said:</legend>\\2</fieldset>",$text);
$text=preg_replace("/\[quote\]([^\[]+)\[\/quote\]/i","<fieldset>\\1</fieldset>",$text);
$text=preg_replace("/( |\A|\n|\r|<BR>)(http:\/\/|https:\/\/)(\w*)\.(\w+)\.(\w{2,4})([^ |\r\n|\n\r|\n|\r]*)/i","\\1[securl=\\2\\3.\\4.\\5\\6]\\2\\3.\\4.\\5\\6[/securl]",$text);


$text=preg_replace("/( |\A|\n|\r|<BR>)(http:\/\/|https:\/\/)(\w*)\.(\w+)\.(\w{2,4})([^ ]*)/i","\\1[securl=\\2\\3.\\4.\\5\\6]\\2\\3.\\4.\\5\\6[/securl]",$text);

$text=preg_replace_callback("/\[url\]([^(\[|<)]+)\[\/url\]/i",create_function('$matches','return urlparse($matches);'),$text);
#$text=preg_replace("/\[url\]([^(\[|<)]+)\[\/url\]/i","[securl=\\1]\\1[/securl]",$text);
#$text=preg_replace("/\[url=([^\]]+)\]([^\[]+)\[\/url\]/i","[securl=\\1]\\2[/securl]",$text);
$text=preg_replace_callback("/\[url=([^\]]+)\]([^\[]+)\[\/url\]/i",create_function('$matches','return urlparse($matches);'),$text);
$text=preg_replace("/\[scurl=(http:\/\/|https:\/\/)([^\]]+)\]([^\[]+)\[\/scurl\]/i","<a href='\\1\\2'>\\3</a>",$text);
$text=preg_replace("/\[scurl=([^\]]+)\]([^\[]+)\[\/scurl\]/i","<a href='https://\\1'>\\2</a>",$text);
$text=preg_replace("/\[scurl\]([^\[]+)\[\/scurl\]/i","<a href='https://\\1'>\\1</a>",$text);
$text=preg_replace("/\[securl=(http:\/\/|https:\/\/)([^\]]+)\]([^\[]+)\[\/securl\]/i","<a href='\\1\\2' target='_blank' rel='nofollow'>\\3</a>",$text);
$text=preg_replace("/\[securl=([^\]]+)\]([^\[]+)\[\/securl\]/i","<a href='http://\\1' target=_blank rel='nofollow'>\\2</a>",$text);

## videos
$text=preg_replace("/\[video\]http(s|):\/\/i.imgur.com\/([^\[]+).mp4\[\/video\]/","<imgur:\\2.mp4>",$text);
$text=preg_replace("/\[video\]http(s|):\/\/(www\.|)vimeo.com\/([^\[]+)\[\/video\]/","<vimeo:\\3::$width>",$text);
$text=preg_replace("/\[video\](http|https):\/\/www.youtube.com\/watch\?(.*)v=([^\[]+)\[\/video\]/","<youtube:\\3::$width>",$text);
$text=preg_replace("/\[video\](http|https):\/\/youtu.be\/([^\[]+)\[\/video\]/","<youtube:\\2::$width>",$text);
$text=preg_replace("/\[video\]http(s|):\/\/www.supercheats.com\/videos\/(.+)\/(.+)\[\/video\]/","<video:\\3>",$text);
$text=preg_replace_callback("/\[video=([^\]])+\]/",create_function('$matches','return showguidevideo($matches[0]);'),$text);

# images
$text=preg_replace("/\[img\]([^\[]+)\[\/img\]/i","<image:\\1>",$text);
$text=preg_replace_callback("/<image:([^>])+>/",create_function('$matches','return showimage($matches[0]);'),$text);
$text=preg_replace("/\[img=([^\]]+)\]/i","<imagetitle:\\1>",$text);
$text=preg_replace_callback("/<imagetitle:([^>])+>/",create_function('$matches','return showimagetitle($matches[0]);'),$text);

$text=preg_replace_callback("/<imgur:([^>])+>/",create_function('$matches','return showimgur($matches[0]);'),$text);
$text=preg_replace_callback("/<vimeo:([^>])+>/",create_function('$matches','return showvimeo($matches[0]);'),$text);
$text=preg_replace_callback("/<youtube:([^>])+>/",create_function('$matches','return showyoutube($matches[0]);'),$text);
if (preg_match_all("/<video:([^>])+>/",$text,$matches)) {
        foreach ($matches[0] as $match) {
                $showvideo=showvideo($match,$width);
                $text=preg_replace("/$match/","$showvideo",$text);
        }
}



return ($text);
}

function urlparse($matches) {
	$url=$matches[1]; if ($matches[2]) { $t=$matches[2]; } else { $t=shorten($url,45); }
	if (preg_match("/(http|https):/i",$url)) { $turl=$url; } else { $turl="http://".$url; }
	if (preg_match("/\.supercheats\.com/i",$url)) {
		$text='<a href="'.$turl.'">'.$t.'</a>';
	} else {
		$text='<a href="'.$turl.'" target="_blank" rel="nofollow">'.$t.'</a>';
	}
return($text);

}

function notify_error($page,$error) {
$d=print_r($_SERVER,TRUE);
mail("mark@webmedianetwork.co.uk","Supercheats page error","Error: $error\n\n$d\n\nPage: $page\nIP: ".$_SERVER["REMOTE_ADDR"]."\nTime ".time(),"From: site@supercheats.com\n");

}

function showimgur($code) {
        $code=preg_replace("/(.*<imgur:|>.*)/","",$code);
        $videotext='<div class="videowrapper"><video width="640" autoplay loop><source src="https://i.imgur.com/'.$code.'" type="video/mp4">Your browser does not support the video tag.</video></div>';
        return ($videotext);
}

function showvimeo($code) {
        $code=preg_replace("/(.*<vimeo:|>.*)/","",$code);
        list($code,$width)=preg_split("/::/",$code);
        $height=ceil(($width/4)*3);
        list($code,$trash)=preg_split("/\&/",$code);
        $videotext='<div class="videowrapper"><iframe src="https://player.vimeo.com/video/'.$code.'" width="600" height="345" frameborder="0"></iframe></div>';
        return ($videotext);
}


function showguidevideo($match) {
	$match=preg_replace("/(\[video=|\])/","",$match);
	if (preg_match("/ title=/",$match)) {
		list($match,$title)=preg_split("/ title=/",$match);
	}
	if (preg_match("/(youtube|youtu\.be)/",$match)) {
        	$youtubecode=preg_replace("/.+\?/","",$match);
        	$data=explode("&",$youtubecode);
        	foreach ($data as $d) {
               		$dargs=explode("=",$d);
               		if ($dargs[0]=="v") { $youtubecode=$dargs[1]; }
        	}
		#$vid='https://www.youtube.com/embed/'.$youtubecode;
		#$text='<div class="noPrint"><div class="videowrapper"><iframe width="560" height="315" src="https://www.youtube.com/embed/'.$youtubecode.'" frameborder="0" allowfullscreen></iframe></div>';	
		$text='<div class="noPrint"><div class="videowrapper yt-video" data-yt-url="https://www.youtube.com/embed/'.$youtubecode.'?rel=0&showinfo=0&autoplay=1"><img src="" data-src="https://i.ytimg.com/vi/'.$youtubecode.'/mqdefault.jpg" srcset="https://i.ytimg.com/vi/'.$youtubecode.'/mqdefault.jpg 320w, https://i.ytimg.com/vi/'.$youtubecode.'/sddefault.jpg 640w" data-srcset="https://i.ytimg.com/vi/'.$youtubecode.'/mqdefault.jpg 320w, https://i.ytimg.com/vi/'.$youtubecode.'/sddefault.jpg 640w" sizes="(min-width: 640px) 640px, 100vw" class="hand lazy"><span class="yt-playbutton play-youtube"><i class="fa fa-youtube-play" aria-hidden="true"></i></span></div>';
	} else {
		$vid=$match;
		$query="SELECT id,playwire,width,height,duration,gamename,type FROM videos WHERE originalfilename='".addslashes($vid)."' and type=':Guide:' and (status='ACTIVE' or status='WAIT')";
        	$result = mysql_query($query);
        	$row = mysql_fetch_array($result, MYSQL_ASSOC);
        	if ($row["id"]) {
                	$videodata=$row;
		}
                if ($videodata["playwire"]>1) {
                        if ($videodata["height"]>$videodata["width"]) { $extra='data-height="600"'; }
                        $text='<div class="noPrint"><center>
                        <script data-config="https://config.playwire.com/11665/videos/v2/'.$videodata["playwire"].'/zeus.json" data-width="100%" '.$extra.' src="//cdn.playwire.com/bolt/js/zeus/embed.js" data-id="playwire_'.$videodata["playwire"].'" type="text/javascript"></script></center>
                	';
		} else {
			$vid="https://video.supercheats.com/videos/".vlchyph($videodata["gamename"])."/".$videodata["folder"]."/".$videodata["filename"];
			$text='<div class="noPrint"><div class="videowrapper"><iframe width="640" height="480" src="'.$vid.'" frameborder="0" allowfullscreen></iframe></div>';
		}
	}
	if ($title) { $text.='<div class="guide_caption">'.$title.'</div>'; }
	$text.='</div>';
	return($text);
}

function showimage($match) {
        $image=preg_replace("/(.*<image:|>.*)/","",$match);
        $images=preg_split("/::/",$image);
        if (count($images)>1) {
        $random=getUniqueCode(3);
                $image='<ul class="thumbset">';
                foreach ($images as $i) {
                        if (preg_match("/latestscreens.com/",$i)) {
                                if (preg_match("/\/thumbs\//",$i)) {
                                $thumb=$i;
                                $target=preg_replace("/\/thumbs/","",$i);
                                } else {
                                $thumb=preg_replace("/\/([^\/]+)$/","/thumbs/\\1",$i);
                                $target=$i;
                                }
                        } else { $target=$i;$thumb=$i;}
                                #$image.="<li class=thumbset><a href='$target' class='lightview' rel='gallery[set".$random."]'><img src='$thumb' class='thumbsetimage'></a></li>";
				$image.='<li class="thumbset"><img src="'.$thumb.'" class="thumbsetimage hand" data-fullimage="'.$target.'" onclick="fullimage(this);" /></li>';

                }
                $image.="</ul>";
        } else {
        $image=$images[0];
        if (preg_match("/avatarswizard\.com/i",$image)) {
                $image="https://www.supercheats.com/images/blocked.gif";
        }
        if (preg_match("/\.jpg$/",$image)) { $class="screen1"; } else { $class="screen2"; }
	$mediumimageid=thumburl($image,"640");
	$smallimage=thumburl($image,"300");
        $image='<div class="tcenter"><div class="guideimage"><img src="'.$smallimage.'" class="hand fadeinimage '.$class.'" data-mediumimage="'.$mediumimageid.'" data-fullimage="'.$image.'" onclick="fullimage(this);" /></<span class="expand"></span></div></div>';
	$text='<div class="tcenter"><img src="" data-src="'.$mediumimageid.'" class="articleimage lazy" srcset="'.$smallimage.' 300w, '.$mediumimageid.' 640w" sizes="(max-width: 900px) 300px, 640px" data-srcset="'.$smallimage.' 300w, '.$mediumimageid.' 640w" sizes="(max-width: 900px) 300px, 640px" /></div>';
        }
        return ($image);
}
function showimagetitle($match) {
	$match=preg_replace("/(.*<imagetitle:|>.*)/","",$match);
        $matches=preg_split("/ title=/",$match);
	$image=$matches[0];
	$smallimage=thumburl($matches[0],"300");
	$mediumimage=thumburl($matches[0],"640");
	if ($matches[1]) { $caption='<div class="caption">'.$matches[1].'</div>'; $title='title="'.$matches[1].'"'; }
	$text='<div class="tcenter"><img src="" data-src="'.$mediumimage.'" class="articleimage lazy" srcset="'.$smallimage.' 300w, '.$mediumimage.' 640w" sizes="(max-width: 900px) 300px, 640px" data-srcset="'.$smallimage.' 300w, '.$mediumimage.' 640w" sizes="(max-width: 900px) 300px, 640px" '.$title.'/>'.$caption.'</div>';
	return($text);
}

function oldshowimage($match) {
        $image=preg_replace("/(.*<image:|>.*)/","",$match);
        $images=preg_split("/::/",$image);
        if (count($images)>1) {
        $random=getUniqueCode(3);
                $image="<ul class=thumbset>";
                foreach ($images as $i) {
			if (preg_match("/latestscreens.com/",$i)) {
                                if (preg_match("/\/thumbs\//",$i)) {
                                $thumb=$i;
                                $target=preg_replace("/\/thumbs/","",$i);
                                } else {
                                $thumb=preg_replace("/\/([^\/]+)$/","/thumbs/\\1",$i);
                                $target=$i;
                                }
                        } else { $target=$i;$thumb=$i;}
                                $image.="<li class=thumbset><a href='$target' class='lightview' rel='gallery[set".$random."]'><img src='$thumb' class='thumbsetimage'></a></li>";

                }
                $image.="</ul>";
        } else {
        $image=$images[0];
	if (preg_match("/avatarswizard\.com/i",$image)) {
		$image="https://www.supercheats.com/images/blocked.gif";
	}
	if (preg_match("/\.jpg$/",$image)) { $class="screen1"; } else { $class="screen2"; }
	$image='<center><a href="'.$image.'" class="lightview" target="_blank"><img src="'.$image.'" class="'.$class.'" style="max-width:85%; max-height:400px;" /></a></center>';
        }
        return ($image);
}

function showyoutube($youtubecode) {
	$youtubecode=preg_replace("/(.*<youtube:|>.*)/","",$youtubecode);
	list($youtubecode,$width)=preg_split("/::/",$youtubecode);
	#$width=preg_replace("/>/","",$width);
	$height=ceil(($width/4)*3);
        #list($youtubecode,$size)=preg_split("/::/",$data);
        #$youtubecode=preg_replace("/(.*<youtube:|>.*)/","",$youtubecode);
        list($youtubecode,$trash)=preg_split("/\&/",$youtubecode);
        #$videotext='<div class="videowrapper"><iframe width="560" height="315" src="https://www.youtube.com/embed/'.$youtubecode.'" frameborder="0" allowfullscreen></iframe></div>';
	$videotext='<div class="noPrint"><div class="videowrapper yt-video" data-yt-url="https://www.youtube.com/embed/'.$youtubecode.'?rel=0&showinfo=0&autoplay=1"><img src="" data-src="https://i.ytimg.com/vi/'.$youtubecode.'/mqdefault.jpg" srcset="https://i.ytimg.com/vi/'.$youtubecode.'/mqdefault.jpg 320w, https://i.ytimg.com/vi/'.$youtubecode.'/sddefault.jpg 640w" data-srcset="https://i.ytimg.com/vi/'.$youtubecode.'/mqdefault.jpg 320w, https://i.ytimg.com/vi/'.$youtubecode.'/sddefault.jpg 640w" sizes="(min-width: 640px) 640px, 100vw" class="hand lazy"><span class="yt-playbutton play-youtube"><i class="fa fa-youtube-play" aria-hidden="true"></i></span></div></div>';
        return ($videotext);
}

function showvideo($videoid,$width) {
	connect(supercheats);
	$height=ceil(($width/4)*3);
        $videoid=preg_replace("/(.*<video:|>.*)/","",$videoid);
	$query="SELECT * FROM videos WHERE id='$videoid'";
	$stuff = mysql_query($query);
	$row = mysql_fetch_array($stuff, MYSQL_ASSOC);

if ((($force_youtube==1) or ($row["folder"]=="")) and ($row["youtube"]!="")) {

	$youtubecode=preg_replace("/.+\?/","",$row["youtube"]);
	$data=explode("&",$youtubecode);
	foreach ($data as $d) {
        	$dargs=explode("=",$d);
        	if ($dargs[0]=="v") { $youtubecode=$dargs[1]; }
	}
	if ($youtubecode) {
	
		$videotext='</p><div class="videowrapper"><iframe width="560" height="315" src="https://www.youtube.com/embed/'.$youtubecode.'" frameborder="0" allowfullscreen></iframe></div><p>';

	} else {
        	$videotext="<br />// Error loading video //<br />";
        	notify_error($_SERVER["PHP_SELF"],"Youtube video not found");
	}
} else {
	## localvideo
	if ($row["height"]>$row["width"]) { $extra=' data-height="600"'; }
	#$videotext='</p><div align=center><iframe name="video'.$videoid.'" id="video'.$videoid.'" src="http://video.supercheats.com/insertvideo.php?id='.$videoid.'&w='.$width.'&h='.($height+32).'" style="width:'.$width.'px;height:'.($height+32).'px;border:0px;overflow:hidden;"></iframe></div><p>';
	$videotext='</p><br clear="all" /><center><script data-config="https://config.playwire.com/11665/videos/v2/'.$row["playwire"].'/zeus.json" data-width="100%" '.$extra.' src="//cdn.playwire.com/bolt/js/zeus/embed.js" type="text/javascript"></script></center><div class="guide_caption">'.$row["title"].'</div><p>';
}
return($videotext);
}

function niceduration($time) {
                $seconds=fmod($time,60);
                $nicetime=$seconds."s";
                $time=(($time-$seconds)/60);
                if ($time) {
                $minutes=fmod($time,60);
                $nicetime=$minutes."m $nicetime";
                $time=(($time-$minutes)/60);
                }
                if ($time) {
                $hours=fmod($time,24);
                $nicetime=$hours."h $nicetime";
                $time=(($time-$hours)/24);
                }
                if ($time) {
                $days=$time;
                $nicetime=$days."d $nicetime";
                }
                return ($nicetime);

}

function questionTitle($itext,$max) {
        $t=preg_split("/\?/",$itext);
        if (strlen($t[0])<15) { $dotext=$t[0]."?".$t[1]; } else { $dotext=$t[0]."?"; }
        if (strlen($dotext)>$max) {
                $text=substr($dotext,0,($max-2));
                $rest=str_split(substr($dotext,($max-2),100));
                $endreached=1;
                foreach ($rest as $l) {
                        if (preg_match("/[a-z0-9\.?]/",$l)) {
                        $text.=$l;
                        } else { $endreached=0; break; }
                }
                if (! $endreached) {
                $text.="..";
                }
        } else { $text=$dotext; }
        $text=preg_replace("/<[^>]+$/","",$text);
        return($text);
}

function croptext($text,$max) {
	if (strlen($text)>$max) {
                $text=substr($text,0,$max);
		$rest=substr($text,$max);
		foreach ($rest as $i) { if ($i!=" ") { $text.=$i; } }
                $text=preg_replace("/<[^>]+$/","",$text)."..";
        }
        return($text);
}

function shorten($text,$max) {
	if (strlen($text)>$max) {
		$text=substr($text,0,($max-2))."..";
		$text=preg_replace("/<[^>]+$/","",$text);
	}
	return($text);
}

function getavatar($uid) {
$query="SELECT avatar FROM users WHERE screenname='".addslashes($uid)."'";
$stuff = mysql_query($query);
while($row = mysql_fetch_array($stuff, MYSQL_ASSOC)){
	$avatar=$row["avatar"];
}
if (! $avatar) { $avatar="https://www.supercheats.com/images/avatars/noavatar.png"; }
return($avatar);
}

function getuseravatar($name) {
$query="SELECT avatar FROM users WHERE screenname='".addslashes($name)."'";
$stuff = mysql_query($query);
$row = mysql_fetch_array($stuff, MYSQL_ASSOC);
if (! $row["avatar"]) { $row["avatar"]="https://www.supercheats.com/images/avatars/noavatar.png"; }
return ($row);
}

function get_user($id) {
	$query="SELECT rec_id,screenname,status FROM users WHERE rec_id='".addslashes($id)."'";
	$stuff = mysql_query($query);
	$row = mysql_fetch_array($stuff, MYSQL_ASSOC);
	return($row);
}
function getuserdetails($name) {

$query="SELECT * FROM users WHERE screenname='".addslashes($name)."'";
$stuff = mysql_query($query);
$row = mysql_fetch_array($stuff, MYSQL_ASSOC);
if ($row) {
	$row["signupdate"]=date("M jS Y",$row["signupdate"]);
connect(supercheats_forum);
$query="SELECT * FROM forum_users WHERE screenname='".addslashes($name)."'";
$stuff = mysql_query($query);
$frow = mysql_fetch_array($stuff, MYSQL_ASSOC);
$row["status"]=$frow["status"];
$row["posts"]=$frow["posts"];
connect(supercheats);
if (! $row["avatar"]) { $row["avatar"]="https://www.supercheats.com/images/avatars/noavatar.png"; }
return ($row);
}
}


function getuserid($name) {

$query="SELECT rec_id FROM users WHERE screenname='".addslashes($name)."'";
$stuff = mysql_query($query);
while ($row = mysql_fetch_array($stuff, MYSQL_ASSOC)) {
        $id=$row["rec_id"];
}
return ($id);
}

function getgamenamedetails($name) {
        $query="SELECT recid,name,platform,status,lchyphname,rating,packshot,game_thumb FROM products WHERE name = '".addslashes($name)."'";
        $stuff = mysql_query($query);
        while($row = mysql_fetch_array($stuff, MYSQL_ASSOC)) {
		$rows[]=$row;
	}
        return($rows);
}
function getgamenamedetailsi($name) {
        $query="SELECT recid,name,platform,status,lchyphname,rating,packshot,game_thumb FROM products WHERE name = '".addslashes($name)."'";
        $rows=returnmysql($query);
        return($rows);
}

function getgamedetailsi($id) {
        if (is_numeric($id)) {
        } else {
                $error=print_r($_GET,TRUE);
                $error.=print_r($_POST,TRUE);
                $error.=" - $id - \nsite functions";
                notify_error($_SERVER["PHP_SELF"],"1\n".$error);
        }
        $query="SELECT recid,name,platform,status,lchyphname,rating,packshot,game_thumb FROM products WHERE recid = '".addslashes($id)."'";
        $row = returnmysql($query,"single");

        return($row);
}

function getgamedetails($id) {
        if (is_numeric($id)) {
		$query="SELECT recid,name,platform,status,lchyphname,rating,packshot,game_thumb FROM products WHERE recid = '".addslashes($id)."'";
        $stuff = mysql_query($query);
        $row = mysql_fetch_array($stuff, MYSQL_ASSOC);
        } else { 
                $error=print_r($_GET,TRUE);
                $error.=print_r($_POST,TRUE);
		$error.=" - $id - \nsite functions";
                notify_error($_SERVER["PHP_SELF"],"2\n".$error);
        }
	return($row);
}

function igetitemdetails($id) {
        if (is_numeric($id)) {
		$query="SELECT id,name,lchyphname,lcname,urlname,url_bit,system FROM items WHERE id = '".addslashes($id)."'";
        $stuff = mysql_query($query);
        $row = mysql_fetch_array($stuff, MYSQL_ASSOC);
        } else {
                $error=print_r($_GET,TRUE);
                $error.=print_r($_POST,TRUE);
                $error.=" - $id - \nsite functions";
                notify_error($_SERVER["PHP_SELF"],"3\n".$error);
        }
        return($row);
}


function realplatformname($plat) {
$pquery="SELECT name FROM platforms WHERE shortname='$plat' or name='$plat'";
$pstuff = mysql_query($pquery);
while($prow = mysql_fetch_array($pstuff, MYSQL_ASSOC)){
        $platformname=$prow["name"];
}
return ($platformname);
}

function checkquestions($id) {

## check questions
$query="SELECT id FROM questions WHERE gameid = '$id'";
$stuff = mysql_query($query);
if (mysql_num_rows($stuff)) {
        return("YES");
}
}

function checkcheatcodes($id,$lcplatform) {
$query="SELECT recid,submittedby FROM $lcplatform WHERE gamecode='$id' and subtype='cheats' and (submittedby='Team Supercheats' or submittedby='GameCube Dude' or submittedby='Sanzano' or submittedby='Cheat Hunter' or submittedby='MongooseGeneral')";
$stuff = mysql_query($query);
if (mysql_num_rows($stuff)) { return("YES"); }

}

function subtypetoext($subtype) {
	$exttype=strtolower(preg_replace("/( |-)/","",$subtype));

	if ($exttype=="cheats") { $exttype="cheatcodes"; }
	if ($exttype=="usersubmittedcheats") { $exttype="cheats"; }
return ($exttype);
}

function showcomment($row,$width=420) {
if ($row["abusecount"]>=3) { $row["comment"]="[i]This comment has been referred for moderation[/i]"; }
echo '
<div class="black_box padding_10">
                <div class="comments">'.bbcparse($row["comment"],$width).'</div>

';
if ($row["submittedby"]) {
$userdetails=getuserdetails($row["submittedby"]);
echo '
                <div class="comments_bottom">&nbsp;</div>
                <p class="small"><img src="'.$userdetails["avatar"].'" class="border_img fleft comments_img" alt="" /><a href="/members/'.urlencode($row["submittedby"]).'">'.$row["submittedby"].'</a> |  <a href="#">'.$userdetails["status"].'</a>  |  Joined: '.date("M jS Y",$userdetails["signupdate"]).'<br /> <a href="#">'.$userdetails["posts"].' Posts</a>  |  <a href="#">'.$userdetails["acceptedsubs"].' Submissions</a>
';
if ($mvps[$row["submittedby"]]) {
echo ' |  <a href="#">'.$mvps[$row["submittedby"]]["type"].' MVP</a>';
}
echo '</p>
';

} else { $row["submittedby"]="Guest"; }
echo '
             </div>
             <div class="blog_lists_01">
<div class="blog_03">Added '.date("jS M Y",$row["timestamp"]).', ID #'.$row["id"].', by '.$row["submittedby"].'</div>
<div class="blog_04" id="comment'.$row["id"].'">
<a href=\'#reportcomment\' onclick="document.getElementById(\'commentid\').value=\''.$row["id"].'\';" class=\'lightview\'>REPORT</a>
</div>
</div>
            <div class="cboth">&nbsp;</div>
';

}

function sendforgotpassemail($row) {
$code=getUniqueCode(12);
$query="INSERT INTO changes VALUES('".time()."','".$row["rec_id"]."','".addslashes($row["screenname"])."','$code','Password','')";
$result = mysql_query($query) or die(mysql_error());
$message="Dear ".$row["screenname"].",\n\nWe have received a request to reset your password on SuperCheats.com.\n
If you have requested this then please follow the link below. This is a unique link that will expire in 12 hours. If you did not request this or you no longer need to reset your password please ignore this email and no changes will be made to your account. \n\n
To reset the password please click on this link or copy and past it all into a browser address bar:\n
https://www.supercheats.com/passwordreset/$code

regards,
Team SuperCheats
www.supercheats.com
";


mail($row["email"],"SuperCheats Password Reset",$message,"From: webmaster@supercheats.com\n","-f webmaster@supercheats.com");
}

function relatedQuestions($submission) {
	#if (($submission["updatedate"]>(time()-3)) and ($submission["similarqs"])) {
        #        $out=$submission["similarqs"];
        #} else {
                $questiontext=$submission["question"];
                $qid=$submission["id"];
                $ignorewords=array(' ','i','ve','ive','do','a','you','is','it','and','the','get','some','my','should','have');

                $words=preg_split("/\W+/",substr($questiontext,0,250));
                foreach ($words as $word) {
                        if (is_string($word)) {
                                $word=strtolower($word);
                                if (!in_array($word,$ignorewords)) {
                                        $newwords[]=$word;
                                }
                        }
                }
                usort($newwords,'lengthsort');
                $words=array_slice($newwords,0,10);
                $query="SELECT id,title,question,answers FROM questions WHERE gameid='".$submission["gameid"]."' and id!='$qid' and accepted='YES' ORDER BY views DESC LIMIT 50";
		$stuff = mysql_query($query);
		if (mysql_num_rows($stuff)) {
		while($q = mysql_fetch_array($stuff, MYSQL_ASSOC)){
                                $questions[$q["id"]]=$q;
                                foreach ($words as $word) {
                                        if (preg_match("/$word/i",$q["question"])) {
                                                $similarqs[$q["id"]]++;
                                        }
                                }
                }
		}
                if (count($similarqs)>1) {
                        arsort($similarqs);
                        foreach ($similarqs as $i=>$v) {
                                $related[]=$questions[$i];
                        }
                        $related=array_slice($related,0,5);
                        $out=json_encode($related);
        #                $query="UPDATE questions SET updatedate='".time()."',similarqs='".addslashes($out)."' WHERE id='".$qid."'";
			#$stuff = mysql_query($query);
                } else {
			$related=array_slice($questions,0,5);
			$out=json_encode($related);
		}
        #}
        if ($out) {
                return(json_decode($out,TRUE));
        } else {
        return(false);
        }
}

function relatedCodes($submission) {
                $text=$submission["question"];
                $id=$submission["id"];
                $ignorewords=array(' ','i','ve','ive','do','a','you','is','it','and','the','get','some','my','should','have');
                $words=preg_split("/\W+/",substr($text,0,250));
                foreach ($words as $word) {
                        if (is_string($word)) {
                                $word=strtolower($word);
                                if (!in_array($word,$ignorewords)) {
                                        $newwords[]=$word;
                                }
                        }
                }
                usort($newwords,'lengthsort');
                $words=array_slice($newwords,0,10);
		if ($submission["type"]=="codebreaker") {
		$query="SELECT id,title,description FROM codebreaker_codes WHERE ((gameid = '".$submission["gameid"]."') and ((status='ACTIVE') or (status='RECOMMENDED')) and (id!='$id')) ORDER BY status DESC,id DESC LIMIT 50";
		} else {
		$query="SELECT id,title,description FROM action_replay_codes WHERE ((gameid = '".$submission["gameid"]."') and ((status='ACTIVE') or (status='RECOMMENDED')) and (id!='$id')) ORDER BY status DESC,id DESC LIMIT 50";
		}
                $stuff = mysql_query($query) or die(mysql_error());
                if (mysql_num_rows($stuff)) {
                while($q = mysql_fetch_array($stuff, MYSQL_ASSOC)){
                                $codes[$q["id"]]=$q;
                                foreach ($words as $word) {
                                        if (preg_match("/$word/i",$q["description"])) {
                                                $similarcs[$q["id"]]++;
                                        }
                                }
                }
                }
                if (count($similarcs)>1) {
                        arsort($similarcs);
                        foreach ($similarcs as $i=>$v) {
                                $related[]=$codes[$i];
                        }
                        $related=array_slice($related,0,5);
                        $out=json_encode($related);
                }
        if ($out) {
                return(json_decode($out,TRUE));
        } else {
        return(false);
        }
}

function sendchangeemail($row,$newemail) {
$query="DELETE FROM changes WHERE id<'".(time()-43200)."'";
$result = mysql_query($query) or die(mysql_error());
$code=getUniqueCode(12);
$query="INSERT INTO changes VALUES('".time()."','".$row["rec_id"]."','".addslashes($row["screenname"])."','$code','Email','".addslashes($newemail)."')";
$result = mysql_query($query) or die(mysql_error());
$message="Dear ".$row["screenname"].",\n\nWe have received a request to change your email address on SuperCheats.com to this one ($newemail).\n
If you have requested this then please follow the instructions below. This is a unique code that will expire in 12 hours. If you did not request this or you no longer need to change your email address please ignore this email and no changes will be made to your account. \n\n
To confirm the change please return to your account settings page and enter the code below:

$code

https://www.supercheats.com/myaccount/accountsettings

regards,
Team SuperCheats
www.supercheats.com
";

mail($newemail,"SuperCheats Account Email Address",$message,"From: webmaster@supercheats.com\n","-f webmaster@supercheats.com");
}


      function getUniqueCode($length = "")
      {
      $code = md5(uniqid(rand(), true));
      if ($length != "") return substr($code, 0, $length);
      else return $code;
      }


function questionurl($text) {
        $text=lchyph(previewtext($text,40));
        return($text);
}

function getrealplatform($plat) {
        $query="SELECT name FROM platforms WHERE shortname='$plat' or shortname='".strtolower(preg_replace("/ /","",$plat))."'";
        $stuff = mysql_query($query);
        while ($row = mysql_fetch_array($stuff, MYSQL_ASSOC)) {
                $realplat=$row["name"];
        }
        return ($realplat);
}

function getNth ($n) {
        $n=$n*1;
  $qn = (int) (($n%100) / 10);
  $rn = $n % 10;

  $suffix = "th";

  if ($qn != 1) {
   switch ($rn) {
   case 1: $suffix = "st"; break;
   case 2: $suffix = "nd"; break;
   case 3: $suffix = "rd"; break;
   }
  }

  return $n . $suffix;
}

function correcttext($text,$type="") {

$text=preg_replace("/\[b\]\[\/b\]/i","",$text);
$text=preg_replace("/\[i\]\[\/i\]/i","",$text);
$text=preg_replace("/\[u\]\[\/u\]/i","",$text);
$text=preg_replace("/\[color=[^\]]+\]\[\/color\]/i","",$text);
$text=preg_replace("/\[size=[^\]]+\]\[\/size\]/i","",$text);
$text=preg_replace("/\[center\]\[\/center\]/i","",$text);
$text=preg_replace("/\[strike\]\[\/strike\]/i","",$text);
$text=preg_replace("/\[spoiler\]\[\/spoiler\]/i","",$text);
$text=preg_replace("/\[quote\]\[\/quote\]/i","",$text);
$text=preg_replace("/\[url\]\[\/url\]/i","",$text);
$text=preg_replace("/\[img\]\[\/img\]/i","",$text);
$text=preg_replace("/\[video\]\[\/video\]/i","",$text);
$text=preg_replace("/\[list\]\n\[\*\]\n\[\/list\]/i","",$text);

$query = "SELECT * FROM autocorrect";
$result = mysql_query($query) or die("</select>$query<BR>error:". mysql_error());
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
        $before=$row["before"];
        $corrections[$before]=$row["after"];
}
$textlines=preg_split("/\. +/",$text);
$num=count($textlines);
foreach ($textlines as $line) {
        reset($corrections);
        while (list($key, $val) = each($corrections)) {
                $line=preg_replace("/([^a-z0-9\"'\[])$key([^a-z0-9\"'\]])/i","\\1$val\\2",$line);
                $line=preg_replace("/\[I\]/","[i]",$line);
		$line=preg_replace("/\[\/I\]/","[/i]",$line);
                #$line=preg_replace("/ $key,/i"," $val,",$line);
		#$line=preg_replace("/\]$key($| |,|.|\[)/i","]$val\\1",$line);
		#$line=preg_replace("/(\A| |,|.|\[)$key\[/i","\\1$val"."[",$line);
	
        }
        $line=ucfirst($line);
        #$newtext.=trim($line);
        $newtext.=$line;
        if ($num > 1) {
                $newtext.=". ";
        }
        $num--;
}
$textlines=preg_split("/\? +/",$newtext);
$num=count($textlines);
foreach ($textlines as $line) {
	if (! preg_match("/\Ahttp/",$line)) {
        $line=ucfirst($line);
	}
        $newnewtext.=$line;
        if ($num > 1) {
                $newnewtext.="? ";
        }
        $num--;
}
$textlines=preg_split("/\n/",$newnewtext);
$num=count($textlines);
foreach ($textlines as $line) {
	if (! preg_match("/\Ahttp/",$line)) {
        $line=ucfirst($line);
        }
        $newnewnewtext.=$line;
        if ($num > 1) {
                $newnewnewtext.="\n";
        }
        $num--;
}
$textlines=preg_split("/! +/",$newnewnewtext);
$num=count($textlines);
foreach ($textlines as $line) {
	if (! preg_match("/\Ahttp/",$line)) {
        $line=ucfirst($line);
        }
        $newnewnewnewtext.=$line;
        if ($num > 1) {
                $newnewnewnewtext.="! ";
        }
        $num--;
}
$newtext=stripslashes($newnewnewnewtext);
return ($newtext);
}

## forums

function getlastpost($post) {
$query="SELECT posterid,post_time FROM fullposts WHERE id='$post'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result, MYSQL_ASSOC);
return($row);

}

function gettopic($id) {
$query="SELECT * FROM topics WHERE id='$id'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result, MYSQL_ASSOC);
return($row);

}

function linkcheck($text) {
        if (preg_match("/(\[url\]|a href|www.supercheats.com)/",$text)) {
                return(true);
        } else { return(false); }
}
function backlinkAnswers($game) {
        #$query="SELECT link_text FROM games_backlinks WHERE link_type='answers' and gameid='".$game["id"]."'";
        #$items=returnmysql($query);
        #if ($items) {
        #        foreach ($items as $item) {
         #               $game["answerlinks"][]=$item["link_text"];
          #      }
        #}
        $url='https://www.supercheats.com'.$game["backurl"];
        if (! $game["answerlinks"]) {
        $game["answerlinks"]=array(
'For more questions for '.$game["name"].' check out the [url='.$url.']question page[/url] where you can search or ask your own question.',
'If you are still looking for help with this game we have more [url='.$url.']questions and answers[/url] for you to check.',
'Search for more answers for '.$game["name"].' or ask your own question [url='.$url.']here[/url].'
);
        }
        $text=$game["answerlinks"][array_rand($game["answerlinks"], 1)];
        return($text);

}

function breadcrumb($pagevars,$name,$platform,$subtype,$subid) {
$text='<div class="breadcrumb"><a href="https://www.supercheats.com/">Home</a> ';
$baseurl='https://www.supercheats.com/';
if ($platform) {
        if (! $lcplatform) { $lcplatform=sc($platform); }
        if ($lcplatform=="playstation4") { $baseplatformurl="ps4"; } else { $baseplatformurl=$lcplatform; }
        if( $pagevars["platforms"][$lcplatform]["pageformat"]=="new") {
        $basegameurl=lchyph($name).'/';
        $text.='<i class="fa fa-angle-right" aria-hidden="true"></i> <a href="'.$baseurl.$lcplatform.'-cheats.htm">'.$platform.'</a> ';
        $text.='<i class="fa fa-angle-right" aria-hidden="true"></i> <a href="'.$baseurl.$baseplatformurl.'/'.$basegameurl.'">'.$name.'</a> ';
        } else {
        $basegameurl=sc($name);
        $text.='<i class="fa fa-angle-right" aria-hidden="true"></i> <a href="'.$baseurl.$lcplatform.'.htm">'.$platform.'</a> ';
        $text.='<i class="fa fa-angle-right" aria-hidden="true"></i> <a href="'.$baseurl.$baseplatformurl.'/'.$basegameurl.'.htm">'.$name.'</a> ';
        }
        if (($subtype) and ($subtype!="Index") and ($subtype!="cheats") and ($subtype!="hints and tips")) {
        $text.='<i class="fa fa-angle-right" aria-hidden="true"></i> ';
        if ($subid) {
                if ((in_array($lcplatform,$cheattipplats)) and (($subtype=="cheats") or ($subtype=="hints and tips"))) {
                        $text.='<a href="'.$baseurl.$baseplatformurl.'/'.$basegameurl.'/cheats-tips">Cheats and Tips</a>';
                } elseif ($subtype=="Questions") {
			$text.='<a href="'.$baseurl.lchyph($name).'/questions/">Questions</a>';
                #if( $pagevars["platforms"][$lcplatform]["pageformat"]=="new") {
                #        $text.='<a href="'.$baseurl.$baseplatformurl.'/'.$basegameurl.'questions-answers.php">'.ucfirst($subtype).'</a>';
                #} else {
                #        $text.='<a href="'.$baseurl.$baseplatformurl.'/'.$basegameurl.'questions.php">'.ucfirst($subtype).'</a>';
                #}
                } else {
                $subtypeurl=sc(preg_replace("/ and tips/i","",$subtype));
                if ($subtypeurl=="actionreplaycodes") { $subtypeurl="codes2"; }
                if ($subtypeurl=="gamesharkcodes") { $subtypeurl="codes"; }
                $text.='<a href="'.$baseurl.$baseplatformurl.'/'.$basegameurl.$subtypeurl.'.htm">'.ucfirst($subtype).'</a>';
                }
        } else { $text.=$subtype; }
        }
} elseif ($subtype=="Videos") {
        $text.='<i class="fa fa-angle-right" aria-hidden="true"></i> <a href="https://www.supercheats.com/videos.htm">Videos</a> ';
        if ($gamename) {
        $text.='<i class="fa fa-angle-right" aria-hidden="true"></i> <a href="https://www.supercheats.com/'.lchyph($gamename).'/videos/">'.$gamename.'</a> ';
        }
} elseif ($subtype=="Mods") {
        $text.='<i class="fa fa-angle-right" aria-hidden="true"></i> <a href="https://www.supercheats.com/mods.htm">Mods</a> ';
        if ($gamename) {
        $text.='<i class="fa fa-angle-right" aria-hidden="true"></i> <a href="https://www.supercheats.com/'.lchyph($gamename).'/mods/">'.$gamename.'</a> ';
        } elseif ($author["name"]) {
                $text.='<i class="fa fa-angle-right" aria-hidden="true"></i> <a href="https://www.supercheats.com/mods/'.$author["name"].'">'.$author["name"].'</a> ';
        }
}
$text.='</div>';
	return($text);
}

?>
