function drunkard_runevent($type)
{
    global $session;
    require_once "lib/partner.php";
    $partner = get_partner();
    $chance = get_module_setting("spillchance");
    $roll = e_rand(1, 100);
    $seen = get_module_pref("seen");
    set_module_pref("seen", $seen + 1);
    output("`5A very drunk patron stumbles into you as you make your way across the crowded room.`n`n");
    if ($roll < $chance) {
        // He spills on you
        output("`5He is carrying a nearly full glass of ale.");
        output("As he collides with you, it spills all over your nearly clean clothes!");
        output("As you look up, you notice %s`5 watching you and become acutely embarrassed.", $partner);
        output("You notice %s`5 is trying to keep from laughing out loud at your mishap.", $partner);
        output("`n`n`&You `\$lose 1`& charm point.");
        if ($session['user']['charm'] > 0) {
            $session['user']['charm']--;
        }
    } else {
        // You're safe
        output("`5Fortunately his glass was already empty.");
        output("You escort him over to a chair where he can sit without running into everyone else.");
        output("As you stand up, you catch %s's`5 eye and receive a big smile for your kindness.", $partner);
        output("`n`n`&You gain `^1`& charm.");
        $session['user']['charm']++;
    }
}
function creatureaddon_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "gravefight-start":
            if (get_module_objpref("creatures", $args['creatureid'], "description")) {
                output(stripslashes(get_module_objpref("creatures", $args['creatureid'], "description")));
            }
            break;
        case "creatureencounter":
            $args['creaturegold'] += get_module_objpref("creatures", $args['creatureid'], "addgold");
            $args['creaturehealth'] += get_module_objpref("creatures", $args['creatureid'], "addhit");
            $args['creatureattack'] += get_module_objpref("creatures", $args['creatureid'], "addattack");
            $args['creaturedefense'] += get_module_objpref("creatures", $args['creatureid'], "adddefense");
            if (get_module_objpref("creatures", $args['creatureid'], "image")) {
                rawoutput("<table width = \"100%\"><tr><td width=\"100%\" align = \"center\"><img src=\"./images/" . get_module_objpref("creatures", $args['creatureid'], "image") . "\"></td></tr></table>");
            }
            if (get_module_objpref("creatures", $args['creatureid'], "description") && !httpget("nodesc")) {
                output(stripslashes(get_module_objpref("creatures", $args['creatureid'], "description")));
            }
            break;
        case "battle-victory":
            if ($session['user']['level'] < 15 && e_rand(1, 100) <= get_module_objpref("creatures", $args['creatureid'], "gemchance") && get_module_objpref("creatures", $args['creatureid'], "gemmessage")) {
                $message = get_module_objpref("creatures", $args['creatureid'], "gemmessage");
                output($message);
                debug("Creature Addon module is awarding a gem.");
                $session['user']['gems']++;
                debuglog("found a gem when slaying a " . $args['creaturename']);
            }
            break;
    }
    return $args;
}
function forestturn_runevent($type)
{
    global $session;
    // The only type of event we care about are the forest.
    $chance = get_module_setting("percentgain");
    $roll = e_rand(1, 100);
    if ($roll <= $chance) {
        output("`^You discover a skin of liquid hanging over the limb of a tree.");
        output("Since the sigils inscribed on the skin are those of someone you recognize as a very powerful warrior from the village, you decide that it would be safe to take a sip.`n`n`n");
        output("Man is that stuff potent!");
        output("You feel `!hyper`^.`n`n");
        output("You `%receive one`^ extra turn!`0");
        $session['user']['turns']++;
    } else {
        output("`^Walking along a path in the forest, you come upon a field of flowers.");
        output("Stopping to pick one, you inhale its scent.`n`n");
        output("`\$Yawn!");
        output("`^Man, that flower scent made you really sleepy.");
        output("You stumble off the path to take a nap.`n`n");
        if ($session['user']['turns'] > 0) {
            output("You `%lose one `^turn!`0");
            $session['user']['turns']--;
        }
    }
}
function binarypuzzle_run()
{
    global $session;
    page_header("Binary Puzzle Thing!");
    addnav("O?Back to the Outpost", "village.php");
    switch (httpget('op')) {
        case "start":
            //first set up the board
            $switches = array(1 => array("val" => 1, "status" => 0), 2 => array("val" => 2, "status" => 0), 3 => array("val" => 4, "status" => 0), 4 => array("val" => 8, "status" => 0), 5 => array("val" => 16, "status" => 0), 6 => array("val" => 32, "status" => 0), 7 => array("val" => 64, "status" => 0), 8 => array("val" => 128, "status" => 0));
            shuffle($switches);
            set_module_pref("switches", serialize($switches));
            //Now set up the clues
            $clues = array();
            for ($i = 1; $i <= 8; $i++) {
                $toprange = $i * 32;
                $bottomrance = $toprange - 32;
                $clues[$i] = e_rand($bottomrange, $toprange);
            }
            $goal = e_rand(129, 255);
            set_module_pref("clues", serialize($clues));
            binarypuzzle_show($switches, $goal);
            break;
        case "switch":
            $sw = httpget('switch');
            $goal = httpget('goal');
            $switches = binarypuzzle_switch($sw);
            binarypuzzle_show($switches, $goal);
            break;
    }
    page_footer();
}
function pubjokes_runevent($type)
{
    global $session;
    $jokenum = e_rand(1, 8);
    $landlord = getsetting("barkeep", "`)Cedrik");
    switch ($jokenum) {
        case 1:
            output("A tall, hairy man enters the pub and strolls over to the bar.  The frog sulking on the top of his bald head draws some stares.  %s looks him up and down, and after a moment's thought, nods up at the frog and asks \"So, mate - where did you get that?\"`n\"Well, it started off as a wart on my arse,\" says the frog.`n`n", $landlord);
            break;
        case 2:
            output("A small, mottled brown duck walks into the pub.  He waddles over to the bar, hops onto a stool, and fixes %s with an intense stare.  You watch closely, knowing that the two are about to face off in a battle of wits.`n\"Got any bread?\" asks the duck.`n\"No,\" replies %s.`n\"Got any bread?\" asks the duck.`n\"No,\" replies %s.`n\"Got any bread?\"`n\"No.\"`n\"Got any bread?\"`n\"No.\"`n\"Got any bread?\"`n\"No.\"`n\"Got any bread?\"`n\"`iNo.`i\"`n\"Got any bread?\"`n\"NO!\"`n\"Got any bread?\"`n\"No, and the next time you ask, I'm going to nail your damned beak to this bar.\"`nThe duck looks up at %s's fierce expression, and appears to reach a decision.`n\"Got any nails?\"`n\"No.\"`n\"Got any bread?\"`n%s's hands move too fast for you to see, but the loud hammering sound and the squeals of indignant quacking pain serve to paint you a pretty good picture.`n\"I lied about the nails,\" says %s with a smile, and goes back to serving drinks.`n`n", $landlord, $landlord, $landlord, $landlord, $landlord, $landlord);
            break;
        case 3:
            output("A severely drunk man blunders past you, laughing and slurring \"ALL MIDGETS ARE BASTARDS!\"`nA figure lurking in the shadows at the corners of the pub calls after him: \"Hey, I take offense at that!\"`nThe drunkard turns around and slurs back, \"Why, mate, 're you a Midget or summat?\"`n\"No, I'm a bastard.\"`n`n");
            break;
        case 4:
            output("A very attractive woman walks up to the bar. She gestures alluringly to Mick, the assistant bartender, who comes over immediately.  When he arrives, she seductively signals that he should bring his face closer to hers. When he does so, she begins to gently caress his full beard.`n\"Are you %s?\", she asks, softly stroking his face with both hands.`n\"Actually, no,\" he replies.\"Can you get him for me? I need to speak to him,\" she says, running her hands beyond his beard and into his hair.`n\"He's just downstairs changing the barrels,\" breathes Mick. \"Is there anything I can do?\"`n\"Yes, there is. I need you to give him a message,\" she continues, slyly popping a couple of her fingers into his mouth and allowing him to suck them gently.`n\"Wh-what should I tell him?\" Mick somehow manages to stammer, his ears as red as emergency flares.`n\"Tell him,\" she whispers, \"There is no toilet paper or hand soap in the ladies room.\"`n`n", $landlord);
            break;
        case 5:
            output("A wriggling SpiderKitty prances over to the bar, climbs up onto a stool and asks for a beer.  %s begins to pour, chuckling.  \"You know,\" he says, \"I named this pub after you.\"`n\"What,\" says the prancing SpiderKitty, \"You named your pub Dave?\"`n`n", $landlord);
            break;
        case 6:
            output("A horse walks into the pub and up to the bar.  %s says, \"Why the long face?\"`nThe horse shrugs. \"Crap jokes, mainly.\"`n\"Ah.\"`n`n", $landlord);
            break;
        case 7:
            output("A man walks in to the pub.  %s, seeing him, pulls his shotgun from under the bar.  \"OUT!\" he shouts.  \"YOU BLOODY WELL KNOW YOU'VE BEEN BARRED!\"`nAs the man sheepishly leaves, you ask %s what the problem was.  He turns to you, shaking his head.`n\"The sign that said \"Wet Floor\" was supposed to be a `icaution`i, not a request.\"`nYou wondered why your boots were sticking so bad.`n`n", $landlord, $landlord);
            break;
        case 8:
            output("You notice a man quite the worse for wear, staggering out of the pub with his pet giraffe in tow - similarly inebriated, the giraffe falls over onto its side, and the man keeps walking.  %s calls after him - \"Hey!  You can't leave that lyin' there!\"`nThe man turns around and gets as far as \"It's not a lion, it's a...\" before the lion bursts from its disguise and drags him screaming into the jungle.  The regulars shrug and go back to their pints.`n`n", $landlord);
            break;
    }
}
function zapgrenade_use($args)
{
    global $session;
    debug("Applying Zap Grenade buff");
    apply_buff('zapgrenade', array("startmsg" => "`3You pull the pin on your grenade and toss it at {badguy}`3, shielding your eyes.  After a blinding flash, your foe is left dazed and confused!", "name" => "`^ZAP Grenade", "rounds" => e_rand(3, 7), "badguyatkmod" => 0.1, "badguydefmod" => 0.1, "roundmsg" => "{badguy} is blinded, deafened and thoroughly confused, and flails wildly while you pummel it!", "wearoff" => "{badguy}`3 feels some coherence return, and lunges at you!", "expireafterfight" => 1, "schema" => "iitems-catcher"));
    return $args;
}
function worldmapen_defaultcityloc()
{
    global $session;
    $i = 0;
    $citylocX = 0;
    $citylocY = 0;
    $citylocations = array();
    $citylocations[][] = "";
    $vloc = array();
    $vname = getsetting("villagename", LOCATION_FIELDS);
    $vloc[$vname] = "village";
    $vloc = modulehook("validlocation", $vloc);
    foreach ($vloc as $loc => $val) {
        $k = 0;
        while ($k == 0) {
            foreach ($citylocations as $val1) {
                if ($val1[0] == $citylocX && $val1[1] == $citylocY) {
                    $k = 0;
                    $citylocX = e_rand(1, get_module_setting("worldmapsizeX"));
                    $citylocY = e_rand(1, get_module_setting("worldmapsizeY"));
                } else {
                    $k++;
                    $citylocations[$i][0] = $citylocX;
                    $citylocations[$i][1] = $citylocY;
                    set_module_setting($loc . 'X', $citylocX);
                    set_module_setting($loc . 'Y', $citylocY);
                    set_module_setting($loc . 'Z', "1");
                }
            }
        }
        $i++;
    }
}
function lovers_chat_seth()
{
    global $session;
    if (httpget("act") == "") {
        output("You make your way over to where %s`0 is sitting, ale in hand.", getsetting("bard", "`^Seth"));
        output("Sitting down, and waiting for %s`0 to finish a song, you light your pipe.", getsetting("bard", "`^Seth"));
        addnav("Ask about your manliness", "runmodule.php?module=lovers&op=chat&act=armor");
        addnav("Discuss Sports", "runmodule.php?module=lovers&op=chat&act=sports");
    } elseif (httpget("act") == "sports") {
        output("You and %s`0 spend some time talking about the recent dwarf tossing competition.", getsetting("bard", "`^Seth"));
        output("Not wanting to linger around another man for too long, so no one \"wonders\", you decide you should find something else to do.");
    } else {
        $charm = $session['user']['charm'] + e_rand(-1, 1);
        output("%s`0 looks you up and down very seriously.", getsetting("bard", "`^Seth"));
        output("Only a friend can be truly honest, and that is why you asked him.");
        switch ($charm) {
            case -3:
            case -2:
            case -1:
            case 0:
                $msg = translate_inline("You make me glad I'm not gay!");
                break;
            case 1:
            case 2:
            case 3:
                $msg = translate_inline("I've seen some handsome men in my day, but I'm afraid you aren't one of them.");
                break;
            case 4:
            case 5:
            case 6:
                $msg = translate_inline("I've seen worse my friend, but only trailing a horse.");
                break;
            case 7:
            case 8:
            case 9:
                $msg = translate_inline("You're of fairly average appearance my friend.");
                break;
            case 10:
            case 11:
            case 12:
                $msg = translate_inline("You certainly are something to look at, just don't get too big of a head about it, eh?");
                break;
            case 13:
            case 14:
            case 15:
                $msg = translate_inline("You're quite a bit better than average!");
                break;
            case 16:
            case 17:
            case 18:
                $msg = translate_inline("Few women would be able to resist you!");
                break;
            default:
                $msg = translate_inline("I hate you, why, you are simply the most handsome man ever!");
        }
        output("Finally he reaches a conclusion and states, \"%s`0\"", $msg);
    }
}
function lottery_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "newday":
            $numbers = get_module_setting("todaysnumbers");
            $n = $numbers;
            output("`n`@Today's lottery numbers are `^%s-%s-%s-%s`0`n", $n[0], $n[1], $n[2], $n[3]);
            $roundnum = get_module_setting("roundnum");
            $pround = get_module_pref("roundnum");
            if ($roundnum > $pround) {
                if (get_module_pref("pick") === $numbers) {
                    $prize = get_module_setting("prize");
                    if ($prize > "" && $pround < $roundnum) {
                        rawoutput("<font size='+1'>");
                        output("`\$You won today's lottery!`0`n");
                        rawoutput("</font>");
                        output("`\$The jackpot is `^^%s`\$ gold, money that has been deposited in to your bank account!`n", $prize);
                        $session['user']['goldinbank'] += $prize;
                        debuglog("won {$prize} gold on lottery");
                        addnews("`@%s`@ won `^%s`@ gold in the lottery!`0", $session['user']['name'], $prize);
                    }
                }
                set_module_pref("pick", "");
            }
            break;
        case "newday-runonce":
            $numbers = array();
            for ($i = 0; $i < 4; $i++) {
                $numbers[$i] = e_rand(0, 9);
            }
            sort($numbers);
            set_module_setting("todaysnumbers", join("", $numbers));
            $sql = "SELECT count(*) AS c FROM " . db_prefix("module_userprefs") . " WHERE modulename='lottery' AND setting='pick' AND value='" . join("", $numbers) . "'";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            if ($row['c'] > 0) {
                //split the jackpot among winners.
                $prize = round(get_module_setting("currentjackpot") / $row['c'], 0);
                set_module_setting("prize", $prize);
                set_module_setting("currentjackpot", get_module_setting("basepot"));
                set_module_setting("howmany", $row['c']);
            } else {
                //the jackpot rolls over.
                set_module_setting("prize", 0);
                set_module_setting("howmany", 0);
            }
            set_module_setting("roundnum", get_module_setting("roundnum") + 1);
            break;
        case "inn":
            addnav("Things to do");
            addnav(array("%s`0's Lottery", getsetting('barkeep', '`tCedrik')), "runmodule.php?module=lottery&op=store");
            break;
    }
    return $args;
}
function lights_out_run()
{
    global $session;
    page_header("Lights Out!");
    addnav("O?Back to the Outpost", "village.php");
    //playtesting
    $numlights = 9;
    $lightsperrow = 3;
    $startlights = 5;
    $maxchangesperlight = 4;
    switch (httpget('op')) {
        case "start":
            $lights = array();
            for ($lamp = 1; $lamp <= 9; $lamp++) {
                $lights[$lamp]['status'] = 0;
                $numberofchanges = e_rand(2, 4);
                $lampstochange = array(1 => "1", 2 => "2", 3 => "3", 4 => "4", 5 => "5", 6 => "6", 7 => "7", 8 => "8", 9 => "9");
                unset($lampstochange[$lamp]);
                $switches = array();
                for ($c = 1; $c <= $numberofchanges; $c++) {
                    $sw = array_rand($lampstochange);
                    $switches[] = $sw;
                    unset($lampstochange[$sw]);
                }
                $lights[$lamp]['changes'] = $switches;
            }
            debug($lights);
            //Now randomly poke some lights
            for ($i = 1; $i <= $startlights; $i++) {
                $sw = e_rand(1, $numlights);
                $lights = lights_out_switch($sw, $lights);
            }
            $spref = serialize($lights);
            set_module_pref("lights", $spref);
            $moves = 0;
            $jackpot = 200;
            lights_out_show($lights, $moves, $jackpot);
            break;
        case "switch":
            $moves = httpget('moves');
            $moves++;
            $jackpot = httpget('jackpot');
            output("Current jackpot: %s`n", $jackpot);
            $lights = lights_out_switch(httpget('switch'));
            $jackpot += 5;
            lights_out_show($lights, $moves, $jackpot);
            $lit = lights_out_check($lights);
            if (!$lit) {
                output("Congratulations!  You won %s Req, for your stake of %s!", $jackpot, $moves * 10);
            } else {
                output("There are %s lights left to turn off.  You have made %s moves.`n", $lit, $moves);
            }
            break;
    }
    page_footer();
}
function findgold_runevent($type, $link)
{
    global $session;
    $min = $session['user']['level'] * get_module_setting("mingold");
    $max = $session['user']['level'] * get_module_setting("maxgold");
    $gold = e_rand($min, $max);
    output("`^Fortune smiles on you and you find %s gold!`0", $gold);
    $session['user']['gold'] += $gold;
    debuglog("found {$gold} gold in the dirt");
}
function drinks_drunkenize($commentary, $level)
{
    if (get_module_pref("noslur")) {
        return $commentary;
    }
    $straight = $commentary;
    $replacements = 0;
    while ($replacements / strlen($straight) < $level / 500) {
        $slurs = array("a" => "aa", "e" => "ee", "f" => "ff", "h" => "hh", "i" => "iy", "l" => "ll", "m" => "mm", "n" => "nn", "o" => "oo", "r" => "rr", "s" => "sss", "u" => "oo", "v" => "vv", "w" => "ww", "y" => "yy", "z" => "zz");
        if (e_rand(0, 9)) {
            $letter = array_rand($slurs);
            $x = strpos(strtolower($commentary), $letter);
            if ($x !== false && substr($commentary, $x, 5) != "*hic*" && substr($commentary, max($x - 1, 0), 5) != "*hic*" && substr($commentary, max($x - 2, 0), 5) != "*hic*" && substr($commentary, max($x - 3, 0), 5) != "*hic*" && substr($commentary, max($x - 4, 0), 5) != "*hic*") {
                if (substr($commentary, $x, 1) != strtolower($letter)) {
                    $slurs[$letter] = strtoupper($slurs[$letter]);
                } else {
                    $slurs[$letter] = strtolower($slurs[$letter]);
                }
                $commentary = substr($commentary, 0, $x) . $slurs[$letter] . substr($commentary, $x + 1);
                $replacements++;
            }
        } else {
            $x = e_rand(0, strlen($commentary));
            // Skip the ` followed by a letter
            if (substr($commentary, $x - 1, 1) == "`") {
                $x += 1;
            }
            if (substr($commentary, $x, 5) == "*hic*") {
                $x += 5;
            }
            if (substr($commentary, max($x - 1, 0), 5) == "*hic*") {
                $x += 4;
            }
            if (substr($commentary, max($x - 2, 0), 5) == "*hic*") {
                $x += 3;
            }
            if (substr($commentary, max($x - 3, 0), 5) == "*hic*") {
                $x += 2;
            }
            if (substr($commentary, max($x - 4, 0), 5) == "*hic*") {
                $x += 1;
            }
            $commentary = substr($commentary, 0, $x) . "*hic*" . substr($commentary, $x);
            $replacements++;
        }
        //end if
    }
    //end while
    //get rid of spare *'s in *hic**hic*
    while (strpos($commentary, "*hic**hic*")) {
        $commentary = str_replace("*hic**hic*", "*hic*hic*", $commentary);
    }
    return $commentary;
}
function quest_rohit_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "worldnav":
            if (get_module_pref("plotpoint1") && !get_module_pref("plotpoint2") && e_rand(0, 100) < 10 && $session['user']['race'] != "Robot") {
                redirect("runmodule.php?module=quest_rohit&op=plotpoint2", "Redirecting to Rohit Plot Point 2 from World Map");
            }
            break;
    }
    return $args;
}
function mountrarity_dohook($hookname, $args)
{
    switch ($hookname) {
        case "newday-runonce":
            $sql = "SELECT mountid FROM " . db_prefix("mounts") . " WHERE mountactive=1";
            $result = db_query($sql);
            while ($row = db_fetch_assoc($result)) {
                $id = $row['mountid'];
                $rarity = get_module_objpref("mounts", $id, "rarity");
                if (e_rand(1, 100) > $rarity) {
                    set_module_objpref("mounts", $id, "unavailable", 1);
                } else {
                    // You need to reset the availability if it's not unavailable
                    // otherwise, it never becomes available again!
                    set_module_objpref("mounts", $id, "unavailable", 0);
                }
            }
            break;
        case "mountfeatures":
            $rarity = get_module_objpref("mounts", $args['id'], "rarity");
            $args['features']['Rarity'] = $rarity;
            break;
        case "stables-desc":
            if (get_module_setting("showout")) {
                $sql = "SELECT mountid, mountname FROM " . db_prefix("mounts") . " WHERE mountactive=1";
                $result = db_query($sql);
                output("`nA sign by the door proclaims that the following mounts are out of stock for today:");
                while ($row = db_fetch_assoc($result)) {
                    $out = get_module_objpref("mounts", $row['mountid'], "unavailable");
                    if ($out) {
                        output("`n%s", $row['mountname']);
                    }
                }
            } else {
                output("`nIf you don't see something you like today, perhaps you should check again tomorrow.");
            }
            break;
        case "stables-nav":
            $sql = "SELECT mountid FROM " . db_prefix("mounts") . " WHERE mountactive=1";
            $result = db_query($sql);
            while ($row = db_fetch_assoc($result)) {
                $id = $row['mountid'];
                $out = get_module_objpref("mounts", $id, "unavailable");
                if ($out) {
                    blocknav("stables.php?op=examine&id={$id}");
                }
            }
            break;
    }
    return $args;
}
function heidi_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "village":
            $allowgift = get_module_setting("allowgift");
            $allowdp = get_module_setting("allowdp");
            $changeallowed = get_module_setting("changeallowed");
            // disable for farmies lower than level 10
            if (($allowgift || $allowdp || $changeallowed > 0) && ($session['user']['dragonkills'] > 0 || $session['user']['level'] >= 10)) {
                tlschema($args['schemas']['marketnav']);
                addnav($args['marketnav']);
                tlschema();
                addnav("H?Heidi's Place", "runmodule.php?module=heidi");
            }
            break;
        case "newday":
            if ($args['resurrection'] != 'true') {
                set_module_pref("pvpchange", 0);
            }
            set_module_pref("pendingdp", 0);
            $turns = getsetting("turns", 10) + $session['user']['spirits'];
            reset($session['user']['dragonpoints']);
            while (list($key, $val) = each($session['user']['dragonpoints'])) {
                if ($val == "ff") {
                    $turns++;
                }
            }
            set_module_pref("newdayturns", $turns);
            $echance = e_rand(0, 100);
            $mult = e_rand(200, 400);
            $addgold = round($mult * ($session['user']['level'] / max(10, $session['user']['dragonkills'])));
            if ($session['user']['dragonkills'] < 6) {
                $addgold * 1.5;
            }
            if ($echance >= get_module_setting("findperc")) {
                $addgold = 0;
            }
            set_module_pref("addgold", $addgold);
            if ($addgold > 1) {
                // they are a recipient
                $session['user']['gold'] += $addgold;
                output("`n`5Beside your pillow is a small leather bag containing %s gold, and a note: `^Blessings to ye, child, for someone cared enough to send ye a gift.", $addgold);
                output("`5Wondering who it is from, you add it to your purse.`n");
                debuglog("gained {$addgold} gold from an anonymous gift.");
            }
            break;
    }
    return $args;
}
function klutz_runevent($type)
{
    global $session;
    output("`7While you're minding your own business, a lady plows headlong into you.`n`n");
    output("`&\"Oh! Oh, I'm terribly sorry! I mustn't have been watching where I was going...\"`n`n");
    output("`7She scrambles on the ground, trying to collect all the things she has dropped.");
    output("You help her gather her belongings.`n`n");
    output("`^She is most grateful for your help!`n`n");
    if (get_module_pref("gotgem") == 0 && e_rand(1, 4) == 1) {
        output("`7As a thank you, she hands you a `5gem`7!");
        $session['user']['gems']++;
        set_module_pref("gotgem", 1);
    }
}
function improbabilitybomb_use($args)
{
    global $session;
    $effect = e_rand(1, 8);
    if (has_buff("ibomb7a") && $effect == 7) {
        $effect = 3;
    }
    if (has_buff("ibomb8") && $effect == 8) {
        $effect = 3;
    }
    apply_buff('startmsg', array("rounds" => 1, "atkmod" => 1, "startmsg" => "`0You light the fuse on the Improbability Bomb and toss it towards your opponent.", "schema" => "improbabilitybomb"));
    switch ($effect) {
        case 1:
            apply_buff('ibomb1', array("rounds" => 1, "atkmod" => 1, "startmsg" => "`0The bomb bursts into a shower of Requisition tokens!  Blimey, there must be about a thousand of them!  What's more, all these tokens are swirling into the air and nose-diving straight into your pocket.  Result!", "schema" => "improbabilitybomb"));
            $gold = e_rand(900, 1100);
            $session['user']['gold'] += $gold;
            break;
        case 2:
            apply_buff('ibomb2', array("rounds" => 1, "atkmod" => 1, "startmsg" => "`0The fuse fizzes and sparks, until eventually... it goes out.  The bomb is gone.  However, there's a tasty, tasty cigarette in its place!  You grab it before your enemy gets the chance.", "schema" => "improbabilitybomb"));
            $session['user']['gems']++;
            break;
        case 3:
        case 4:
            apply_buff('ibomb3', array("rounds" => 1, "minioncount" => 1, "minbadguydamage" => "5+round(<attack>*1.0,0);", "maxbadguydamage" => "5+round(<attack>*3.0,0);", "effectmsg" => "`4The bomb explodes close enough to {badguy}`4 to do `^{damage}`4 damage!", "schema" => "improbabilitybomb"));
            break;
        case 5:
            apply_buff('ibomb6', array("rounds" => 1, "atkmod" => 1, "startmsg" => "`0The Improbability Bomb breaks open, bathing you in a cool white light.  When it fades, you feel calm, self-confident and somehow more attractive.  Pretty useless in a combat situation, but hey, it's nice to be feel good about yourself.  You gain some Charm.", "schema" => "improbabilitybomb"));
            $session['user']['charm'] += 1;
            break;
        case 6:
            apply_buff('ibomb7a', array("rounds" => 4, "minioncount" => 8, "minbadguydamage" => 0, "maxbadguydamage" => 5, "startmsg" => "The bomb begins to roll around the theater of combat, bouncing off rocks like a pinball - and firing out showers of white-hot sparks!", "effectmsg" => "`2A glowing spark leaps onto {badguy}, burning it for {damage} points!", "schema" => "improbabilitybomb", "expireafterfight" => 1));
            apply_buff('ibomb7b', array("rounds" => 4, "minioncount" => 8, "mingoodguydamage" => 0, "maxgoodguydamage" => 5, "effectmsg" => "`4A white-hot spark attaches to you, burning you for {damage} points!", "schema" => "improbabilitybomb", "wearoff" => "The bomb fizzles out and sends out one last dying volley of sparks.", "expireafterfight" => 1));
            break;
        case 7:
            apply_buff('ibomb8', array("startmsg" => "`0The bomb uncurls, revealing a little `5Purple Monster!`0", "rounds" => -1, "name" => "`5Purple Monster`0", "minioncount" => 1, "minbadguydamage" => 5, "maxbadguydamage" => 50, "effectmsg" => "`5The Purple Monster leaps towards {badguy} and bites down hard for {damage} damage!`0", "schema" => "improbabilitybomb", "wearoff" => "`5The Purple Monster, seeing its business here concluded, disappears with a faint 'pop.'`0", "expireafterfight" => 1));
            break;
        case 8:
            $maxdmg = $session['user']['maxhitpoints'] * 2;
            if ($maxdmg < 500) {
                $maxdmg = 500;
            }
            $mindmg = $session['user']['hitpoints'] * 0.5;
            if ($maxdmg < 200) {
                $maxdmg = 200;
            }
            apply_buff('ibomb9', array("rounds" => 1, "minioncount" => 1, "mingoodguydamage" => $mindmg, "maxgoodguydamage" => $maxdmg, "effectmsg" => "`4Before the bomb even leaves your hand, it blows up in your face!  The explosion causes {damage} points!", "schema" => "improbabilitybomb", "expireafterfight" => 1));
            break;
    }
    return $args;
}
function select_taunt_array()
{
    global $session, $badguy;
    $sql = "SELECT taunt FROM " . db_prefix("taunts") . " ORDER BY rand(" . e_rand() . ") LIMIT 1";
    $result = db_query($sql);
    if ($result) {
        $row = db_fetch_assoc($result);
        $taunt = $row['taunt'];
    } else {
        $taunt = "`5\"`6%w's mother wears combat boots`5\", screams %W.";
    }
    $taunt = substitute_array($taunt);
    array_unshift($taunt, true, "taunts");
    return $taunt;
}
function extrarandom_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "choosebadguy":
            //If we've seen this creature before, choose a new one
            $pcreatures = @unserialize(get_module_pref("lastcreatures"));
            if (!is_array($pcreatures)) {
                $pcreatures = array();
            }
            if ($args['creatureid'] > 1) {
                global $attempts;
                if (in_array($args['creatureid'], $pcreatures)) {
                    if ($attempts < 3) {
                        //re-roll, getting a creature from the same level
                        debug("We've seen " . $args['creaturename'] . " too recently - switching monster");
                        $lvl = $args['creaturelevel'];
                        $id = $args['creatureid'];
                        if ($args['forest']) {
                            $sql = "SELECT * FROM " . db_prefix("creatures") . " WHERE creaturelevel = {$lvl} AND forest=1 AND creatureid != {$id} ORDER BY rand(" . e_rand() . ") LIMIT 1";
                        } else {
                            if ($args['graveyard']) {
                                $sql = "SELECT * FROM " . db_prefix("creatures") . " WHERE creaturelevel = {$lvl} AND forest=1 AND creatureid != {$id} ORDER BY rand(" . e_rand() . ") LIMIT 1";
                            }
                        }
                        $result = db_query($sql);
                        $args = db_fetch_assoc($result);
                        $attempts++;
                        $args = modulehook("choosebadguy", $args);
                    } else {
                        debug("Screw it!  Too many attempts!");
                    }
                }
                $pcreatures[] = $args['creatureid'];
                $count = count($pcreatures);
                $des = 8;
                if ($count > $des) {
                    for ($i = 0; $i < $count - $des; $i++) {
                        array_shift($pcreatures);
                    }
                }
                set_module_pref("lastcreatures", serialize($pcreatures));
            }
            break;
    }
    return $args;
}
function scrapbots_choose_fighter($army)
{
    debug("Choosing fighter, here is the army:");
    debug($army);
    //get a fighter at random
    $fighter = "none";
    while ($fighter == "none") {
        $bot = e_rand(0, count($army) - 2);
        if (e_rand(1, 100) < $army[$bot]['briskness'] * 10) {
            debug("Fighter Chosen:");
            $fighter = $army[$bot];
            debug($fighter);
        } else {
            debug("Fighter failed Briskness check.  Choosing again.");
        }
    }
    return $fighter;
}
function supplycrates_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "donation":
            $amt = $args['amt'];
            $donationbonus = floor($args['amt'] / get_module_setting("donationaddition"));
            $xmax = get_module_setting("worldmapsizeX", "worldmapen");
            $ymax = get_module_setting("worldmapsizeY", "worldmapen");
            for ($i = 0; $i < $donationbonus; $i++) {
                $x = e_rand(1, $xmax);
                $y = e_rand(1, $ymax);
                $owner = "worldmap_" . $x . "," . $y . ",1";
                give_item("supplycrate", false, $owner);
            }
            break;
    }
    return $args;
}
function improbablestufftrading_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "village":
            tlschema($args['schemas']['marketnav']);
            addnav($args['marketnav']);
            tlschema();
            addnav("eBoy's Trading Station", "runmodule.php?module=improbablestufftrading&op=start");
            break;
        case "newday-runonce":
            //Scramble the prices
            //Set up a loop, one to seven
            for ($i = 0; $i <= 7; $i++) {
                set_module_objpref("city", $i, "smallmedkit-current", e_rand(get_module_objpref("city", $cityid, "smallmedkit-min"), get_module_objpref("city", $cityid, "smallmedkit-max")));
                set_module_objpref("city", $i, "largemedkit-current", e_rand(get_module_objpref("city", $cityid, "largemedkit-min"), get_module_objpref("city", $cityid, "largemedkit-max")));
                set_module_objpref("city", $i, "energydrink-current", e_rand(get_module_objpref("city", $cityid, "energydrink-min"), get_module_objpref("city", $cityid, "energydrink-max")));
                set_module_objpref("city", $i, "nicotinegum-current", e_rand(get_module_objpref("city", $cityid, "nicotinegum-min"), get_module_objpref("city", $cityid, "nicotinegum-max")));
                set_module_objpref("city", $i, "powerpill-current", e_rand(get_module_objpref("city", $cityid, "powerpill-min"), get_module_objpref("city", $cityid, "powerpill-max")));
                set_module_objpref("city", $i, "teleporter-current", e_rand(get_module_objpref("city", $cityid, "teleporter-min"), get_module_objpref("city", $cityid, "teleporter-max")));
                set_module_objpref("city", $i, "banggrenade-current", e_rand(get_module_objpref("city", $cityid, "banggrenade-min"), get_module_objpref("city", $cityid, "banggrenade-max")));
                set_module_objpref("city", $i, "whoomphgrenade-current", e_rand(get_module_objpref("city", $cityid, "whoomphgrenade-min"), get_module_objpref("city", $cityid, "whoomphgrenade-max")));
                set_module_objpref("city", $i, "zapgrenade-current", e_rand(get_module_objpref("city", $cityid, "zapgrenade-min"), get_module_objpref("city", $cityid, "zapgrenade-max")));
                set_module_objpref("city", $i, "repellentspray-current", e_rand(get_module_objpref("city", $cityid, "repellentspray-min"), get_module_objpref("city", $cityid, "repellentspray-max")));
                set_module_objpref("city", $i, "rationpack-current", e_rand(get_module_objpref("city", $cityid, "rationpack-min"), get_module_objpref("city", $cityid, "rationpack-max")));
                set_module_objpref("city", $i, "improbabilitybomb-current", e_rand(get_module_objpref("city", $cityid, "improbabilitybomb-min"), get_module_objpref("city", $cityid, "improbabilitybomb-max")));
                set_module_objpref("city", $i, "kittencard-current", e_rand(get_module_objpref("city", $cityid, "kittencard-min"), get_module_objpref("city", $cityid, "kittencard-max")));
                set_module_objpref("city", $i, "bribe", e_rand(1000, 3000));
                $bribable = e_rand(0, 100);
                if ($bribable < 25) {
                    //eBoy is unbribable
                    set_module_objpref("city", $i, "acceptingbribes", 0);
                } else {
                    if ($bribable > 75) {
                        //eBoy is Bribable - else no change from yesterday
                        set_module_objpref("city", $i, "acceptingbribes", 1);
                    }
                }
            }
            break;
    }
    return $args;
}
function innchat_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "innchatter":
            $id = $session['user']['acctid'];
            if (e_rand(1, 2) == 1) {
                $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE locked=0 AND acctid != '{$id}' ORDER BY rand(" . e_rand() . ") LIMIT 1";
            } else {
                $sql = "SELECT creaturename AS name FROM " . db_prefix("masters") . " WHERE 1 ORDER BY rand(" . e_rand() . ") LIMIT 1";
            }
            // Only let this hit the database once every 10 minute if we're
            // using data caching.  Otherwise it could be expensive.  If they
            // hit it multiple times within ten minutes, it'll use the same
            // random name of player or master.  We'll invalidate the name when someone's name changes
            // for any reason.
            $res = db_query_cached($sql, "innchat-names");
            $row = db_fetch_assoc($res);
            // Give 2 out of X (currently 7 (5+these 2)) chances of hearing about
            // a player.
            $noplayers = translate_inline("loneliness in town");
            if ($row['name'] == "") {
                $row['name'] = $noplayers;
            }
            $args[] = $row['name'];
            $args[] = $row['name'];
            $args[] = translate_inline("Frequently Asked Questions");
            $args[] = translate_inline("dwarf tossing");
            $args[] = translate_inline("YOU");
            $args[] = getsetting("villagename", LOCATION_FIELDS);
            $args[] = translate_inline("today's weather");
            $args[] = translate_inline("the elementary discord of being");
            // "Das elementare Zerwürfnis des Seins" no idea if that makes any sense in english. (Ok, it doesn't make sense in german too.) It's from a "Jägermeister" commercial spot :)
            break;
        case "namechange":
        case "dragonkill":
            // Someone just did a dragonkill or had their name changed.  Since it
            // it could have been this person, we'll just invalidate the cache
            invalidatedatacache("innchat-names");
            break;
    }
    return $args;
}
function lovers_dohook($hookname, $args)
{
    global $session;
    $partner = get_partner();
    switch ($hookname) {
        case "newday":
            set_module_pref("seenlover", 0);
            if ($session['user']['marriedto'] == 4294967295.0) {
                $dk = $session['user']['dragonkills'];
                // 0.7 seemed to be a perfect balance of no loss of charm.
                // 1.0 was too much.
                $dk = max(1, round(0.85 * sqrt($dk), 0));
                $charmloss = e_rand(1, $dk);
                $session['user']['charm'] -= $charmloss;
                output("`n`%You're  married,  so there's no reason to keep up that perfect image, and you let yourself go a little today ( You lose `\$%s charmpoint(s)`%).`n", $charmloss);
                if ($session['user']['charm'] <= 0) {
                    output("`bWhen  you  wake  up, you find a note next to you, reading`n`5Dear %s`5,`n", $session['user']['name']);
                    output("Despite  many  great  kisses, I find that I'm simply no longer attracted to you the way I used to be.`n`n");
                    output("Call  me fickle, call me flakey, but I need to move on.");
                    output("There are other warriors in the land, and I think some of them are really hot.");
                    output("So it's not you, it's me, etcetera etcetera.`n`n");
                    output("No hard feelings, Love,`n%s`b`n", $partner);
                    addnews("`\$%s`\$ has left %s`\$ to pursue \"other interests.\"`0", $partner, $session['user']['name']);
                    $session['user']['marriedto'] = 0;
                    $session['user']['charm'] = 0;
                }
            }
            break;
        case "inn":
            addnav("Things to do");
            if ($session['user']['sex'] == SEX_MALE) {
                addnav(array("F?Flirt with %s", $partner), "runmodule.php?module=lovers&op=flirt");
                addnav(array("Chat with %s", translate_inline(getsetting("bard", "`^Seth"))), "runmodule.php?module=lovers&op=chat");
            } else {
                addnav(array("F?Flirt with %s", $partner), "runmodule.php?module=lovers&op=flirt");
                addnav(array("Gossip with %s", translate_inline(getsetting("barmaid", "`%Violet"))), "runmodule.php?module=lovers&op=chat");
            }
            break;
    }
    return $args;
}
function get_dk_title($dks, $gender, $ref = false)
{
    // $ref is an arbitrary string value.  The title picker will try to
    // give the next highest title in the same 'ref', but if it cannot it'll
    // default to a random one of the ones available for the required DK.
    // Figure out which dk value is the right one to use.. The one to use
    // is the closest one below or equal to the players dk number.
    // We will prefer the dk level from the same $ref if we can, but if there
    // is a closer 'any' match, we will use that!
    $refdk = -1;
    if ($ref !== false) {
        $sql = "SELECT max(dk) as dk FROM " . db_prefix("titles") . " WHERE dk<='{$dks}' and ref='{$ref}'";
        $res = db_query($sql);
        $row = db_fetch_assoc($res);
        $refdk = $row['dk'];
    }
    $sql = "SELECT max(dk) as dk FROM " . db_prefix("titles") . " WHERE dk<='{$dks}'";
    $res = db_query($sql);
    $row = db_fetch_assoc($res);
    $anydk = $row['dk'];
    $useref = "";
    $targetdk = $anydk;
    if ($refdk >= $anydk) {
        $useref = "AND ref='{$ref}'";
        $targetdk = $refdk;
    }
    // Okay, we now have the right dk target to use, so select a title from
    // any titles available at that level.  We will prefer titles that
    // match the ref if possible.
    $sql = "SELECT male,female FROM " . db_prefix("titles") . " WHERE dk='{$targetdk}' {$useref} ORDER BY RAND(" . e_rand() . ") LIMIT 1";
    $res = db_query($sql);
    $row = array('male' => 'God', 'female' => 'Goddess');
    if (db_num_rows($res) != 0) {
        $row = db_fetch_assoc($res);
    }
    if ($gender == SEX_MALE) {
        return $row['male'];
    } else {
        return $row['female'];
    }
}
function strategyhut_run()
{
    global $session;
    $cost = get_module_setting("cost");
    $op = httpget("op");
    page_header("The Strategy Hut");
    output("`5`c`bThe Strategy Hut`b`c");
    if ($op == "") {
        addnav(array("Ask for Advice (`^%s gold`0)", $cost), "runmodule.php?module=strategyhut&op=ask");
        output("`&You enter the hut, to find `6Atrus `&busy at his desk.");
        output("\"`^Well, a young warrior in search of help!");
        output("For a small fee, I will offer advice to you.`3\"`n`n");
        output("`&Hesitantly, you approach the burly warrior.`n`n");
        output("`&You blink a few times before you realize he was actually talking to you.");
        output("`6Atrus `&doesn't seem very patient, so you'd better decide quickly if you want to hear his advice!`n");
    } elseif ($session['user']['gold'] < $cost) {
        output("`&You go through your pockets, searching for money, but you don't have enough.");
        output("After a moment of intense searching, `6Atrus `&starts to scowl, and you decide to leave before he gets annoyed.`n`n");
    } else {
        $session['user']['gold'] -= $cost;
        debuglog("spent {$cost} gold at the strategy hut");
        output("`&You give `6Atrus `^%s gold`7.", $cost);
        output("`&He nods, and thinks for a moment.`n`n");
        $phrases = array("\"`^Heal often, bank often.`3\"", "\"`^Think balance: weapons and armor must be close in level, not enough defense and your first attack will be your last.`3\"", "\"`^Don't be afraid to slum, in the lower DK levels, speed is NOT a priority. Later is different.`3\"", "\"`^That stat bar is your life, when it gets into the yellow zone, heal. When it goes red, pray.`3\"", "\"`^In PvP, pick your targets with care. If not sure, DON'T... or you'll be explaining to {deathoverlord}`^ what happened.`3\"", "\"`^You don't always need to resurrect. There will be times to save favor for emergencies.`3\"", "\"`^If it's a game bug, petition it. If it's a gameplay issue, petition it.`3\"", "\"`^A good offense is not always a good defense, even the strongest players die in the forest.`3\"", "\"`^Confidence is one thing: attacking a God is suicide. Check the bio first.`3\"", "\"`^Keep an open mind and think it through. Only a fool fights blindly.`3\"", "\"`^There is a dragon, and when you are ready, it will be too. Patience.`3\"", "\"`^Travelling between towns can be dangerous. Heal first.`3\"", "\"`^Talk to everyone in all the villages, visit the shops and stalls. Explore. Learn.`3\"", "\"`^Lower DK players die often in the beginning. It happens to all of us.`3\"", "\"`^When you face the dragon, be ready and fully healed... or it will eat you for lunch.`3\"", "\"`^Your mount or familiar is an asset... learn what it can do, and know its limits. *And* yours, as well.`3\"", "\"`^There is no shame in knowing when to run. Better a bruised ego than a visit to {deathoverlord}`^.`3\"", "\"`^Log in ONCE per game day only, or you will be killed repeatedly... and lose experience as a result. There is no safe place.`3\"", "\"`^If you can't resurrect, log off and wait for New Day. You are already dead.`3\"", "\"`^A good player treats his fellows with courtesy and respect. A wise player knows that new friends can help him succeed.`3\"", "\"`^Don't forget to feed your mount or familiar.`3\"");
        $question = e_rand(0, count($phrases) - 1);
        $phrases = translate_inline($phrases);
        $myphrase = $phrases[$question];
        $myphrase = str_replace('{deathoverlord}', getsetting('deathoverlord', '`$Ramius'), $myphrase);
        output_notl("%s`n`n", $myphrase);
        output("`&You ponder his advice for a moment, before thanking him and making your exit.`n`n");
        if (is_module_active("medals")) {
            require_once "modules/medals.php";
            medals_award_medal("strategyhut", "Strategy Seeker", "This player asked for help in the Strategy Hut.", "medal_strategy.png");
        }
    }
    villagenav();
    page_footer();
}
function rail_peddler_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "improbablehousing_interior":
            $hid = $args['hid'];
            $rid = $args['rid'];
            $loc = rail_peddler_getloc();
            if ($hid == $loc['peddlerhid'] && $rid == $loc['peddlerrid']) {
                // We're in the right place to meet the peddler
                $price = get_module_setting("peddlerprice");
                if ($session['user']['gems'] >= $price && !rail_hascard("cardcase")) {
                    // note: this is a one-time character event, so we won't restrict tries per day.
                    switch (e_rand(1, 5)) {
                        case 1:
                            output("Among hurrying crowds in the concourse, a scruffy figure approaches a distant passer-by. At first the contestant shakes his head, then looks more interested. He digs out his tobacco pouch and receives something, you can't quite make out what, in exchange for a handful of cigarettes.`n`n");
                            break;
                        case 2:
                            output("Behind you a far-off voice calls out, \"`2Best levver, best levver cases! Bloody `bbadass`b cases! Bleedin' ace! Brung in special fer yer, an' cheap at twice the price!`0\"`n`nWhen you turn around, though, you can't make out who it might have been.`n`n");
                            break;
                        case 3:
                            output("A voice at your elbow says, \"`2Ey mate, y'looks like yer knows what's o'clock. Looky 'ere. `bgen`b-oo-`bwine`b levver, hand tooled an' all, sale price today jus' special fer ye, on'y `b%s`b bleedin' ciggies. What d'yer say, hey?`0\"`n`nYou examine the small leather case thrust under your nose. It does seem quite well-made, though you're not sure what you'd use it for.`n`n\"`2C'mon mate, it's ace, all da badasses and Holy Cheese showoffs are buying 'em up. When dey're gone, dey're gone! Dis here's yer lucky chance, I haveta make a sale today b'fore I kin go home ta care fer me old muvver. I'm offring it ta yer b'low me bleedin' cost!`0\"`n`nYou eye the case, pondering. You do have the cigs. The seller doesn't `ilook`i much like the Shady Salesman...`n`n", $price);
                            addnav("What do you do?");
                            addnav("Buy the case", "runmodule.php?module=rail_peddler&op=buy");
                            addnav("Pass on the offer", "runmodule.php?module=rail_peddler&op=pass");
                            break;
                    }
                } else {
                    if (rail_hascard("cardcase")) {
                        // this hook lets the peddler have a continued existence as a rumormonger
                        $args = modulehook("railpeddler-hascase", $args);
                    }
                }
            }
            break;
    }
    return $args;
}
function supplycrate_use($args)
{
    increment_module_pref("cratesopened", 1, "supplycrates");
    $found = get_module_pref("cratesopened", "supplycrates");
    if (is_module_active("medals")) {
        if ($found > 250) {
            require_once "modules/medals.php";
            medals_award_medal("crate1000", "Supreme Crate Finder", "This player has opened more than 250 Supply Crates!", "medal_crategold.png");
        }
        if ($found > 50) {
            require_once "modules/medals.php";
            medals_award_medal("crate500", "Expert Crate Finder", "This player has opened more than 50 Supply Crates!", "medal_cratesilver.png");
        }
        if ($found > 10) {
            require_once "modules/medals.php";
            medals_award_medal("crate100", "Supreme Crate Finder", "This player has opened more than 10 Supply Crates!", "medal_cratebronze.png");
        }
    }
    $crateables = get_items_with_settings("cratefind");
    $randompool = array();
    foreach ($crateables as $item => $prefs) {
        for ($i = 0; $i < $prefs['cratefind']; $i++) {
            $randompool[] = $item;
        }
    }
    output("You spend a few minutes prying open your Supply Crate.`n");
    $giveitems = array();
    $numitems = e_rand(get_module_setting("minitems", "supplycrates"), get_module_setting("maxitems", "supplycrates"));
    $chosenitems = array_rand($randompool, $numitems);
    foreach ($chosenitems as $key => $poolkey) {
        $item = $randompool[$poolkey];
        $name = $crateables[$item]['verbosename'];
        output("You find a %s!`n", $name);
        give_item($item);
    }
    return $args;
}
function waterfall_runevent($type)
{
    global $session;
    // We assume this event only shows up in the forest currently.
    $from = "forest.php?";
    $session['user']['specialinc'] = "module:waterfall";
    $op = httpget('op');
    switch ($op) {
        case "search":
        case "":
            output("`n`2You see a small path that leads away from the main trail. The path is overgrown and you almost didn't see it as you crept by.`n`n");
            output("As you crouch down to study the trail, you notice footprints leading down the path but, oddly, none coming out. While studying the path you hear what sounds like running water.`n");
            addnav("T?Follow the Trail", $from . "op=trail");
            addnav("Continue in the forest", $from . "op=leave");
            break;
        case "trail":
            output("`2You take the path and begin exploring...`n`n");
            $rand = e_rand(1, 12);
            switch ($rand) {
                case 1:
                case 2:
                case 3:
                case 4:
                case 5:
                    output("`2After a few hours of exploring you become lost.`n`n");
                    output("`&You `\$lose `&some Stamina finding your way back.`n`n");
                    if ($session['user']['turns'] > 0) {
                        $session['user']['turns']--;
                    }
                    $session['user']['specialinc'] = "";
                    break;
                case 6:
                case 7:
                case 8:
                    output("`^After a few minutes of exploring you find a waterfall!`n`n");
                    output("`2You also notice a small ledge along the rock face of the waterfall.`n");
                    output("Should you walk the ledge?");
                    addnav("Walk the ledge", $from . "op=ledge");
                    addnav("Return to the forest", $from . "op=leaveleave");
                    break;
                case 9:
                case 10:
                case 11:
                case 12:
                    output("`^After a few minutes exploring the area you find a waterfall!`n");
                    output("`2Thirsty from the walk to the falls you are trying to decide whether or not to take a drink.`n");
                    addnav("Take a drink", $from . "op=drink");
                    addnav("Return to the forest", $from . "op=leaveleave");
                    break;
            }
            break;
        case "ledge":
            $session['user']['specialinc'] = "";
            $fall = e_rand(1, 9);
            switch ($fall) {
                case 1:
                case 2:
                case 3:
                case 4:
                    $gems = e_rand(1, 2);
                    output("`&You carefully walk the ledge behind the waterfall and find... `%%s %s`n", $gems, translate_inline($gems == 1 ? "gem" : "gems"));
                    $session['user']['gems'] += $gems;
                    debuglog("found {$gems} gem(s) behind the waterfall.");
                    break;
                case 5:
                case 6:
                case 7:
                case 8:
                    $lhps = round($session['user']['hitpoints'] * 0.25);
                    $session['user']['hitpoints'] -= $lhps;
                    output("`&You carefully walk the ledge behind the waterfall but not carefully enough!`n");
                    output("You slip and fall, hurting yourself.`n`n");
                    output("`4You have lost `\$%s `4hitpoints during your fall.", $lhps);
                    if ($session['user']['gold'] > 0) {
                        $gold = round($session['user']['gold'] * 0.15);
                        output("`4You also notice that you lost `^%s gold `4during the ordeal.`n`n", $gold);
                        $session['user']['gold'] -= $gold;
                        debuglog("lost {$gold} gold when he fell in the water by the waterfall.");
                    }
                    break;
                case 9:
                    output("`7As you are walking the ledge you slip and fall,`n");
                    output("hitting the rocks and the water below!`n`n");
                    output("`4`nYou have died and lost all your gold!");
                    output("`nYou may continue playing tomorrow.`n");
                    $session['user']['turns'] = 0;
                    $session['user']['hitpoints'] = 0;
                    debuglog("lost {$session['user']['gold']} gold when he fell from the top of the waterfall.");
                    $session['user']['gold'] = 0;
                    $session['user']['alive'] = false;
                    addnews("`%The broken body of %s`% was found partially submerged by the rocks under a waterfall.", $session['user']['name']);
                    addnav("Daily News", "news.php");
                    break;
            }
            break;
        case "drink":
            $session['user']['specialinc'] = "";
            $cnt = e_rand(1, 6);
            switch ($cnt) {
                case 1:
                case 2:
                case 3:
                    output("`2You drink from the falls and feel refreshed!`n`n");
                    output("`^You have been restored to full health!");
                    if ($session['user']['hitpoints'] < $session['user']['maxhitpoints']) {
                        $session['user']['hitpoints'] = $session['user']['maxhitpoints'];
                    }
                    break;
                case 4:
                    output("`2You walk to the base of the waterfall and drink deeply of the pure water.`n");
                    output("As you drink, you feel a tingling sensation spread all over your body...`n");
                    output("You feel refreshed and healthier than ever!`n`n");
                    $hptype = "permanently";
                    if (!get_module_setting("carrydk") || is_module_active("globalhp") && !get_module_setting("carrydk", "globalhp")) {
                        $hptype = "temporarily";
                    }
                    $hptype = translate_inline($hptype);
                    output("`^Your hitpoints have been restored and your maximum hitpoints have been %s increased by 1.", $hptype);
                    $session['user']['maxhitpoints']++;
                    if ($session['user']['hitpoints'] < $session['user']['maxhitpoints']) {
                        $session['user']['hitpoints'] = $session['user']['maxhitpoints'];
                    }
                    set_module_pref("extrahps", get_module_pref("extrahps") + 1);
                    break;
                case 5:
                case 6:
                    output("`2You drink from the falls and you start feeling weird.  You sit down and become ill.`n");
                    output("`4You lose some Stamina while recovering!");
                    if ($session['user']['turns'] > 0) {
                        $session['user']['turns']--;
                    }
                    break;
            }
            break;
        case "leave":
            output("`^You stare at the path for a few more moments trying to get the courage to explore it. A piercing chill runs up your spine that makes you start trembling.  At this point you have decided to stay on the main trail.  You quickly move away from the mysterious trail.");
            $session['user']['specialinc'] = "";
            break;
        case "leaveleave":
            output("`^You decide that discretion is the better part of valor, or at least survival, and return to the forest.");
            $session['user']['specialinc'] = "";
            break;
    }
    output_notl("`0");
}
function module_events($eventtype, $basechance, $baseLink = false)
{
    if ($baseLink === false) {
        global $PHP_SELF;
        $baseLink = substr($PHP_SELF, strrpos($PHP_SELF, "/") + 1) . "?";
    } else {
        //debug("Base link was specified as $baseLink");
        //debug(debug_backtrace());
    }
    if (e_rand(1, 100) <= $basechance) {
        global $PHP_SELF;
        $events = module_collect_events($eventtype);
        $chance = r_rand(1, 100);
        reset($events);
        $sum = 0;
        foreach ($events as $event) {
            if ($event['rawchance'] == 0) {
                continue;
            }
            if ($chance > $sum && $chance <= $sum + $event['normchance']) {
                $_POST['i_am_a_hack'] = 'true';
                tlschema("events");
                output("`^`c`bSomething Special!`c`b`0");
                tlschema();
                $op = httpget('op');
                httpset('op', "");
                module_do_event($eventtype, $event['modulename'], false, $baseLink);
                httpset('op', $op);
                return 1;
            }
            $sum += $event['normchance'];
        }
    }
    return 0;
}