// this failed attempt if it includes superusers.
                            $sql = "SELECT acctid FROM " . db_prefix("accounts") . " WHERE (superuser&" . SU_EDIT_USERS . ")";
                            $result2 = db_query($sql);
                            $subj = translate_mail(array("`#%s failed to log in too many times!", $_SERVER['REMOTE_ADDR']), 0);
                            $number = db_num_rows($result2);
                            for ($i = 0; $i < $number; $i++) {
                                $row2 = db_fetch_assoc($result2);
                                //delete old messages that
                                $sql = "DELETE FROM " . db_prefix("mail") . " WHERE msgto={$row2['acctid']} AND msgfrom=0 AND subject = '" . serialize($subj) . "' AND seen=0";
                                db_query($sql);
                                if (db_affected_rows() > 0) {
                                    $noemail = true;
                                } else {
                                    $noemail = false;
                                }
                                $msg = translate_mail(array("This message is generated as a result of one or more of the accounts having been a superuser account.  Log Follows:`n`n%s", $alert), 0);
                                systemmail($row2['acctid'], $subj, $msg, 0, $noemail);
                            }
                            //end for
                        }
                        //end if($su)
                    }
                    //end if($c>=10)
                }
                //end while
            }
            //end if (db_num_rows)
            redirect("index.php");
        }
    }
} else {
    db_query($sql);
    $err = db_error();
    if ($err) {
        payment_error(E_ERROR, "SQL: {$sql}\nERR: {$err}", __FILE__, __LINE__);
    }
}
function payment_error($errno, $errstr, $errfile, $errline)
{
    global $payment_errors;
    if (!is_int($errno) || is_int($errno) && $errno & error_reporting()) {
        $payment_errors .= "Error {$errno}: {$errstr} in {$errfile} on {$errline}\n";
    }
}
$adminEmail = getsetting("gameadminemail", "*****@*****.**");
if ($payment_errors > "") {
    $subj = translate_mail("Payment Error", 0);
    // $payment_errors not translated
    ob_start();
    echo "<b>GET:</b><pre>";
    reset($_GET);
    var_dump($_GET);
    echo "</pre><b>POST:</b><pre>";
    reset($_POST);
    var_dump($_POST);
    echo "</pre><b>SERVER:</b><pre>";
    reset($_SERVER);
    var_dump($_SERVER);
    echo "</pre>";
    $contents = ob_get_contents();
    ob_end_clean();
    $payment_errors .= "<hr>" . $contents;
 }
 if ($row['acctid'] > 0 && $session['user']['superuser'] & SU_EDIT_USERS) {
     addnav("User Ops");
     addnav("R?Edit User Record", "user.php?op=edit&userid={$row['acctid']}&returnpetition={$id}");
 }
 if ($row['acctid'] > 0 && $session['user']['superuser'] & SU_EDIT_DONATIONS) {
     addnav("User Ops");
     addnav("Edit User Donations", "donators.php?op=add1&name=" . rawurlencode($row['login']) . "&ret=" . urlencode($_SERVER['REQUEST_URI']));
 }
 $write = translate_inline("Write Mail");
 // We assume that petitions are handled in default language
 $yourpeti = translate_mail("Your Petition", 0);
 $peti = translate_mail("Petition", 0);
 $row['body'] = str_replace("[charname]", translate_mail("[charname]", 0), $row['body']);
 $row['body'] = str_replace("[email]", translate_mail("[email]", 0), $row['body']);
 $row['body'] = str_replace("[description]", translate_mail("[description]", 0), $row['body']);
 // For email replies, make sure we don't overflow the URI buffer.
 $reppet = substr(stripslashes($row['body']), 0, 2000);
 output("`@From: ");
 if ($row['login'] > "") {
     rawoutput("<a href=\"mail.php?op=write&to=" . rawurlencode($row['login']) . "&body=" . rawurlencode("\n\n----- {$yourpeti} -----\n{$reppet}") . "&subject=RE:+{$peti}\" target=\"_blank\" onClick=\"" . popup("mail.php?op=write&to=" . rawurlencode($row['login']) . "&body=" . rawurlencode("\n\n----- {$yourpeti} -----\n{$reppet}") . "&subject=RE:+{$peti}") . ";return false;\"><img src='images/newscroll.GIF' width='16' height='16' alt='{$write}' border='0'></a>");
 }
 output_notl("`^`b%s`b`n", $row['name']);
 output("`@Date: `^`b%s`b (%s)`n", $row['date'], relativedate($row['date']));
 output("`@Status: %s`n", $statuses[$row['status']]);
 if ($row['closedate'] != '0000-00-00 00:00:00') {
     output("`@Last Update: `^%s`@ on `^%s (%s)`n", $row['closer'], $row['closedate'], dhms(strtotime('now') - strtotime($row['closedate']), true));
 }
 output("`@Body:`^`n");
 $body = htmlentities(stripslashes($row['body']), ENT_COMPAT, getsetting("charset", "ISO-8859-1"));
 $body = preg_replace("'([[:alnum:]_.-]+[@][[:alnum:]_.-]{2,}([.][[:alnum:]_.-]{2,})+)'i", "<a href='mailto:\\1?subject=RE: {$peti}&body=" . str_replace("+", " ", URLEncode("\n\n----- {$yourpeti} -----\n" . $row['body'])) . "'>\\1</a>", $body);
