PHP Code:
	
		
			
<?php
// File ID: functions.php
// Purpose: Provides basic sitewide functions
include("config.php");
$GLOBALS['dbhost'] = $dbhost;              //DB Hostname
$GLOBALS['dbuser'] = $dbuser;            //DB User
$GLOBALS['dbpass'] = $dbpass;            //DB Password
$GLOBALS['dbname'] = $dbname;                //Your database name
$GLOBALS['domain'] = $domain;                //Your domain name (No http, www or . )
$GLOBALS['scriptpath'] = $scriptpath;        //The folder you installed this script in
$GLOBALS['prefix'] = $prefix;
include("lang/lang.php");
//Connect to the database first
connect();
startup();
session_start();  
// clean all our data
$_POST = array_map('secure',$_POST);
$_GET = array_map('secure',$_GET);
$session = session_id();
$time = time();
$time_check = $time - 300; // Time check, delete after 300 seconds (5 minutes)
$result = runquery("SELECT * FROM {$GLOBALS['prefix']}online WHERE `session` = '{$session}'");
$count = mysql_num_rows($result);
$result2 = runquery("SELECT * FROM {$GLOBALS['prefix']}online WHERE `username` = '{$loggedinname}'");
$count2 = mysql_num_rows($result2);
if($isloggedin != "yes")
{
    $loggedinname = "Visitor";
}
if($count == 0 and $count2 == 0)
{
    runquery("INSERT INTO {$GLOBALS['prefix']}online VALUES('$loggedinname', '$session', '$time')");
}
else 
{
      runquery("UPDATE ".$GLOBALS['prefix']."online SET time=".$time.", session ='".$session."', username='".$loggedinname."' WHERE session = '".$session."'");
}
// if over 5 minute, delete session
$sql4="DELETE FROM ".$GLOBALS['prefix']."online WHERE time < ".$time_check;
$result4=runquery($sql4);
// Begin functions definition:
function runquery($query) {
    // next three lines may be commented out if debugging is unnessecary
    //$arr = debug_backtrace();
    //$GLOBALS['queries'] .= "<br /><strong>{$query}</strong> on line {$arr[0]["line"]} of {$arr[0]["file"]}.";
    //$GLOBALS['numberofqueries']++;
    $result = mysql_query($query);
    return $result;
}
function changecash($amount, $user, $startamount) {
    $newamount = $startamount + $amount;
    if ($newamount >= 0) {
        $GLOBALS['money'] = $newamount;
        runquery("UPDATE {$GLOBALS['prefix']}users SET `money` = '{$newamount}' WHERE `username` = '{$user}'");
        return true;
    }
    return false;
}
function clickreward($amount, $user, $startamount) {
    $addamount = explode(",",$amount);
    $randamount = rand($addamount[0], $addamount[1]);
    return $randamount;
}
function connect() {
    //This function simply connects us to the database
    $conn = mysql_connect($GLOBALS['dbhost'], $GLOBALS['dbuser'], $GLOBALS['dbpass']) or die ('Error connecting to MySQL');
    mysql_select_db($GLOBALS['dbname']);
}
function secure($data) {
    //This function performs security checks on all incoming form data
    if(is_array($data)) {
        die("Hacking Attempt!");
    }
    $data = htmlentities($data);
    $data = mysql_real_escape_string($data);
    $data = strip_tags($data, '');
    return $data;
}
function getsitecontent($page) { 
   
    $query = "SELECT * FROM ".$GLOBALS['prefix']."content WHERE page = '$page'"; 
    $result = @runquery($query); 
    $num = @mysql_num_rows($result); 
    //first check if their is any results if yes then pull the data 
    if($num>0){ 
        $title=@mysql_result($result,0,"title"); 
        $content=@mysql_result($result,0,"content"); 
        $password=@mysql_result($result,0,"content_password"); 
        $title = stripslashes($title); 
        $content = stripslashes($content); 
    $value['content'] = $content; 
    $value['title'] = $title; 
    $value['password'] = $password; 
    return $value; 
    } 
    else{ 
    return FALSE; 
    } 
}  
function replace($old, $new, $template) {
    //This function replaces template values
    $template = str_replace($old, $new, $template);
    return $template;
}
function uidtousername ($id) {
$query = "SELECT * FROM ".$GLOBALS['prefix']."users WHERE uid='$id'";
$result = mysql_query($query);
$username=@mysql_result($result,0,"username"); 
return $username;
}
function usernametouid ($name) {
$query = "SELECT * FROM ".$GLOBALS['prefix']."users WHERE username='$name'";
$result = mysql_query($query);
$uid=@mysql_result($result,0,"uid"); 
return $uid;
}
// NOTE - make sure this is only run once in a whole page load - not multiple times!
function logincheck() {
    //Set up our login info...
    $uid = "";
    $password = "";
    //Check for cookie
    if (isset($_COOKIE['auid']) and isset($_COOKIE['apass'])) {
        $uid = $_COOKIE['auid'];
        $password = $_COOKIE['apass'];
        $uid = secure($uid);
        $password = secure($password);
        //Run login operation
        $query = "SELECT * FROM ".$GLOBALS['prefix']."users, ".$GLOBALS['prefix']."groups WHERE uid = '$uid' LIMIT 1";
        $result = runquery($query);
        
        $GLOBALS['usersettings'] = mysql_fetch_array($result);
        $luid=@mysql_result($result, 0, $GLOBALS['prefix']."users.uid");
        $lpass=@mysql_result($result, 0, $GLOBALS['prefix']."users.password");
        $usergroup=@mysql_result($result, 0, $GLOBALS['prefix']."users.usergroup");
        if($uid == $luid and $password == $lpass) {
            $isloggedin = "yes";
        }
        else{
            if (isset($_COOKIE['auser'])) {
                $past = time() - 10; 
                setcookie("auid", $uid, $past);
            }
            if (isset($_COOKIE['apass'])) {
                $past = time() - 10; 
                setcookie("apass", $password, $past);
            }
            $isloggedin = "no";
        }
    }
    else {
        $isloggedin = "no";
    } 
    // return our user data
    $username = uidtousername($uid);
    $GLOBALS['isloggedin'] = $isloggedin;
    $GLOBALS['username'] = $username;
    $GLOBALS['loggedinname'] = $username; // MESSY - I'm unsure of which {username/loggedinname} is the correct one to use.
    $GLOBALS['money'] = $GLOBALS['usersettings']['money'];
    $GLOBALS['group'] = $usergroup;
}
function passencr($username, $password){
$pepper = '2/Fd4o42mMj*4P60s8N7';
$salt = grabanysetting("saltcode");
$password = md5($password);
$newpassword = sha1($username.$password);
$finalpassword = hash('sha512', $pepper.$newpassword.$salt);
return $finalpassword;
}   
function updatepass($username, $password){
$pepper = '2/Fd4o42mMj*4P60s8N7';
$salt = grabanysetting("saltcode");
$newpassword = sha1($username.$password);
$finalpassword = hash('sha512', $pepper.$newpassword.$salt);
return $finalpassword;
}  
function getcash($loggedinname){
//First we see if we are logged in or not
$isloggedin = $GLOBALS['isloggedin'];
$loggedinname = $GLOBALS['username'];
$query = "SELECT * FROM ".$GLOBALS['prefix']."users WHERE username = '$loggedinname'";
$result = runquery($query);
$num = mysql_num_rows($result);
$mycash=@mysql_result($result,0,"money");
return $mycash;
}
function grabanysetting($where) {
    $value = stripslashes($GLOBALS['settings'][$where]);    
    return $value;
}
function getlinks() {
    $links = "";
    $query = "SELECT * FROM ".$GLOBALS['prefix']."links ORDER BY id ASC";
    $result = runquery($query);
    $num = mysql_num_rows($result);
    //Loop out code
    $i=0;
    while ($i < $num) {
        $linktext=@mysql_result($result, $i,"linktext");
        $linkurl=@mysql_result($result, $i,"linkurl");
        $linktext = stripslashes($linktext);
        $links .= "<li><a href='".$linkurl."'>".$linktext."</a></li>";
        $i++;
    }
    return $links;
}
function getsidebar() {
    //This function determines what shows in the side bar of the template
    $isloggedin = $GLOBALS['isloggedin'];
    $loggedinname = $GLOBALS['loggedinname'];
    if($isloggedin == "yes") {
        $msgctr = "<a href='messages.php'>Messages</a>";
        $query = "SELECT * FROM ".$GLOBALS['prefix']."messages WHERE touser='".$loggedinname."' and status='unread'";
        $result = runquery($query);
        $num = mysql_num_rows($result);
        if($num > 0) {
        $msgctr = "<a href='messages.php'>Messages <b>(".$num.")</b></a>";
        }
        $sidebar = "You have {$GLOBALS['money']} {$GLOBALS['settings']['cost']}.<br />
        <a href='donate.php'>Donate some money to friends</a><br />
        <br /><strong>Your links:</strong><br />
        <li><a href='pound.php'>Pound</a></li>
        <li><a href='myadopts.php'>Your Adopts</a></li>
        <li><a href='account.php'>Account</a></li>
        <li>".$msgctr."
        <li><a href='logout.php'>Log Out</a></li>";
           $query = "SELECT * FROM ".$GLOBALS['prefix']."users WHERE username='".$loggedinname."' and usergroup='1'";
           $result = runquery($query);
           $usercancp = mysql_num_rows($result);
        if($usercancp  != 0) {
            $sidebar .= "<li><a href='pages.php?page=admincheck'>Admin Home</a></li>
                                     <li><a href='admin.php'>Admin Center</a></li><br />";
        }
        $query1 = runquery("SELECT * FROM ".$GLOBALS['prefix']."online WHERE username != 'Visitor'");
        $total1 = mysql_num_rows($query1);
        $query2 = runquery("SELECT * FROM ".$GLOBALS['prefix']."online WHERE username = 'Visitor'");
        $total2 = mysql_num_rows($query2);
        $sidebar .= "<a href='online.php'>This site has ".$total1." members and ".$total2." guests online.</a>";
        
        $sidebar .= "</ul>";
    }
    else {
        $sidebar = "<b><u>Member Login:</u></b><br />
        <form name='form1' method='post' action='login.php'>
          <p>Username: 
            <input name='username' type='text' id='username'>
        </p>
          <p>Password: 
            <input name='password' type='password' id='password'>
        </p>
          <p>
            <input type='submit' name='Submit' value='Log In'>
          </p>
        </form>Don't have an account?<br /><a href='register.php'>Register Free</a><br /><a href='forgotpass.php'>Forgot Password?</a>";
        $query1 = runquery("SELECT * FROM ".$GLOBALS['prefix']."online WHERE username != 'Visitor'");
        $total1 = mysql_num_rows($query1);
        $query2 = runquery("SELECT * FROM ".$GLOBALS['prefix']."online WHERE username = 'Visitor'");
        $total2 = mysql_num_rows($query2);
        $sidebar .= "<br />This site currently has ".$total1." members and ".$total2." guests.";
    }
    return $sidebar;
}
function dologin($username, $password) {
    $query = "SELECT * FROM ".$GLOBALS['prefix']."users WHERE username = '$username'";
    $result = @runquery($query);
    $num = @mysql_num_rows($result);
    $luser=@mysql_result($result, 0,"username");
    $lpass=@mysql_result($result, 0,"password");
    $uid = usernametouid ($username);
    if($username == $luser and $password == $lpass) {
        $status = "success";
        //If the cookie already exists for some reason, delete it
        if (isset($_COOKIE['auid']) and isset($_COOKIE['apass'])) {
            $past = time() - 10; 
            setcookie("auid", $uid, $past);
            setcookie("apass", $password, $past);
        }
        // Set the cookie
        $Month = 2592000 + time();
        setcookie("auid", $uid, $Month);
        setcookie("apass", $password, $Month);
    }
    else{
        $status = "error";
    }
    return $status;
}
function getgroup() {
    $isloggedin = $GLOBALS['isloggedin'];
    $loggedinname = $GLOBALS['username'];
    if($isloggedin == "yes") {
    $query = "SELECT * FROM ".$GLOBALS['prefix']."users WHERE username = '$loggedinname'";
    $result = @mysql_query($query);
    $num = @mysql_num_rows($result);
      $group=@mysql_result($result,0,"usergroup");
        return $group;
    }
    else {
        return 0;
    }
}
function cancp($usergroup) {
    //This function determines if a usergroup is allowed to access the Admin CP
    $query = "SELECT * FROM ".$GLOBALS['prefix']."groups WHERE gid = '$usergroup'";
    $result = @mysql_query($query);
    $num = @mysql_num_rows($result);
    $cancp=@mysql_result($result,0,"cancp");
    if($cancp == "" or $usergroup == 0) {
        $cancp = "no";
    }
    
    return $cancp;
}
function getadmlinks() {
    //This function shows special links to the site admin
    $links = "<li><a href='index.php'>Calinmu</a></li>
    <li><a href='admin.php?set=adopts'>Change Adoptables</a></li>
    <li><a href='admin.php?set=content'>Change Content</a></li>
    <li><a href='admin.php?set=users'>Change Users</a></li>
    <li><a href='admin.php?set=settings'>Site Settings</a></li>
    <li><a href='admin.php?set=ads'>Manage Ads</a></li>";
    return $links;
}
function cando($usergroup, $do) {
    //This function determines if a usergroup is allowed to do a specific task
    $cando = $GLOBALS['usersettings'][$do];
    if($cando == "" or $usergroup == 0) {
        $cando = "no";
    }
    return $cando;
}
// QUERYPROBLEM
function canadopt($aid, $cond, $promocode, $row) {
    // This function determines if a user can adopt a specific adoptable...
    $isloggedin = $GLOBALS['isloggedin'];
    $loggedinname = $GLOBALS['username'];
    if($isloggedin != "yes" and $cond != "showing") {
        return "no";
    }
    // Now we check if our usergroup has permission to adopt the adoptable...
    $group = getgroup();
    $dbcanadpt = cando($group, "canadopt");
    if($dbcanadpt != "yes" and $cond != "showing") {
        return "no";
    }
    // Now we check if the adoptable requires a promo code and if the promo code submitted is correct...
    if($row['whenisavail'] == "promo" and $promocode != $row['promocode']) {
        return "no";
    }
    // Now we check those three conditions we have in the Admin CP
    if($row['whenisavail'] == "conditions") {
        // If we have a restriction on the number of times this can be adopted...
        if($row['freqcond'] == "enabled") {
            // Select from the database and determine how many times this adoptable type has been adopted
            $num = 0;
            $query = "SELECT * FROM ".$GLOBALS['prefix']."owned_adoptables WHERE type='$type'"; // QUERYPROBLEM
            $result = runquery($query);
            $num = mysql_num_rows($result);
            if($num > $number) {
                return "no";
            }
        }
        // Begin the date restriction check
        $today = date('Y-m-d');
        if($row['datecond'] == "enabled" and $row['date'] != $today) {
            return "no";
        }
        // We are checking to see how many of this adoptable a user owns
        // If they own more than the specifed number, they cannot adopt...
        if($row['moreless'] == "enabled") {
            $num = 0;
            $query = "SELECT * FROM ".$GLOBALS['prefix']."owned_adoptables WHERE owner='$loggedinname' and type='$type'";
            $result = runquery($query);
            $num = mysql_num_rows($result);
            if($num > $row['morelessnum']) {
                return "no";
            }
        }
        // Check if the user is of a specified usergroup...
        if($row['levelgrle'] == "enabled") {
            $ourgid = getgroup();
            // If the two numbers do not match, do not allow the adoption...
            if($ourgid != $row['grlelevel']) {
                return "no";
            }    
        }
    } // end conditions
    return "yes";
}
// MESSY
function getaltstatus($parentid, $childid, $childlevel) {
    // This function determines if we will use alternate images...
    $altstatus = "no";
    $run = "no";
    // First we need to see if this adoptable type has alternate images enabled...
    $query = "SELECT * FROM ".$GLOBALS['prefix']."adoptables WHERE id='$parentid'";
    $result = runquery($query);
    $num = mysql_num_rows($result);
    $alternates=@mysql_result($result, 0,"alternates"); 
    $altoutlevel=@mysql_result($result, 0,"altoutlevel");
    $altchance=@mysql_result($result, 0,"altchance");
    
    // Let's see if the level we are on is the level that requires alternates
    if($alternates == "enabled") {
        if($childlevel == $altoutlevel) {
            $run = "yes";
        }
    }
    if($run == "yes") {
        $randnum = rand(1, $altchance);
        if( $randnum == 1) {
            $altstatus = "yes"; // If we pull a 1 as the random number, we use the alternate images :)
        }
    }
    return $altstatus;
}
// MESSY / QUERYPROBLEM
function getcurrentimage($id) {
    // This function determines which image we should use for a given adoptable...
    $image = "";
    // First we select the adoptable from the database and get some basic information...
    $query = "SELECT * FROM ".$GLOBALS['prefix']."owned_adoptables WHERE aid='$id'";
    $result = runquery($query);
    $num = mysql_num_rows($result);
    $type=@mysql_result($result, 0,"type"); 
    $currentlevel=@mysql_result($result, 0,"currentlevel"); 
    $imageurl=@mysql_result($result, 0,"imageurl");
    $usealternates=@mysql_result($result, 0,"usealternates");
    if($imageurl != "") {
        // If we are using a custom image for this adoptable, use that
        $image = $imageurl;
    }
    else {
        // There is no custom image, so we must see if we are using an egg or a level image.
        if($currentlevel == 0 or $currentlevel == "0") {
            // Let's see what the egg image is...    
            $query = "SELECT * FROM ".$GLOBALS['prefix']."adoptables WHERE type='$type'";
            $result = runquery($query);
            $num = mysql_num_rows($result);
            $eggimage=@mysql_result($result, 0, "eggimage"); 
            $image = $eggimage; // Set the image URL equal to the egg image...
        }
        else {
            // We don't know the level or the image - we must find both.
            $query = "SELECT * FROM ".$GLOBALS['prefix']."levels WHERE adoptiename='$type' and thisislevel='$currentlevel'";
            $result = runquery($query);
            $num = mysql_num_rows($result);
            $primaryimage=@mysql_result($result, 0,"primaryimage"); 
            $alternateimage=@mysql_result($result, 0,"alternateimage");
            // If alternate images are enabled and an alternate image exists, use it
            if($usealternates == "yes" and $alternateimage != "") {
                $image = $alternateimage; // Use the alternate image
            }
            else{
                $image = $primaryimage; // Set the image equal to the primary image for the level
            }
        }
    }
    if($type == "" or $image == "") {
        // We did not settle on an image, so we show an error image...
        $image = "http://www.".$GLOBALS['domain']."".$GLOBALS['scriptpath']."/templates/icons/delete.gif";
    }
    return $image;
}
// QUERYPROBLEM - when is getcurrentlevel() actually used?
function getcurrentlevel($id) {
    // This function gets the current level of an adoptable...
    $query = "SELECT * FROM ".$GLOBALS['prefix']."owned_adoptables WHERE aid='$id'";
    $result = runquery($query);
    $num = mysql_num_rows($result);
    $currentlevel=@mysql_result($result, 0,"currentlevel"); 
    if($currentlevel == "") {
        $currentlevel = "error"; // If the adoptable does not have a current level or does not exist, we return an error...
    }
    
    // Return the level
    return $currentlevel;
}
function getnextlevelexists($type, $currentlevel) {
    // This function determines if a higher level exists for an adopt, or if it is at max level.
    $query = "SELECT * FROM ".$GLOBALS['prefix']."levels WHERE adoptiename='$type' and thisislevel > '$currentlevel'";
    $result = runquery($query);
    $num = mysql_num_rows($result);
    if($num > 0) {
        return "true";
    }
    return "false";
}
function convertidtotype($id) {
    // This function takes in an adoptable's ID and returns the type of adoptable it is...
    $query = "SELECT * FROM ".$GLOBALS['prefix']."owned_adoptables WHERE aid='$id'";
    $result = runquery($query);
    $num = mysql_num_rows($result);
     
    $type=@mysql_result($result, 0,"type"); 
    if($type == "") {
        return "error";
    }
    
    return $type;
}
// MESSY - I have no idea what this function is supposed to do.
function converttypetoparentid($type) {
    // This function takes in an adoptable type and returns the ID of the parent
    
    $query = "SELECT * FROM ".$GLOBALS['prefix']."adoptables WHERE type='$type'";
    $result = runquery($query);
    $num = mysql_num_rows($result);
    $id=@mysql_result($result, 0, "id"); 
    if($id == "") {
        $id = "error";
    }
    return $id;
}
// QUERYPROBLEM - this is being called (I believe) on every click page, and uses many too many queries.
function reward($id, $type, $currentlevel, $owner) {
    // This function determines if we are giving the user a reward or not...
    $query = "SELECT * FROM ".$GLOBALS['prefix']."levels WHERE adoptiename='$type' and thisislevel='$currentlevel'";
    $result = runquery($query);
    $num = mysql_num_rows($result);
     
    $rewarduser=@mysql_result($result, 0,"rewarduser"); 
    $promocode=@mysql_result($result, 0,"promocode");
    if($rewarduser == "yes" and $promocode != "") {
        // We are sending out a reward...
        $mtitle = "You have received a reward!";
        $mtext = "Congratulations!  You have received a reward because one of your adoptables leveled up and the site admin has chosen to reward you for this.<br /><br />
        <b><u>Your reward is the following promo code:</u></b> ".$promocode."<br /><br />
        You may use this promo code on the <a href='promo.php?promocode=".$promocode."'>Promo Code Page</a> to receive a special exclusive or limited edition adoptable!<br /><br />
        Congratulations on your reward!";
        $mtext = mysql_real_escape_string($mtext);
        $date = date('Y-m-d');
        $query = "INSERT INTO ".$GLOBALS['prefix']."messages VALUES ('', 'SYSTEM', '$owner','unread','$date','$mtitle', '$mtext')";
        runquery($query);
        // Now we check if we are sending out an email to the user alerting them of the message...
        $query = "SELECT * FROM ".$GLOBALS['prefix']."users WHERE username='".$owner."'";
        $result = runquery($query);
        $num = mysql_num_rows($result);
        $newmessagenotify=@mysql_result($result, 0,"newmessagenotify");
        $email=@mysql_result($result, 0,"email");
        if($newmessagenotify == 1) {
            // We are sending this user an email about the new message...
            $systememail = grabanysetting("systememail"); // QUERYPROBLEM - we should get the settings at the beginning so we never need to call for them after that.
            
            $headers = "From: ".$systememail."";
            $site_name = grabanysetting("sitename"); // QUERYPROBLEM - see, two queries for this message alone.
            $message = "Hello ".$owner.";\n\nYou have received a new Private Message from SYSTEM at ".$site_name." with the title ".$mtitle.".\n
            You can read this message at: http://www.".$GLOBALS['domain']."".$GLOBALS['scriptpath']."/messages.php\n
            Thank You.  The ".$site_name." team.";
            mail($email, $site_name." - You Have Received a Reward", $message, $headers);
        }
    }
    return $rewardstatus; // MESSY - where is the variable $rewardstatus used before this?
}
// MESSY - what is this function for?
function getadmimages() {
    $formcontent = "";
    $query = "SELECT * FROM ".$GLOBALS['prefix']."filesmap";
    $result = runquery($query);
    $num = mysql_num_rows($result);
    $i=0;
    while ($i < $num) {
        $wwwpath=@mysql_result($result, $i,"wwwpath");
        $friendlyname=@mysql_result($result, $i,"friendlyname");
        $formcontent = $formcontent."<option value='".$wwwpath."'>".$friendlyname."</option>";
        $i++;
    }
    return $formcontent;
}
function deleteuser($user) {
    //This function deletes a user from the system...
    $user = secure($user);
    $query = "DELETE FROM ".$GLOBALS['prefix']."users WHERE username = '".$user."'";
    $result = runquery($query);
    $query = "DELETE FROM ".$GLOBALS['prefix']."owned_adoptables WHERE owner = '".$user."'";
    $result = runquery($query);
}
// MESSY - I believe this still runs if there are no ads. There should be an option to turn it off.
function getads($page) {
    // Function to display site advertisements
    
    if($page == "any") {
        $page = "";
    }
    $query = "SELECT * FROM ".$GLOBALS['prefix']."ads WHERE page = '".$page."' and status = 'active' ORDER BY RAND() LIMIT 1";
    $result = @runquery($query);
    $num = @mysql_num_rows($result);
    if($num > 0) {
        $value=@mysql_result($result, 0,"text");
        $value = stripslashes($value);
        $aid=@mysql_result($result, 0,"id");
        $actualimpressions=@mysql_result($result, 0,"actualimpressions");
        $impressions=@mysql_result($result, 0,"impressions");
        if($impressions == "") {
            $impressions = 0;
        }
        $actualimpressions = $actualimpressions + 1;
        //Update the impressions count
        $query = "UPDATE ".$GLOBALS['prefix']."ads SET actualimpressions='".$actualimpressions."' WHERE id='".$aid."'";
        runquery($query);
        //Check that ad is not over max impressions...
        if ($actualimpressions >= $impressions and $impressions != 0) {
            $query = "UPDATE ".$GLOBALS['prefix']."ads SET status='inactive' WHERE id='".$aid."'";
            runquery($query);
        }
    }
    else{
        $value = "";
    }
    return $value;
}
// NEW - mainly by Hall of Famer
function getabandonedimage($id) {
    // This function determines which image we should use for a given adoptable (which has been abandoned).
    $image = "";
    // First we select the adoptable from the database and get some basic information...
    $query = "SELECT * FROM ".$GLOBALS['prefix']."abandoned WHERE aid='$id'";
    $result = runquery($query);
    $num = mysql_num_rows($result);
    $type=@mysql_result($result, 0,"type"); 
    $currentlevel=@mysql_result($result, 0,"currentlevel"); 
    $imageurl=@mysql_result($result, 0,"imageurl");
    $usealternates=@mysql_result($result, 0,"usealternates");
    if($imageurl != "") {
        // If we are using a custom image for this adoptable, use that
        $image = $imageurl;
    }
    else {
        // There is no custom image, so we must see if we are using an egg or a level image.
        if($currentlevel == 0 or $currentlevel == "0") {
            // Let's see what the egg image is...    
            $query = "SELECT * FROM ".$GLOBALS['prefix']."adoptables WHERE type='$type'";
            $result = runquery($query);
            $num = mysql_num_rows($result);
            $eggimage=@mysql_result($result, 0, "eggimage"); 
            $image = $eggimage; // Set the image URL equal to the egg image...
        }
        else {
            // We don't know the level or the image - we must find both.
            $query = "SELECT * FROM ".$GLOBALS['prefix']."levels WHERE adoptiename='$type' and thisislevel='$currentlevel'";
            $result = runquery($query);
            $num = mysql_num_rows($result);
            $primaryimage=@mysql_result($result, 0,"primaryimage"); 
            $alternateimage=@mysql_result($result, 0,"alternateimage");
            // If alternate images are enabled and an alternate image exists, use it
            if($usealternates == "yes" and $alternateimage != "") {
                $image = $alternateimage; // Use the alternate image
            }
            else{
                $image = $primaryimage; // Set the image equal to the primary image for the level
            }
        }
    }
    if($type == "" or $image == "") {
        // We did not settle on an image, so we show an error image...
        $image = "http://www.".$GLOBALS['domain']."".$GLOBALS['scriptpath']."/templates/icons/delete.gif";
    }
    return $image;
}
// NEW - again, I think by Hall of Famer
function canadoptab($aid, $cond, $promocode){
    $canadopt = "yes"; // The default status is that we CAN adopt, unless proven false...
    $isloggedin = $GLOBALS['isloggedin'];
    $loggedinname = $GLOBALS['username'];
    if($isloggedin != "yes" and $cond != "showing"){
        $canadopt = "no";
    }
    // Now we check if our usergroup has permission to adopt the adoptable...
    $group = getgroup();
    $dbcanadopt = cando($group, "canadopt");
    if($dbcanadopt != "yes" and $cond != "showing"){
        $canadopt = "no";
    }
    
    return $canadopt;
} 
// NEW - a function to set everything up on start so we don't need to keep using queries to get stuff
function startup() {
    // get all of our default settings, like title and stuff
    $result = runquery("SELECT * FROM ".$GLOBALS['prefix']."settings");
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        $GLOBALS['settings'][$row['name']] = $row['value'];
    }
    // set up our log in stuff so we always have it
    logincheck();
}
// NEW - a function to get a page from the database
function getpage($name) {
    $query = "SELECT * FROM ".$GLOBALS['prefix']."content WHERE page='{$name}' LIMIT 1";    
    $result = runquery($query);
    $row = mysql_fetch_array($result);
    $GLOBALS['article_content'] = $row['content'];
    $GLOBALS['article_title'] = $row['title'];
    $GLOBALS['date'] = $row['date'];
    return;
}
// NEW - a function to show the page
function showpage($title, $content, $date) {
    $theme = $GLOBALS['usersettings']['theme'];
    if ($theme == '') {
        $theme = grabanysetting("theme");
    }
    $themeurl = "templates/{$theme}/template.html";
    $patterns = array("/:ARTICLETITLE:/","/:ARTICLECONTENT:/", "/:ARTICLEDATE:/", "/:BROWSERTITLE:/", "/:SITENAME:/", "/:SLOGAN:/", "/:LINKSBAR:/", "/:SIDEFEED:/", "/:ADS:/");
    // if we have said we are in an admin area, don't show ads and show admin links
    if ($GLOBALS['admin']==true) {
        $replacements = array($title, $content, $date, grabanysetting("browsertitle")." ".$title, grabanysetting("sitename"), grabanysetting("slogan"), getadmlinks(), getsidebar(), "");
    }
    else {
        $replacements = array($title, $content, $date, grabanysetting("browsertitle")." ".$title, grabanysetting("sitename"), grabanysetting("slogan"), getlinks(), getsidebar(), getads("any"));
    }
    // now that we have our stuff, let's start making it all into a webpage
    $template = file_get_contents($themeurl);
    $template =  preg_replace($patterns, $replacements, $template);
    $template .= "<div style='position: fixed; bottom: 0; left: 0; color: white; font-size: 10px; width: 380px; '>A total of {$GLOBALS['numberofqueries']} queries were used in this page. They were: {$GLOBALS['queries']}</div>";
    return $template;
}
function getpostbar ($name) {
      $query = "SELECT * FROM ".$GLOBALS['prefix']."users WHERE username='$name'";
    $result = runquery($query);
    $num = mysql_num_rows($result);
    $membersince=@mysql_result($result, 0,"membersince"); 
    $dollar=@mysql_result($result, 0,"money"); 
    $avatar=@mysql_result($result, 0,"avatar");
    $bio=@mysql_result($result, 0,"profile");
    $gender=@mysql_result($result, 0,"gender");
    $nickname=@mysql_result($result, 0,"nickname");
$postbar = " 
<table>
<span class='smalltext'> 
<tr>
<td>
<img src='{$avatar}'>
</td>
<td>
<b>Member Since: </b><br>{$membersince}<br> 
<b>Bio:</b><br>{$bio}<br> 
</td>
<td>
<b>Nickname:</b> {$nickname}<br> 
<b>Gender:</b> {$gender}<br>
<b>Cash:</b> <a href='forum.php?do=donate&from={$uid}&am={$dollar}'>{$dollar}</a><br> 
</td>
</span>
</table> 
"; 
return $postbar; 
}
function getonlinestatus($name) {
$query = "SELECT * FROM ".$GLOBALS['prefix']."online WHERE username='$name'";
$result = mysql_query($query);
$num = mysql_num_rows($result);
if($num == 0){
$onlinestatus = "<img src='templates/icons/user_offline.gif'>";
}
else{
$onlinestatus = "<img src='templates/icons/user_online.gif'>";
}
return $onlinestatus;
}
function getfriendgender($name) {
$query = "SELECT * FROM ".$GLOBALS['prefix']."users WHERE username='$name'";
$result = mysql_query($query);
$gender=@mysql_result($result,0,"gender");
if($gender == "Male"){
$friendgender = "<img src='picuploads/m.png'>";
}
else if($gender == "Female"){
$friendgender = "<img src='picuploads/f.png'>";
}
else{
$friendgender = "";
}
return $friendgender;
}
function getfriendid ($name) {
$query = "SELECT * FROM ".$GLOBALS['prefix']."users WHERE username='$name'";
$result = mysql_query($query);
$friendid=@mysql_result($result,0,"friends"); //friendlist
$friendidlist = explode(",",$friendid);
return $friendidlist; 
}
function getfriendnum ($name) {
$friendidlist = getfriendid ($name);
$query = "SELECT * FROM ".$GLOBALS['prefix']."users WHERE username='$name'";
$result = mysql_query($query);
$friendid=@mysql_result($result,0,"friends"); //friendlist
if($friendid == ""){
$friendnum = "0";
}
else{
$friendnum = count($friendidlist);
}
return $friendnum; 
}
function deletefriend($id){
$friendidlist = getfriendid ($loggedinname);
foreach($friendidlist as $friend){
  if($friend != $id){
  $newfriendidlist[] = $friend; 
  }
}
$newfriendid = implode(",", $newfriendidlist);
return $newfriendid;
}
?>