function systemmail($to, $subject, $body, $from = 0, $noemail = false)
{
    global $session;
    $sql = "SELECT prefs,emailaddress FROM " . db_prefix("accounts") . " WHERE acctid='{$to}'";
    $result = db_query($sql);
    $row = db_fetch_assoc($result);
    db_free_result($result);
    $prefs = unserialize($row['prefs']);
    $serialized = 0;
    if ($from == 0) {
        if (is_array($subject)) {
            $subject = serialize($subject);
            $serialized = 1;
        }
        if (is_array($body)) {
            $body = serialize($body);
            $serialized += 2;
        }
        $subject = safeescape($subject);
        $body = safeescape($body);
    } else {
        $subject = safeescape($subject);
        $subject = str_replace("\n", "", $subject);
        $subject = str_replace("`n", "", $subject);
        $body = safeescape($body);
        if (isset($prefs['dirtyemail']) && $prefs['dirtyemail'] || $from == 0) {
        } else {
            $subject = soap($subject, false, "mail");
            $body = soap($body, false, "mail");
        }
    }
    $sql = "INSERT INTO " . db_prefix("mail") . " (msgfrom,msgto,subject,body,sent,originator) VALUES ('" . $from . "','" . (int) $to . "','{$subject}','{$body}','" . date("Y-m-d H:i:s") . "', " . $session['user']['acctid'] . ")";
    db_query($sql);
    invalidatedatacache("mail-{$to}");
    $email = false;
    if (isset($prefs['emailonmail']) && $prefs['emailonmail'] && $from > 0) {
        $email = true;
    } elseif (isset($prefs['emailonmail']) && $prefs['emailonmail'] && $from == 0 && isset($prefs['systemmail']) && $prefs['systemmail']) {
        $email = true;
    }
    $emailadd = "";
    if (isset($row['emailaddress'])) {
        $emailadd = $row['emailaddress'];
    }
    if (!is_email($emailadd)) {
        $email = false;
    }
    if ($email && !$noemail) {
        if ($serialized & 2) {
            $body = unserialize(stripslashes($body));
            $body = translate_mail($body, $to);
        }
        if ($serialized & 1) {
            $subject = unserialize(stripslashes($subject));
            $subject = translate_mail($subject, $to);
        }
        $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid='{$from}'";
        $result = db_query($sql);
        $row1 = db_fetch_assoc($result);
        db_free_result($result);
        if ($row1['name'] != "") {
            $fromline = full_sanitize($row1['name']);
        } else {
            $fromline = translate_inline("The Green Dragon", "mail");
        }
        $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid='{$to}'";
        $result = db_query($sql);
        $row1 = db_fetch_assoc($result);
        db_free_result($result);
        $toline = full_sanitize($row1['name']);
        // We've inserted it into the database, so.. strip out any formatting
        // codes from the actual email we send out... they make things
        // unreadable
        $body = preg_replace("'[`]n'", "\n", $body);
        $body = full_sanitize($body);
        $subject = htmlentities($subject, ENT_COMPAT, getsetting("charset", "ISO-8859-1"));
        $mailsubj = translate_mail(array("New LoGD Mail (%s)", $subject), $to);
        $mailbody = translate_mail(array("You have received new mail on LoGD at http://%s`n`n" . "-=-=-=-=-=-=-=-=-=-=-=-=-=-`n" . "From: %s`n" . "To: %s`n" . "Subject: %s`n" . "Body: `n%s`n" . "-=-=-=-=-=-=-=-=-=-=-=-=-=-" . "`nDo not respond directly to this email, it was sent from the game email address, and not the email address of the person who sent you the " . "message.  If you wish to respond, log into Legend of the Green Dragon at http://%s .`n`n" . "You may turn off these alerts in your preferences page, available from the village square.", $_SERVER['HTTP_HOST'] . dirname($_SERVER['SCRIPT_NAME']), $fromline, $toline, full_sanitize(stripslashes($subject)), stripslashes($body), $_SERVER['HTTP_HOST'] . dirname($_SERVER['SCRIPT_NAME'])), $to);
        mail($row['emailaddress'], $mailsubj, str_replace("`n", "\n", $mailbody), "From: " . getsetting("gameadminemail", "postmaster@localhost"));
    }
    invalidatedatacache("mail-{$to}");
}
    //now, let's set their item data up
    $sql = "SELECT acctid,name,sex FROM " . db_prefix("accounts") . " WHERE acctid={$playerid} LIMIT 1";
    $result = db_query($sql);
    $row = db_fetch_assoc($result);
    $pname = $row['name'];
    $gifteeid = $row['acctid'];
    $usersex = translate_inline($row['sex'] ? "She" : "He");
    output("`2You have bought `^%s`2 as a gift for `6%s`2!", $gifteditem, $pname);
    output(" %s will receive mail with details on how to pick it up.`0`n`n", $usersex);
    set_module_pref("gifted", 1, "mysticalshop", $gifteeid);
    set_module_pref("giftid", $id, "mysticalshop", $gifteeid);
    set_module_pref("giftcat", $cat, "mysticalshop", $gifteeid);
    //send a mail with name of item, shop, and location (for the clueless)
    $subject = translate_inline("Someone bought you a magical item!");
    $shop = get_module_setting("shopname");
    $loc = get_module_setting("shoploc");
    if ($levellimit == 1 || !is_numeric($levellimit)) {
        $levelmessage = '';
    } else {
        $levelmessage = sprintf_translate(' as soon as you reach level %s', $levellimit);
    }
    if (get_module_setting('shopappear') == 1 && get_module_pref('pass', $gifteeid) == 0) {
        $levelmessage .= translate_inline('. You will need a pass (available at the lodge) to be able to find and enter the shop');
    }
    $message = translate_mail(array('%s `2has bought you `^%s`2!`n`nYou may pick up your gift at `^%s `2in `^%s`2%s.`0', $session['user']['name'], $gifteditem, $shop, $loc, $levelmessage));
    require_once "lib/systemmail.php";
    systemmail($gifteeid, $subject, $message);
    debuglog('purchased ' . $gifteditem . ' for ' . $pname . ' at ' . $shop . ' in ' . $loc . ' (gold: ' . $giftgold . ', gems: ' . $giftgems . ').', $gifteeid);
} else {
    output('Either the item has become unavailable or the person may not receive it.');
}
 if (db_affected_rows(LINK) <= 0) {
     output("`\$Error`^: Your account was not created for an unknown reason, please try again. ");
 } else {
     $sql = "SELECT acctid FROM " . db_prefix("accounts") . " WHERE login='******'";
     $result = db_query($sql);
     $row = db_fetch_assoc($result);
     $args = httpallpost();
     $args['acctid'] = $row['acctid'];
     //insert output
     $sql_output = "INSERT INTO " . db_prefix("accounts_output") . " VALUES ({$row['acctid']},'');";
     db_query($sql_output);
     //end
     modulehook("process-create", $args);
     if ($emailverification != "") {
         $subj = translate_mail("LoGD Account Verification", 0);
         $msg = translate_mail(array("Login name: %s `n`nIn order to verify your account, you will need to click on the link below.`n`n http://%s?op=val&id=%s `n`nThanks for playing!", $shortname, $_SERVER['SERVER_NAME'] . ($_SERVER['SERVER_PORT'] == 80 ? "" : ":" . $_SERVER['SERVER_PORT']) . $_SERVER['SCRIPT_NAME'], $emailverification), 0);
         mail($email, $subj, str_replace("`n", "\n", $msg), "From: " . getsetting("gameadminemail", "*****@*****.**"));
         output("`4An email was sent to `\$%s`4 to validate your address.  Click the link in the email to activate your account.`0`n`n", $email);
     } else {
         rawoutput("<form action='login.php' method='POST'>");
         rawoutput("<input name='name' value=\"{$shortname}\" type='hidden'>");
         rawoutput("<input name='password' value=\"{$pass1}\" type='hidden'>");
         output("Your account was created, your login name is `^%s`0.`n`n", $shortname);
         $click = translate_inline("Click here to log in");
         rawoutput("<input type='submit' class='button' value='{$click}'>");
         rawoutput("</form>");
         output_notl("`n");
         if ($trash > 0) {
             output("`^Characters that have never been logged into will be deleted after %s day(s) of no activity.`n`0", $trash);
         }
         if ($new > 0) {
function mechanicalturk_run()
{
    global $session;
    require_once "common.php";
    require_once "lib/http.php";
    page_header("Report a Monster Sighting");
    $points = get_module_setting("addpoints");
    switch (httpget("creatureaction")) {
        case "report":
            require_once "lib/showform.php";
            // $level = 1;
            output("You head into a little hut on the outskirts of the Outpost, close to where the clearing turns to jungle.`n`nAn excitable-looking man sits behind a desk, a pair of binoculars slung around his neck.`n`n\"`2Hello!`0\" he calls to you, practically bouncing with geeky excitement.  \"`2Have you come to report a sighting of a new monster?  I do so enjoy writing them up!`0\"  He opens a little ledger and whips out a pen, ready for your report.`n`nYou've heard rumours about this guy.  Billing himself as a monster expert, he listens to the reports of new monsters that players find, and writes them down in his book.  Sauntering into his hut and providing deadly serious reports of completely made-up monsters is a game that many contestants enjoy playing.  However, given the aura of Improbability surrounding his innocent-looking ledger, the rumours contain a dark side as well; sometimes, if a made-up monster is deemed to be Improbable enough by the standards of whatever strange powers control the Island, it takes on a physical form in the Jungle...`n`n");
            output("As you're thinking this, a splintering CRUNCH from your left causes you to jump three feet into the air.  `%Admin `4Caveman`\$Joe`0 is standing in the remains of the fourth wall of the hut, holding a large axe.  He strikes an attractive pose and says \"`4This is Improbable Island's monster submission hut.  Think of a new monster, and submit it here.  If your idea is accepted, you'll get %s Donator Points!`0\"`n`nHe turns to the little man sat behind the desk, who at this moment is picking bits of wood out of his tea, hair and person in general.  `%Admin `4Caveman`\$Joe`0 shows him a smile.  \"`4I'd say 'Sorry about your wall,' mate, but I'm not.  All part of the job, you see.`0\"`n`nWith that, he walks back out of the hole in the fourth wall, attaches his Admin Goggles, leaps into the sky and flies away.`n`n", $points);
            output("\"`2What a very, very strange man,`0\" says the little man behind the desk.  Quietly.`n`n");
            output("`4`b<a href=\"http://enquirer.improbableisland.com/dokuwiki/doku.php?id=terrible_monster_suggestions\">Here are the monster submission guidelines</a>.`b`0  You MUST read these first if you want any chance at all of your monster being accepted, I really can't stress this enough.`n`n", true);
            rawoutput("When writing descriptions, please use `n to go down one line, and `n`n to leave a blank line.  That's `n, not 'n.  The ` key is usually in the top left corner of your keyboard - it's the same key you use for colour codes.");
            $form = array("Creature Properties,title", "creatureid" => "Creature id,hidden", "creaturename" => "Creature Name", "creatureweapon" => "Weapon", "creaturewin" => "Win Message (Displayed when the `bcreature kills the player`b)", "creaturelose" => "Death Message (Displayed when the `bplayer kills the creature`b)", "creaturelevel" => "Level,range,1,17,1", "forest" => "Creature is in Jungle?,bool", "graveyard" => "Creature is on FailBoat?,bool", "description" => "A long description of the creature");
            $row = array("creatureid" => 0);
            addnav("I honestly don't have any ideas.  Back to the Jungle.", "forest.php");
            rawoutput("<form action='runmodule.php?module=mechanicalturk&creatureaction=save' method='POST'>");
            showform($form, $row);
            rawoutput("</form>");
            addnav("", "runmodule.php?module=mechanicalturk&creatureaction=save");
            break;
        case "save":
            $creatureid = httppost('creatureid');
            $creaturename = httppost('creaturename');
            $creatureweapon = httppost('creatureweapon');
            $creaturewin = httppost('creaturewin');
            $creaturelose = httppost('creaturelose');
            $creaturelevel = httppost('creaturelevel');
            $forest = httppost('forest');
            $graveyard = httppost('graveyard');
            $description = httppost('description');
            $submittedby = $session['user']['name'];
            $uid = $session['user']['acctid'];
            //			$creatureid = db_insert_id();
            //			$creatureid++;
            //			$sql = 'LOCK TABLES '.db_prefix( 'mechanicalturk' ).' WRITE;';
            //			db_query( $sql );
            //			$sql = "INSERT INTO ".db_prefix("mechanicalturk")."(creatureid,creaturename,creatureweapon,creaturewin,creaturelose,creaturelevel,forest,graveyard,submittedby)	VALUES ($creatureid,$creaturename,$creatureweapon,$creaturewin,$creaturelose,$creaturelevel,$forest,$graveyard,$submittedby)";
            $sql = "INSERT INTO " . db_prefix("mechanicalturk") . " (creaturename,creatureweapon,creaturewin,creaturelose,creaturelevel,forest,graveyard,description,submittedby,uid) VALUES ('" . mysql_real_escape_string($creaturename) . "','" . mysql_real_escape_string($creatureweapon) . "','" . mysql_real_escape_string($creaturewin) . "','" . mysql_real_escape_string($creaturelose) . "','" . (int) $creaturelevel . "','" . (int) $forest . "','" . (int) $graveyard . "','" . mysql_real_escape_string($description) . "','" . mysql_real_escape_string($submittedby) . "',{$uid})";
            //			$result = db_query($sql);
            db_query($sql);
            debug($sql);
            //			$sql = 'UNLOCK TABLES;';
            //			db_query( $sql );
            output("`4The monster \"`^%s`4\" has been submitted.`n`nDue to the high volume of monster submissions, it may take several days or even weeks before you hear back from us.  Please be patient!`0`n`nThe little man behind the desk looks around, confused.  \"Who said that?!\"`n`nYou decide it'd be best to get out of here.", $creaturename);
            addnav("Back to the Jungle", "forest.php");
            break;
        case "showsubmitted":
            $sql = "SELECT creatureid,creaturename,creatureweapon,creaturewin,creaturelose,creaturelevel,forest,graveyard,description,submittedby,uid FROM " . db_prefix("mechanicalturk");
            $result = db_query($sql);
            for ($i = 0; $i < db_num_rows($result); $i++) {
                $row = db_fetch_assoc($result);
                output("Monster submission by %s`n`n", $row['submittedby']);
                output("%s`n`n", stripslashes($row['description']));
                output("You have encountered %s which lunges at you with %s!`n`n", stripslashes($row['creaturename']), stripslashes($row['creatureweapon']));
                output("Creature win message: %s`n", stripslashes($row['creaturewin']));
                output("Creature lose message: %s`n", stripslashes($row['creaturelose']));
                output("Creature level: %s`n", $row['creaturelevel']);
                output("Jungle: %s - FailBoat: %s`n`n", $row['forest'], $row['graveyard']);
                rawoutput("<a href=\"runmodule.php?module=mechanicalturk&creatureaction=edit&id=" . $row['creatureid'] . "\">Edit</a> | <a href=\"runmodule.php?module=mechanicalturk&creatureaction=reject&op=1&id=" . $row['creatureid'] . "\">Reject nonspecifically</a> |  <a href=\"runmodule.php?module=mechanicalturk&creatureaction=reject&op=2&id=" . $row['creatureid'] . "\">Reject because of writing</a> | <a href=\"runmodule.php?module=mechanicalturk&creatureaction=reject&op=3&id=" . $row['creatureid'] . "\">Reject but ask for rewrite</a> | <a href=\"runmodule.php?module=mechanicalturk&creatureaction=reject&op=4&id=" . $row['creatureid'] . "\">Reject because of pop culture refs</a> | <a href=\"runmodule.php?module=mechanicalturk&creatureaction=accept&id=" . $row['creatureid'] . "\">Accept this monster</a>");
                addnav("", "runmodule.php?module=mechanicalturk&creatureaction=edit&id=" . $row['creatureid']);
                addnav("", "runmodule.php?module=mechanicalturk&creatureaction=reject&op=1&id=" . $row['creatureid']);
                addnav("", "runmodule.php?module=mechanicalturk&creatureaction=reject&op=2&id=" . $row['creatureid']);
                addnav("", "runmodule.php?module=mechanicalturk&creatureaction=reject&op=3&id=" . $row['creatureid']);
                addnav("", "runmodule.php?module=mechanicalturk&creatureaction=reject&op=4&id=" . $row['creatureid']);
                addnav("", "runmodule.php?module=mechanicalturk&creatureaction=accept&id=" . $row['creatureid']);
                output("`n`n====================`n`n");
            }
            addnav("Back to the Superuser grotto", "superuser.php");
            break;
        case "edit":
            $id = httpget("id");
            require_once "lib/showform.php";
            addnav("Back to the Jungle", "forest.php");
            $form = array("Creature Properties,title", "creatureid" => "Creature id,hidden", "creaturename" => "Creature Name", "creatureweapon" => "Weapon", "creaturewin" => "Win Message (Displayed when the creature kills the player)", "creaturelose" => "Death Message (Displayed when the creature is killed by the player)", "creaturelevel" => "Level,range,1,18,1", "forest" => "Creature is in Jungle?,bool", "graveyard" => "Creature is on FailBoat?,bool", "description" => "A long description of the creature");
            $sql = "SELECT creatureid,creaturename,creatureweapon,creaturewin,creaturelose,creaturelevel,forest,graveyard,description,submittedby,uid FROM " . db_prefix("mechanicalturk") . " WHERE creatureid = {$id}";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            debug($row);
            $row['creaturename'] = stripslashes($row['creaturename']);
            $row['creatureweapon'] = stripslashes($row['creatureweapon']);
            $row['creaturewin'] = stripslashes($row['creaturewin']);
            $row['creaturelose'] = stripslashes($row['creaturelose']);
            $row['description'] = stripslashes($row['description']);
            rawoutput("<form action='runmodule.php?module=mechanicalturk&creatureaction=update' method='POST'>");
            showform($form, $row);
            rawoutput("</form>");
            addnav("", "runmodule.php?module=mechanicalturk&creatureaction=update");
            addnav("Back to the submission list", "runmodule.php?module=mechanicalturk&creatureaction=showsubmitted");
            addnav("Back to the Superuser grotto", "superuser.php");
            break;
        case "update":
            addnav("Back to the submission list", "runmodule.php?module=mechanicalturk&creatureaction=showsubmitted");
            addnav("Back to the Superuser grotto", "superuser.php");
            $creatureid = httppost('creatureid');
            $creaturename = httppost('creaturename');
            $creatureweapon = httppost('creatureweapon');
            $creaturewin = httppost('creaturewin');
            $creaturelose = httppost('creaturelose');
            $creaturelevel = httppost('creaturelevel');
            $forest = httppost('forest');
            $graveyard = httppost('graveyard');
            $description = httppost('description');
            $sql = "UPDATE " . db_prefix("mechanicalturk") . " SET creaturename = '{$creaturename}', creatureweapon = '{$creatureweapon}', creaturewin = '{$creaturewin}', creaturelose = '{$creaturelose}', creaturelevel = '{$creaturelevel}', forest = {$forest}, graveyard = {$graveyard}, description = '{$description}' WHERE creatureid = {$creatureid}";
            db_query($sql);
            debug($sql);
            output("All done!");
            break;
        case "reject":
            $id = httpget("id");
            $op = httpget("op");
            $sql = "SELECT creatureid,creaturename,creatureweapon,creaturewin,creaturelose,creaturelevel,forest,graveyard,description,submittedby,uid FROM " . db_prefix("mechanicalturk") . " WHERE creatureid = {$id}";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            if ($op == 1) {
                $message = translate_mail(array('It\'s not good news to hear, but I\'m afraid your monster idea (the one named %s) just wasn\'t what we were looking for.  Please feel free to try again with a new idea, though!  Please don\'t feel too bad, because less than thirty per cent of submissions are accepted.  For your reference, the creature description is as follows: %s', $row['creaturename'], $row['description']));
            }
            if ($op == 2) {
                $message = translate_mail(array('It\'s not good news to hear, but I\'m afraid your monster idea (the one named %s) was rejected because of spelling, grammar and/or flow issues.  We heartily recommend taking a look at Elements of Style (Google it).  Spending the half an hour it takes to read it will permanently improve your writing skills, and it can also be read for free online, so we think it\'s a very good deal!  Please don\'t feel too bad, because less than thirty per cent of submissions are accepted.  For your reference, the creature description is as follows: %s', $row['creaturename'], $row['description']));
            }
            if ($op == 3) {
                $message = translate_mail(array('It\'s not good news to hear, but I\'m afraid your monster idea (the one named %s) was rejected.  But it\'s not all bad news - in this case, we thought your monster idea had potential, and would like to see it rewritten and expanded upon, perhaps with a longer or more detailed description.  So please feel free to edit it and resubmit!  Please don\'t feel too bad, because less than thirty per cent of submissions are accepted.  For your reference, the creature description is as follows: %s', $row['creaturename'], $row['description']));
            }
            if ($op == 4) {
                $message = translate_mail(array('It\'s not good news to hear, but I\'m afraid your monster idea (the one named %s) was rejected because it contained a pop culture reference that was either already done to death, too obscure or not funny enough.  Remember, although pop culture references aren\'t specifically disallowed, they must be approximately fifty per cent more awesome than other entries that do not contain pop culture references.  Please don\'t feel too bad, because less than thirty per cent of submissions are accepted.  For your reference, the creature description is as follows: %s', $row['creaturename'], $row['description']));
            }
            require_once "lib/systemmail.php";
            systemmail($row['uid'], "Your monster has been rejected!", $message);
            $sql = "DELETE FROM " . db_prefix("mechanicalturk") . " WHERE creatureid = '{$id}'";
            db_query($sql);
            output("The monster has been deleted, and the author notified.");
            addnav("Show list of submitted monsters", "runmodule.php?module=mechanicalturk&creatureaction=showsubmitted");
            break;
        case "accept":
            $id = httpget("id");
            $sql = "SELECT creaturename,creatureweapon,creaturewin,creaturelose,creaturelevel,forest,graveyard,description,submittedby,uid FROM " . db_prefix("mechanicalturk") . " WHERE creatureid = {$id}";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            debug($row);
            $row['creaturename'] = stripslashes($row['creaturename']);
            $row['creatureweapon'] = stripslashes($row['creatureweapon']);
            $row['creaturewin'] = stripslashes($row['creaturewin']);
            $row['creaturelose'] = stripslashes($row['creaturelose']);
            $row['description'] = stripslashes($row['description']);
            output("Sending this to creatures.php.");
            require_once "lib/showform.php";
            $form = array("Creature Properties,title", "creatureid" => "Creature id,hidden", "creaturename" => "Creature Name", "creatureweapon" => "Weapon", "creaturewin" => "Win Message (Displayed when the creature kills the player)", "creaturelose" => "Death Message (Displayed when the creature is killed by the player)", "creaturelevel" => "Level,range,1,18,1", "forest" => "Creature is in forest?,bool", "graveyard" => "Creature is in graveyard?,bool", "creatureaiscript" => "Creature's A.I.,textarearesizeable");
            rawoutput("<form action='creatures.php?op=save' method='POST'>");
            showform($form, $row);
            rawoutput("</form>");
            output("Monster description:`n`n");
            rawoutput("" . $row['description'] . "");
            output("`n`n`bCOPY THIS TO YOUR CLIPBOARD NOW.`b  The Description is not automated and must be input manually.");
            $message = translate_mail(array('Congratulations!  Your monster idea (the one named %s) has been accepted!  Your Donator Points have also been applied to your account.  Enjoy them!', $row['creaturename']));
            require_once "lib/systemmail.php";
            systemmail($row['uid'], "Your monster idea has been accepted!", $message);
            addnav("", "creatures.php?op=save");
            $acctid = $row['uid'];
            addnav("Go back to the list of submitted monsters", "runmodule.php?module=mechanicalturk&creatureaction=showsubmitted");
            $sql = "UPDATE " . db_prefix("accounts") . " SET donation=donation+{$points} WHERE acctid={$acctid}";
            db_query($sql);
            $sql = "DELETE FROM " . db_prefix("mechanicalturk") . " WHERE creatureid = '{$id}'";
            db_query($sql);
            break;
    }
    page_footer();
}
function homepage_run()
{
    require_once "common.php";
    require_once "lib/is_email.php";
    require_once "lib/checkban.php";
    require_once "lib/http.php";
    page_header("Welcome to Improbable Island");
    global $session;
    $r = httpget('r');
    $name = sanitize_name(getsetting("spaceinname", 0), httppost('name'));
    $pass1 = httppost('pass1');
    $pass2 = httppost('pass2');
    $sex = httppost('gender');
    $email = httppost('email');
    $passlen = (int) httppost("passlen");
    if (substr($pass1, 0, 5) != "!md5!" && substr($pass1, 0, 6) != "!md52!") {
        $passlen = strlen($pass1);
    }
    if (!$sex) {
        $outputgender = "man";
    } else {
        $outputgender = "woman";
    }
    switch (httpget('op')) {
        case "changeskin":
            $skin = httpget('skin');
            if ($skin > "") {
                setcookie("template", $skin, strtotime("+45 days"));
                $_COOKIE['template'] = $skin;
            }
            redirect("index.php?r={$r}", "Home page module changing skin");
            break;
        case "gamecredits":
            page_header("Game Credits");
            output("Improbable Island's plot, characters, Stamina system, Item system, ScrapBots system, Races, Implants, Mounts and probably a few other things were created by Dan Hall, AKA Admin CavemanJoe.`nMany monsters were written by Improbable Island's players.`nImprobable Island runs on a modified version of Legend of the Green Dragon 1.1.1, DragonPrime Edition, which was created by the good folks at dragonprime.com.`nThe DragonPrime Edition was based on the original Legend of the Green Dragon, created by Eric Stevens and J.T. Traub as a homage to Legend of the Red Dragon by Seth Able.`n`nPut simply, Improbable Island is a hodgepodged Frankenstein of a game, but we get by.`n`nThe source code to Legend of the Green Dragon 1.1.1 +DP is available at dragonprime.net.`nThe source code to the most recent version of Legend of the Green Dragon written by Stevens and Traub (upon which the DragonPrime edition is based) is available at lotgd.net.`nThe source code of Improbable Island will be made available on Improbable Labs shortly - for now, it is available on request.`n`nFor more information about Improbable Island and Legend of the Green Dragon, check out the links to the left.");
            addnav("Further Reading");
            addnav("Module Credits", "about.php?op=listmodules&r=" . $r);
            addnav("Creative Commons License Info", "about.php?op=license&r=" . $r);
            addnav("Original Legend of the Green Dragon \"About\" page", "about.php?r=" . $r);
            addnav("Back to the Home Page");
            addnav("Back", "home.php?r=" . $r);
            break;
        case 0:
            $tripfilter = 0;
            $sname = strtolower($name);
            if (substr_count($sname, "nigger") || substr_count($sname, "c**t") || substr_count($sname, "dick") && !substr_count($sname, "dicke") || substr_count($sname, "f****t") || substr_count($sname, "v****a") || substr_count($sname, "pussy") || substr_count($sname, "shit") || substr_count($sname, "wank") || substr_count($sname, "bollocks") || substr_count($sname, "clitoris") || substr_count($sname, "f**k") || substr_count($sname, "d***o") || substr_count($sname, "t**s") || substr_count($sname, "piss") || substr_count($sname, "penis")) {
                output("The gatekeeper's biro stops mid-scrawl.  He looks up at you.  \"`6Seriously?`0\" he asks.  \"`6You're gonna walk into a pub, are you, and espy some sweet young thing who puts your heart all aflutter, and when they ask you your name, you're gonna say \"My name's %s, what's yours?\"  Is that right?`0\"`n`nYou shuffle your feet sheepishly.  Let's try this again.`n`n", $name);
                $redoform = 1;
            }
            //todo: redirect when numbers appear in name
            $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE login='******'";
            $result = db_query($sql);
            if (db_num_rows($result) > 0) {
                output("\"`6Oh, dear...`0\" says the gatekeeper.  \"`6See, we've already got a %s drafted in, here.`0\"`n`nYou stare at him for a moment.  \"`#What in the hell difference does `ithat`i make?!`0\"`n`n\"`6Well, you see, it's easier if everyone has different names, and, well, the computer that handles these forms...`0\" he shrugs.  \"`6It's not particularly bright.`0\"`n`nYou nod.  Computers haven't been terribly bright since the EMP wars.`n`n\"`6Just put down any old thing,`0\" says the gatekeeper.  \"`6I doubt it'll matter much.`0\"`n`n", $name);
                $redoform = 1;
            } else {
                if (strlen($name) < 3) {
                    output("\"`6Oh, dear...`0\" says the gatekeeper.  \"`6I'm afraid that name's just too short.`0\"`n`nYou stare at him for a moment.  \"`#What in the hell difference does `ithat`i make?!`0\"`n`n\"`6Well, you see, the computer that handles these forms...`0\" he shrugs.  \"`6It's not particularly bright.`0\"`n`nYou nod.  Computers haven't been terribly bright since the EMP wars.`n`n\"`6Just put down any old thing,`0\" says the gatekeeper.  \"`6I doubt it'll matter much.`0\"`n`n");
                    $redoform = 1;
                } else {
                    if (strlen($name) > 25) {
                        output("\"`6Oh, dear...`0\" says the gatekeeper.  \"`6I'm afraid that name's just too long.`0\"`n`nYou stare at him for a moment.  \"`#What in the hell difference does `ithat`i make?!`0\"`n`n\"`6Well, you see, the computer that handles these forms...`0\" he shrugs.  \"`6It's not particularly bright.`0\"`n`nYou nod.  Computers haven't been terribly bright since the EMP wars.`n`n\"`6Just put down any old thing,`0\" says the gatekeeper.  \"`6I doubt it'll matter much.`0\"`n`n");
                        $redoform = 1;
                    }
                }
            }
            if ($redoform) {
                rawoutput("<form action='runmodule.php?module=homepage&op=0&r={$r}' method='POST'\">\"<span class=\"colLtCyan\">Well then, I suppose you can call me <input name='name' id=\"name\" accesskey='u' size='12'>.</span>\"  Like you're gonna give him your real name anyway.");
                rawoutput("<br /><div align=\"center\"><input type='submit' value='Carry On' class='button'></div><br /><br /></form>");
                addnav("", "runmodule.php?module=homepage&op=0&r=" . $r);
            } else {
                output("The gatekeeper smiles.  \"`6Okay, %s - now, if you don't mind my asking, are you over eighteen?`0\"`n`n", $name);
                output("You grimace.  \"`#Mate, I've been drafted into some sort of war.  If I'm under eighteen, `isomeone's`i in trouble.`0\"`n`n\"`6That as may be,\"`0 says the gatekeeper, \"`6I've got to ask anyway, before we go any further.  Just to make sure.`0\"`n`n`n");
                rawoutput("<table width=80% align=center style=\"border: 1px solid #990000;\"><tr><td class=\"trlight\">");
                output("`c`\$`bWARNING`b`c`7Although most folks would consider Improbable Island to be work-safe by virtue of it being entirely text-based, I should warn you that you probably wouldn't want to invite the vicar over for tea and scones while playing.`n`nImprobable Island contains `bfoetid Midget Brothels`b and other rather adult (but very silly) situations, and is intended for equally silly `badults`b.  If you're not an adult yet, why not check out Kingdom of Loathing, zOMG, Legends of Zork, Puzzle Pirates, Adventure Quest - there's loads of other browser games, really.`n`n");
                output("And if you `iare`i an adult, and want to carry on - knowing that you're about to be subjected to a barrage of sex, drugs and sausage rolls - by all means, continue with the story and have fun.`0");
                rawoutput("</td></tr></table>");
                output("`n`nYou realise you've been staring off into space for a moment, and you blink a couple of times.  \"`#Sorry, I think I spaced out for a minute there.`0\"");
                rawoutput("<form action='runmodule.php?module=homepage&op=1&r={$r}' method='POST'\">");
                rawoutput("<input type='hidden' name='name' value=\"{$name}\">");
                rawoutput("<br /><div align=\"center\"><input type='submit' value='Yes, I am indeed over eighteen.  Now how about some pants?' class='button'></div></form>");
                addnav("", "runmodule.php?module=homepage&op=1&r=" . $r);
            }
            break;
        case 1:
            output("\"`6Yes, yes, we'll sort you out with some pants in just a minute, %s, don't you worry.`0\"  He reaches down out of sight, and pulls up a sheet of paper and a pen.  You see the words \"CONTESTANT REGISTRATION AND PANTS REQUEST FORM 3A\" printed at the top of the page.  Hell, maybe we're getting somewhere.`n`n\"`6Now, might I ask your gender?`0\"`n`nYou hesitate, dumbstruck.  \"`#I'm stood here `istark naked`i, right in front of you.`0\"`n`n\"`6And thanks to all those bloody Zap grenades going off all the time, all I see is a person-shaped blur who won't be getting any pants until they help me fill out this bloody form!`0\" replies the gatekeeper.`n`n", $name);
            rawoutput("<form action='runmodule.php?module=homepage&op=2&r={$r}' method='POST'\"><input type='radio' name='gender' value='0' checked>\"<span class=\"colLtCyan\"><em>Male</em>, thank you very much.</span>\"<br /><input type='radio' name='gender' value='1'>\"<span class=\"colLtCyan\"><em>Female</em>, thank you very much.</span>\"");
            rawoutput("<input type='hidden' name='name' value=\"{$name}\">");
            rawoutput("<br /><div align=\"center\"><input type='submit' value='And is my voice really that androgynous?' class='button'></div><br /><br /></form>");
            addnav("", "runmodule.php?module=homepage&op=2&r=" . $r);
            break;
        case 2:
            output("\"`6No, %s, you `ido`i sound like a %s, but I like a little joke.`0\" the gatekeeper grins.  ", $name, $outputgender);
            output("\"`6Now, can I just take your E-mail address, please?`0\"`n`nMentally, you file the man under \"Nutters.\"  \"`#Hell, we only got `itelevision`i back about a year ago!  You know full well that computers don't work any more.`0\"`n`n\"`6And they haven't done since the EMP bombings years back, yes.  That's the interesting thing -`0\" he leans forward and lowers his voice.  \"`6I've heard tell that there `iare`i some working computers here.  Proper `isilicon`i ones, not these silly relay-and-vacuum-tube monstrosities we use today, where you think you're rich if you've got sixteen bytes of RAM to play with.  We're talking `iterabytes`i, here!  Just `iimagine`i what we could do with that sort of power!`0\"`n`nYou remember what you did with those resources when you had them, only a few years ago.  You played silly browser games on the Internet.`n`n\"`6Anyway - it's an old, old form, from back in the day when it mattered.  Let's take your E-mail address, so we can have something in the space.`0\"  He grins.  \"`6It's not like I'm going to send you any spam, now, is it?`0\"`n`n");
            rawoutput("<form action='runmodule.php?module=homepage&op=3&r={$r}' method='POST'\">\"<span class=\"colLtCyan\">Fine - as far as I remember, it's <input name='email' id=\"email\" accesskey='e' size='25'>.</span>\"");
            rawoutput("<input type='hidden' name='name' value=\"{$name}\">");
            rawoutput("<input type='hidden' name='gender' value=\"{$sex}\">");
            rawoutput("<br /><div align=\"center\"><input type='submit' value='NOW may I have some pants?' class='button'></div></form>");
            rawoutput("<br /><br /><table width=80% align=center style=\"border: 1px solid #990000;\"><tr><td class=\"trlight\">");
            output("`7He ain't kidding - Improbable Island doesn't spam.  Your E-mail address is used to recover your password if you forget it, and (optionally) to let you know if someone sends you a message in-game - that's it.  We don't use it for anything else, and we never let anyone else see it.`n`nOr, you can continue without entering an E-mail address - but you won't be notified of anything, and you won't be able to recover your password if you lose it!`n");
            rawoutput("<form action='runmodule.php?module=homepage&op=3&override=1&r={$r}' method='POST'\"><input name='email' type='hidden' value='not given'>");
            rawoutput("<input type='hidden' name='name' value=\"{$name}\">");
            rawoutput("<input type='hidden' name='gender' value=\"{$sex}\">");
            rawoutput("<br /><div align=\"center\"><input type='submit' value='Continue without an E-mail address' class='button'></div></form>");
            rawoutput("</td></tr></table>");
            addnav("", "runmodule.php?module=homepage&op=3&override=1&r=" . $r);
            break;
        case 3:
            if ($sexdisplay = "Male") {
                $formalgenderdisplay = "man";
            } else {
                $formalgenderdisplay = "lady";
            }
            if (httpget('override') == 1) {
                output("\"`6Fair enough, then, fair enough - I guess it's pretty pointless asking for an E-mail address when they're impossible to use anyway.`0\"`n`n");
                $carryon = 1;
            } else {
                //validate E-mail
                if (!is_email($email)) {
                    output("The gatekeeper frowns.  \"`6That certainly doesn't `isound`i like an E-mail address.  Are you sure that's right?`0\"`n`nLet's try that again.`n");
                } else {
                    //check for duplicates
                    $sql = "SELECT login FROM " . db_prefix("accounts") . " WHERE emailaddress='{$email}'";
                    $result = db_query($sql);
                    if (db_num_rows($result) > 0) {
                        output("The gatekeeper frowns.  \"`6Are you taking the mick, my good %s?  That E-mail is already in my book, here.  You can only sign up once, you know.`0\"`n`nLet's try that again.`n", $formalgenderdisplay);
                    } else {
                        //email is good, request password
                        output("The gatekeeper grins. \"`6I'm sure if you find those computers, you'll be using that address again soon.`0\"`n`n");
                        $carryon = 1;
                    }
                }
            }
            if ($carryon) {
                rawoutput("<script language='JavaScript' src='lib/md5.js'></script>");
                rawoutput("<script language='JavaScript'>\r\n\t\t\t\t<!--\r\n\t\t\t\tfunction md5pass(){\r\n\t\t\t\t\t// encode passwords\r\n\t\t\t\t\tvar plen = document.getElementById('passlen');\r\n\t\t\t\t\tvar pass1 = document.getElementById('pass1');\r\n\t\t\t\t\tplen.value = pass1.value.length;\r\n\r\n\t\t\t\t\tif(pass1.value.substring(0, 5) != '!md5!') {\r\n\t\t\t\t\t\tpass1.value = '!md5!'+hex_md5(pass1.value);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tvar pass2 = document.getElementById('pass2');\r\n\t\t\t\t\tif(pass2.value.substring(0, 5) != '!md5!') {\r\n\t\t\t\t\t\tpass2.value = '!md5!'+hex_md5(pass2.value);\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t}\r\n\t\t\t\t//-->\r\n\t\t\t\t</script>");
                if (httpget('override')) {
                    rawoutput("<form action='runmodule.php?module=homepage&op=4&override=1&r={$r}' method='POST' onSubmit=\"md5pass();\">");
                } else {
                    rawoutput("<form action='runmodule.php?module=homepage&op=4&r={$r}' method='POST' onSubmit=\"md5pass();\">");
                }
                rawoutput("<input type='hidden' name='passlen' id='passlen' value='0'>");
                rawoutput("<input type='hidden' name='name' value=\"{$name}\">");
                rawoutput("<input type='hidden' name='gender' value=\"{$sex}\">");
                rawoutput("<input type='hidden' name='email' value=\"{$email}\">");
                output("You hear a rustling in the bushes behind you, and turn to look.  Branches sway a couple of feet above head-height - there's something there.`n`nYou're suddenly even more aware that you're naked and unarmed.`n`nYou turn back to the gatekeeper.  \"`#Is this going to take long?`0\"`n`n\"`6No, no, we're nearly done now.`0\"  He reaches down beneath his counter, and brings up a stack of shiny silver coins.  \"`6Here's eighty Requisition tokens to get you started.`0\"`n`nYou consider asking him where the hell he thinks you're going to keep them, but a low `4`igrowling`i`0 sound changes your mind very quickly.`n`n\"`#Let me in.  Forget the pants, just let me in.`0\"`n`n\"`6One moment, sunshine, one moment.  I need a password from you.`0\"`n`n\"`#You're kidding me!  Did you `ihear`i that?!`0\"`n`n\"`6Yes, I heard it, and you'll get inside faster if you listen to me.  You need to make up a password - at least four characters in length.  I know, it sounds like a silly thing to ask, but there's a very good reason for it - you see...`0\"  The growling intensifies, and you look back towards the jungle.`n`nThere's a face.  It's looking at you from between the very leafy branches of a tree.  It's eight feet off the ground and shaped like a gas mask, its eyes as big as fists and deep, bright orange, shining against its jet black carapace.`n`n\"`#Don't care,`0\" you say quietly.  \"`#Really, really don't care.  Just put down ");
                rawoutput("<input type='password' name='pass1' id='pass1'>");
                output(".`0\"`n`nThe gatekeeper scribbles on his form.  \"`6Sorry, just run that past me again?`0\"`n`n\"`#I said ");
                rawoutput("<input type='password' name='pass2' id='pass2'>");
                output("!`0\"`n`n");
                rawoutput("<div align=\"center\"><input type='submit' value='Now let me in, damn it!' class='button'></div></form>");
            } else {
                //output the E-mail form again
                rawoutput("<form action='runmodule.php?module=homepage&op=3&r={$r}' method='POST'\">\"<span class=\"colLtCyan\">Fine - as far as I remember, it's <input name='email' id=\"email\" accesskey='e' size='25'>.</span>\"");
                rawoutput("<input type='hidden' name='name' value=\"{$name}\">");
                rawoutput("<input type='hidden' name='gender' value=\"{$sex}\">");
                rawoutput("<br /><div align=\"center\"><input type='submit' value='NOW may I have some pants?' class='button'></div></form>");
                rawoutput("<br /><br /><table width=80% align=center style=\"border: 1px solid #990000;\"><tr><td class=\"trlight\">");
                output("`7He ain't kidding - Improbable Island doesn't spam.  Your E-mail address is used to recover your password if you forget it, and (optionally) to let you know if someone sends you a message in-game - that's it.  We don't use it for anything else, and we never let anyone else see it.`n`nOr, you can continue without entering an E-mail address - but you won't be notified of anything, and you won't be able to recover your password if you lose it!`n");
                rawoutput("<form action='runmodule.php?module=homepage&op=3&override=1&r={$r}' method='POST'\"><input name='email' type='hidden' value='Not Given'>");
                rawoutput("<input type='hidden' name='name' value=\"{$name}\">");
                rawoutput("<input type='hidden' name='gender' value=\"{$sex}\">");
                rawoutput("<br /><div align=\"center\"><input type='submit' value='Continue without an E-mail address' class='button'></div></form>");
                rawoutput("</td></tr></table>");
                addnav("", "runmodule.php?module=homepage&op=3&override=1&r=" . $r);
            }
            break;
        case 4:
            output("`0The thing steps out from behind the trees.  Its chitinous body is thin, shiny, and angular.  There are no hands or feet; its legs and arms terminate in sharp points.  Each time it takes a step, it leaves a deep, round piercing in the ground.  You back up against the gatekeeper's hut, unable to take your eyes off the beast.`n`n");
            if ($passlen <= 3) {
                output("\"`6I'm not sure you heard me right, mate,`0\" says the gatekeeper quietly from behind you.  \"`6I need four characters or more.  No rush.`0\"`n`n");
                $tryagain = true;
            }
            if ($pass1 != $pass2) {
                output("\"`6Sorry, mate, I think I heard two different things,`0\" says the gatekeeper quietly from behind you.  \"`6Wanna repeat that?  No rush.`0\"`n`n");
                $tryagain = true;
            }
            if ($tryagain) {
                rawoutput("<script language='JavaScript' src='lib/md5.js'></script>");
                rawoutput("<script language='JavaScript'>\r\n\t\t\t\t<!--\r\n\t\t\t\tfunction md5pass(){\r\n\t\t\t\t\t// encode passwords\r\n\t\t\t\t\tvar plen = document.getElementById('passlen');\r\n\t\t\t\t\tvar pass1 = document.getElementById('pass1');\r\n\t\t\t\t\tplen.value = pass1.value.length;\r\n\r\n\t\t\t\t\tif(pass1.value.substring(0, 5) != '!md5!') {\r\n\t\t\t\t\t\tpass1.value = '!md5!'+hex_md5(pass1.value);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tvar pass2 = document.getElementById('pass2');\r\n\t\t\t\t\tif(pass2.value.substring(0, 5) != '!md5!') {\r\n\t\t\t\t\t\tpass2.value = '!md5!'+hex_md5(pass2.value);\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t}\r\n\t\t\t\t//-->\r\n\t\t\t\t</script>");
                if (httpget('override')) {
                    rawoutput("<form action='runmodule.php?module=homepage&op=4&override=1&r={$r}' method='POST' onSubmit=\"md5pass();\">");
                } else {
                    rawoutput("<form action='runmodule.php?module=homepage&op=4&r={$r}' method='POST' onSubmit=\"md5pass();\">");
                }
                rawoutput("<input type='hidden' name='passlen' id='passlen' value='0'>");
                rawoutput("<input type='hidden' name='name' value=\"{$name}\">");
                rawoutput("<input type='hidden' name='gender' value=\"{$sex}\">");
                rawoutput("<input type='hidden' name='email' value=\"{$email}\">");
                output("\"`#`iSeriously, mate,`i just put down ");
                rawoutput("<input type='password' name='pass1' id='pass1'>");
                output(".`0\"`n`nThe gatekeeper scribbles on his form.  \"`6Sorry, just run that past me again?`0\"`n`n\"`#I said ");
                rawoutput("<input type='password' name='pass2' id='pass2'>");
                output("!`0\"`n`n");
                rawoutput("<div align=\"center\"><input type='submit' value='Now let me in, damn it!' class='button'></div></form>");
            } else {
                //perform a final test on all supplied information, as in create.php
                //password already checked
                $createaccount = 1;
                //check name
                $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE login='******'";
                $result = db_query($sql);
                //name exists
                if (db_num_rows($result) > 0) {
                    output("name");
                    $createaccount = 0;
                }
                //name too short or too long
                if (strlen($name) < 3 || strlen($name) > 25) {
                    output("name");
                    $createaccount = 0;
                }
                //gender not set
                if ($sex != 1 && $sex != 0) {
                    output("sex is %s", $sex);
                    $createaccount = 0;
                }
                //email
                if (!httpget('override')) {
                    //not overriden
                    //not an E-mail address
                    if (!is_email($email)) {
                        $createaccount = 0;
                        output("email not an email");
                    }
                    //already exists
                    $sql = "SELECT login FROM " . db_prefix("accounts") . " WHERE emailaddress='{$email}'";
                    $result = db_query($sql);
                    if (db_num_rows($result) > 0) {
                        $createaccount = 0;
                        output("email found already");
                    }
                }
                $args = modulehook("check-create", httpallpost());
                if (isset($args['blockaccount']) && $args['blockaccount']) {
                    $msg .= $args['msg'];
                    $createaccount = 0;
                }
                if ($createaccount) {
                    //create the account
                    require_once "lib/titles.php";
                    $title = get_dk_title(0, $sex);
                    $refer = httpget('r');
                    if ($refer > "") {
                        $sql = "SELECT acctid FROM " . db_prefix("accounts") . " WHERE login='******'";
                        $result = db_query($sql);
                        $ref = db_fetch_assoc($result);
                        $referer = $ref['acctid'];
                    } else {
                        $referer = 0;
                    }
                    $dbpass = "";
                    if (substr($pass1, 0, 5) == "!md5!") {
                        $dbpass = md5(substr($pass1, 5));
                    } else {
                        $dbpass = md5(md5($pass1));
                    }
                    $sql = "INSERT INTO " . db_prefix("accounts") . "\r\n\t\t\t\t\t\t(name, superuser, title, password, sex, login, laston, uniqueid, lastip, gold, emailaddress, emailvalidation, referer, regdate, race, location)\r\n\t\t\t\t\t\tVALUES\r\n\t\t\t\t\t\t('{$title} {$name}', '" . getsetting("defaultsuperuser", 0) . "', '{$title}', '{$dbpass}', '{$sex}', '{$name}', '" . date("Y-m-d H:i:s", strtotime("-1 day")) . "', '" . $_COOKIE['lgi'] . "', '" . $_SERVER['REMOTE_ADDR'] . "', " . getsetting("newplayerstartgold", 50) . ", '{$email}', '{$emailverification}', '{$referer}', NOW(), 'Human', 'NewHome')";
                    db_query($sql);
                    if (db_affected_rows(LINK) <= 0) {
                        output("`\$Error`^: Your account was not created for an unknown reason, please try again. ");
                    } else {
                        $sql = "SELECT acctid FROM " . db_prefix("accounts") . " WHERE login='******'";
                        $result = db_query($sql);
                        $row = db_fetch_assoc($result);
                        $args = httpallpost();
                        $args['acctid'] = $row['acctid'];
                        //insert output
                        $sql_output = "INSERT INTO " . db_prefix("accounts_output") . " VALUES ({$row['acctid']},'');";
                        db_query($sql_output);
                        //end
                        modulehook("process-create", $args);
                        //Project Wonderful Conversion Code
                        $pwcode = "<!-- Beginning of Project Wonderful conversion code: -->\r\n\t\t\t\t\t\t<!-- Conversion Track ID: 12 -->\r\n\t\t\t\t\t\t<script type=\"text/javascript\">\r\n\t\t\t\t\t\t<!--var d=document;\r\n\t\t\t\t\t\td.projectwonderful_conversion_id = \"12\";\r\n\t\t\t\t\t\td.projectwonderful_label = \"\";\r\n\t\t\t\t\t\td.projectwonderful_value = \"\";\r\n\t\t\t\t\t\t//-->\r\n\t\t\t\t\t\t</script>\r\n\t\t\t\t\t\t<script type=\"text/javascript\" \r\n\t\t\t\t\t\tsrc=\"http://www.projectwonderfuladservices.com/conversion.js\">\r\n\t\t\t\t\t\t</script>\r\n\t\t\t\t\t\t<!-- End of Project Wonderful ad code. -->";
                        rawoutput($pwcode);
                        if ($emailverification != "") {
                            $subj = translate_mail("LoGD Account Verification", 0);
                            $msg = translate_mail(array("Login name: %s `n`nIn order to verify your account, you will need to click on the link below.`n`n http://%s?op=val&id=%s `n`nThanks for playing!", $shortname, $_SERVER['SERVER_NAME'] . ($_SERVER['SERVER_PORT'] == 80 ? "" : ":" . $_SERVER['SERVER_PORT']) . $_SERVER['SCRIPT_NAME'], $emailverification), 0);
                            mail($email, $subj, str_replace("`n", "\n", $msg), "From: " . getsetting("gameadminemail", "*****@*****.**"));
                            output("`4An email was sent to `\$%s`4 to validate your address.  Click the link in the email to activate your account.`0`n`n", $email);
                        } else {
                            output("\"`#`iLET ME IN!  RIGHT THE HELL NOW!`i`0\"`n`n\"`6Hmm?`0\"  The gatekeeper looks up from his forms.  \"`6Oh!  Yes, I see what you mean.  Wow!`0\" he smiles, as the beast plods closer.  \"`6That's a big one!  Geez, look at the `isize`i of 'im!`0\"`n`n\"`#`iPlease!`i`0\"`n`n\"`6Oh, oh, yes.  Of course.`0\"  He pulls a lever, and the outpost gates swing open.  \"`6In you go, then.`0\"`n`nYou tear through the gates and into the Outpost.`n`nThe gatekeeper chuckles.  \"`6Nice one, Harry!`0\"`n`nGrinning, the monster takes a bow.  \"`4It `inever`i gets old, this,`0\" it says in a broad Yorkshire accent. \"`4You in the pub later?`0\"`n`n\"`6Of course, it's darts night.`0\"`n`n\"`4Right-ho, then.  Ta-raa.`0\"`n`n\"`6See you, Harry.`0\"  The gatekeeper sits back in his chair, lights a cigarette, and carries on with his crossword.`n");
                            rawoutput("<div align='center'><form action='login.php' method='POST'>");
                            rawoutput("<input name='name' value=\"{$name}\" type='hidden'>");
                            rawoutput("<input name='password' value=\"{$pass1}\" type='hidden'>");
                            $click = translate_inline("Venture into Improbable Island!");
                            rawoutput("<input type='submit' class='button' value='{$click}'>");
                            rawoutput("</form></div>");
                            output_notl("`n");
                            savesetting("newestplayer", $row['acctid']);
                        }
                    }
                } else {
                    output("Whoops!  Did you use the back and/or forward buttons?  It looks like your account is already set up.  Head back to the home page and log yourself in!");
                    addnav("D'oh!");
                    addnav("Back to the homepage", "home.php");
                }
            }
            break;
    }
    if ($name) {
        addnav("Character Information");
        addnav(array("Character name: %s", $name), "");
        if (httpget('op') != 1 && httpget('op') != 0) {
            if ($sex) {
                addnav("Gender: Female", "");
            } else {
                if (isset($sex)) {
                    addnav("Gender: Male", "");
                }
            }
            if ($email) {
                addnav(array("E-mail address: %s", $email), "");
            }
        }
    }
    page_footer();
    return true;
}