function hunterslodge_healthinsurance_use($args)
{
    global $session;
    $id = $args['id'];
    $expirationtime = get_item_pref("expiration_timestamp", $id);
    if (!$expirationtime) {
        $expires = time() + 604800;
        set_item_pref("expiration_timestamp", $expires, $id);
        output("`0This is the first time you've used this certificate.  It will expire exactly one week from now.`n`n");
    } else {
        if (time() > $expirationtime) {
            output("This certificate has now expired!`n`n");
            delete_item($id);
        } else {
            require_once "lib/datetime.php";
            $expirein = reltime($expirationtime, false);
            output("This certificate will expire in %s.`n`n", $expirein);
        }
    }
    $args['destroyafteruse'] = false;
    return $args;
}
function pvpvictory($badguy, $killedloc, $options)
{
    global $session;
    // If the victim has logged on and banked some, give the lessor of
    // the gold amounts.
    $sql = "SELECT gold FROM " . db_prefix("accounts") . " WHERE acctid='" . (int) $badguy['acctid'] . "'";
    $result = db_query($sql);
    $row = db_fetch_assoc($result);
    $badguy['creaturegold'] = (int) $row['gold'] > (int) $badguy['creaturegold'] ? (int) $badguy['creaturegold'] : (int) $row['gold'];
    if ($session['user']['level'] == 15) {
        output('`#***At your level of fighting prowess, the mere reward of beating your foe is sufficient accolade.`n');
    }
    // Winner of fight gets altered amount of gold based on badguy's level
    // and amount of gold they were carrying this can some times work to
    // their advantage, sometimes against.  The basic idea is to prevent
    // exhorbitant amounts of money from being transferred this way.
    $winamount = round(10 * $badguy['creaturelevel'] * log(max(1, $badguy['creaturegold'])), 0);
    output("`b`\$You have slain %s!`0`b`n", $badguy['creaturename']);
    if ($session['user']['level'] == 15) {
        $winamount = 0;
    }
    output("`#You receive `^%s`# gold!`n", $winamount);
    $session['user']['gold'] += $winamount;
    $exp = round(getsetting("pvpattgain", 10) * $badguy['creatureexp'] / 100, 0);
    if ($session['user']['level'] == 15) {
        $exp = 0;
    }
    $expbonus = round($exp * (1 + 0.1 * ($badguy['creaturelevel'] - $session['user']['level'])) - $exp, 0);
    if ($expbonus > 0) {
        output("`#***Because of the difficult nature of this fight, you are awarded an additional `^%s`# experience!`n", $expbonus);
    } else {
        if ($expbonus < 0) {
            output("`#***Because of the simplistic nature of this fight, you are penalized `^%s`# experience!`n", abs($expbonus));
        }
    }
    $wonexp = $exp + $expbonus;
    output("You receive `^%s`# experience!`n`0", $wonexp);
    $session['user']['experience'] += $wonexp;
    $lostexp = round($badguy['creatureexp'] * getsetting("pvpdeflose", 5) / 100, 0);
    debuglog("gained {$winamount} ({$badguy['creaturegold']} base) gold and {$wonexp} exp (loser lost {$lostexp}) for killing ", $badguy['acctid']);
    $args = array('pvpmessageadd' => "", 'handled' => false, 'badguy' => $badguy, 'options' => $options);
    $args = modulehook("pvpwin", $args);
    // /\- Gunnar Kreitz
    if ($session['user']['sex'] == SEX_MALE) {
        $msg = "`2While you were in %s, `^%s`2 initiated an attack on you with his `^%s`2, and defeated you!`n`nYou noticed he had an initial hp of `^%s`2 and just before you died he had `^%s`2 remaining.`n`nAs a result, you lost `\$%s%%`2 of your experience (approximately %s points), and `^%s`2 gold.`n%s`nDon't you think it's time for some revenge?`n`n`b`7Technical Notes:`b`nAlthough you might not have been in %s`7 when you got this message, you were in %s`7 when the fight was started, which was at %s according to the server (the fight lasted about %s).";
    } else {
        $msg = "`2While you were in %s, `^%s`2 initiated an attack on you with her `^%s`2, and defeated you!`n`nYou noticed she had an initial hp of `^%s`2 and just before you died she had `^%s`2 remaining.`n`nAs a result, you lost `\$%s%%`2 of your experience (approximately %s points), and `^%s`2 gold.`n%s`nDon't you think it's time for some revenge?`n`n`b`7Technical Notes:`b`nAlthough you might not have been in %s`7 when you got this message, you were in %s`7 when the fight was started, which was at %s according to the server (the fight lasted about %s).";
    }
    $mailmessage = array($msg, $killedloc, $session['user']['name'], $session['user']['weapon'], $badguy['playerstarthp'], $session['user']['hitpoints'], getsetting("pvpdeflose", 5), $lostexp, $badguy['creaturegold'], $args['pvpmessageadd'], $killedloc, $killedloc, date("D, M d h:i a", (int) $badguy['fightstartdate']), reltime((int) $badguy['fightstartdate']));
    systemmail($badguy['acctid'], array("`2You were killed while in %s`2", $killedloc), $mailmessage);
    // /\- Gunnar Kreitz
    $sql = "UPDATE " . db_prefix("accounts") . " SET alive=0, goldinbank=(goldinbank+IF(gold<{$badguy['creaturegold']},gold-{$badguy['creaturegold']},0)),gold=IF(gold<{$badguy['creaturegold']},0,gold-{$badguy['creaturegold']}), experience=experience-{$lostexp} WHERE acctid=" . (int) $badguy['acctid'] . "";
    db_query($sql);
    return $args['handled'];
}
 rawoutput("<td>");
 output_notl($ranks[$row['clanrank']]);
 rawoutput("</td><td>");
 $link = "bio.php?char=" . $row['acctid'] . "&ret=" . urlencode($_SERVER['REQUEST_URI']);
 rawoutput("<a href='{$link}'>", true);
 addnav("", $link);
 output_notl("`&%s`0", $row['name']);
 rawoutput("</a>");
 rawoutput("</td><td align='center'>");
 output_notl("`^%s`0", $row['level']);
 rawoutput("</td><td align='center'>");
 output_notl("`\$%s`0", $row['dragonkills']);
 rawoutput("</td><td>");
 output_notl("`3%s`0", $row['clanjoindate']);
 rawoutput("</td><td>");
 output_notl("`#%s`0", reltime(strtotime($row['laston'])));
 rawoutput("</td>");
 if ($session['user']['clanrank'] > CLAN_MEMBER) {
     rawoutput("<td>");
     if ($row['clanrank'] < $session['user']['clanrank'] && $row['clanrank'] < CLAN_FOUNDER) {
         rawoutput("[ <a href='clan.php?op=membership&setrank=" . clan_nextrank($ranks, $row['clanrank']) . "&who=" . rawurlencode($row['login']) . "&whoname=" . rawurlencode($row['name']) . "&whoacctid=" . $row['acctid'] . "'>{$promote}</a> | ");
         addnav("", "clan.php?op=membership&setrank=" . clan_nextrank($ranks, $row['clanrank']) . "&who=" . rawurlencode($row['login']) . "&whoname=" . rawurlencode($row['name']) . "&whoacctid=" . $row['acctid']);
     } else {
         output_notl("[ `)%s`0 | ", $promote);
     }
     if ($row['clanrank'] <= $session['user']['clanrank'] && $row['clanrank'] > CLAN_APPLICANT && $row['login'] != $session['user']['login'] && clan_previousrank($ranks, $row['clanrank']) > 0) {
         rawoutput("<a href='clan.php?op=membership&setrank=" . clan_previousrank($ranks, $row['clanrank']) . "&whoacctid=" . $row['acctid'] . "'>{$demote}</a> | ");
         addnav("", "clan.php?op=membership&setrank=" . clan_previousrank($ranks, $row['clanrank']) . "&whoacctid=" . $row['acctid']);
     } elseif ($row['clanrank'] == CLAN_FOUNDER && $row['clanrank'] > CLAN_APPLICANT && $row['login'] == $session['user']['login']) {
         output_notl("<a href='clan.php?op=membership&setrank=" . clan_previousrank($ranks, $row['clanrank']) . "&whoacctid=" . $row['acctid'] . "'>{$stepdown}</a> | ", true);
         addnav("", "clan.php?op=membership&setrank=" . clan_previousrank($ranks, $row['clanrank']) . "&whoacctid=" . $row['acctid']);
Exemplo n.º 4
0
?>
                  <? else: ?>
                    <i>
                      <?php 
echo _('keine Beschreibung vorhanden');
?>
                    </i>
                  <? endif ?>
                </td>
              </tr>
            <? endforeach ?>
          </table>
          <p></p>
          <? if ($lock->isLocked($lock_data)): ?>
            <?php 
echo MessageBox::info(sprintf(_('Die Migration wurde %s von %s bereits angestossen und läuft noch.'), reltime($lock_data['timestamp']), User::find($lock_data['user_id'])->getFullName()), array(sprintf(_('Sollte während der Migration ein Fehler aufgetreten sein, so können Sie ' . 'diese Sperre durch den unten stehenden Link oder das Löschen der Datei ' . '<em>%s</em> auflösen.'), $lock->getFilename())));
?>
            <?php 
echo Studip\LinkButton::create(_('Sperre aufheben'), URLHelper::getURL('?release_lock=1&target=' . @$target));
?>
          <? else: ?>
            <form method="POST">
              <?php 
echo CSRFProtection::tokenTag();
?>
              <? if (isset($target)): ?>
                <input type="hidden" name="target" value="<?php 
echo $target;
?>
">
              <? endif ?>
addnav("Refresh", "gamelog.php?start={$start}{$cat}");
if ($category > "") {
    addnav("View all", "gamelog.php");
}
addnav("Game Log");
if ($next < $max) {
    addnav("Next page", "gamelog.php?start={$next}{$cat}");
}
if ($start > 0) {
    addnav("Previous page", "gamelog.php?start={$prev}{$cat}");
}
$result = db_query($sql);
$odate = "";
$categories = array();
$i = 0;
while ($row = db_fetch_assoc($result)) {
    $dom = date("D, M d", strtotime($row['date']));
    if ($odate != $dom) {
        output_notl("`n`b`@%s`0`b`n", $dom);
        $odate = $dom;
    }
    $time = date("H:i:s", strtotime($row['date'])) . " (" . reltime(strtotime($row['date'])) . ")";
    output_notl("`7(%s) %s `7(`&%s`7)", $row['category'], $row['message'], $row['name']);
    if (!isset($categories[$row['category']]) && $category == "") {
        addnav("Operations");
        addnav(array("View by `i%s`i", $row['category']), "gamelog.php?cat=" . $row['category']);
        $categories[$row['category']] = 1;
    }
    output_notl("`n");
}
page_footer();
function viewcommentary($section, $message = "Interject your own commentary?", $limit = 10, $talkline = "says", $schema = false)
{
    global $session, $REQUEST_URI, $doublepost, $translation_namespace;
    global $emptypost;
    // *** DRAGONBG.COM CORE PATCH START ***
    if ($section) {
        rawoutput("<a name='{$section}'></a>");
        // Let's add a hook for modules to block commentary sections
        $args = modulehook("blockcommentarea", array("section" => $section));
        if (isset($args['block']) && $args['block'] == "yes") {
            return;
        }
    }
    // *** DRAGONBG.COM CORE PATCH END ***
    if ($schema === false) {
        $schema = $translation_namespace;
    }
    tlschema("commentary");
    $nobios = array("motd.php" => true);
    if (!array_key_exists(basename($_SERVER['SCRIPT_NAME']), $nobios)) {
        $nobios[basename($_SERVER['SCRIPT_NAME'])] = false;
    }
    if ($nobios[basename($_SERVER['SCRIPT_NAME'])]) {
        $linkbios = false;
    } else {
        $linkbios = true;
    }
    if ($message == "X") {
        $linkbios = true;
    }
    if ($doublepost) {
        output("`\$`bDouble post?`b`0`n");
    }
    if ($emptypost) {
        output("`\$`bWell, they say silence is a virtue.`b`0`n");
    }
    // *** DRAGONBG.COM CORE PATCH START ***
    $clanrankcolors = array(CLAN_APPLICANT => "`!", CLAN_MEMBER => "`#", CLAN_OFFICER => "`^", CLAN_LEADER => "`&", CLAN_FOUNDER => "`\$");
    $args = modulehook("clanrankcolors", array("clanrankcolors" => $clanrankcolors, "clanid" => $session['user']['clanid']));
    $clanrankcolors = $args['clanrankcolors'];
    // *** DRAGONBG.COM CORE PATCH END ***
    // Needs to be here because scrolling through the commentary pages, entering a bio, then scrolling again forward
    // then re-entering another bio will lead to $com being smaller than 0 and this will lead to an SQL error later on.
    $com = (int) httpget("comscroll");
    if ($com < 0) {
        $com = 0;
    }
    $cc = false;
    if (httpget("comscroll") !== false && (int) $session['lastcom'] == $com + 1) {
        $cid = (int) $session['lastcommentid'];
    } else {
        $cid = 0;
    }
    $session['lastcom'] = $com;
    if ($com > 0 || $cid > 0) {
        // Find newly added comments.
        // *** DRAGONBG.COM CORE PATCH START ***
        $sql = "SELECT COUNT(commentid) AS newadded FROM " . db_prefix("commentary") . " LEFT JOIN " . db_prefix("accounts") . " ON " . db_prefix("accounts") . ".acctid = " . db_prefix("commentary") . ".author WHERE " . ($section ? "section='{$section}' AND " : '') . "(" . db_prefix("accounts") . ".locked=0 or " . db_prefix('accounts') . ".locked is null) AND commentid > '{$cid}'";
        $result = db_query($sql);
        $row = db_fetch_assoc($result);
        $newadded = $row['newadded'];
        // *** DRAGONBG.COM CORE PATCH END ***
    } else {
        $newadded = 0;
    }
    $commentbuffer = array();
    if ($cid == 0) {
        $sql = "SELECT " . db_prefix("commentary") . ".*, " . db_prefix("accounts") . ".name, " . db_prefix("accounts") . ".acctid, " . db_prefix("accounts") . ".clanrank, " . db_prefix("clans") . ".clanshort FROM " . db_prefix("commentary") . " LEFT JOIN " . db_prefix("accounts") . " ON " . db_prefix("accounts") . ".acctid = " . db_prefix("commentary") . ".author LEFT JOIN " . db_prefix("clans") . " ON " . db_prefix("clans") . ".clanid=" . db_prefix("accounts") . ".clanid WHERE " . ($section ? "section='{$section}' AND " : '') . "( " . db_prefix("accounts") . ".locked=0 OR " . db_prefix("accounts") . ".locked is null ) " . "ORDER BY commentid DESC LIMIT " . $com * $limit . ",{$limit}";
        // *** DRAGONBG.COM CORE PATCH END ***
        if ($com == 0 && strstr($_SERVER['REQUEST_URI'], "/moderate.php") !== $_SERVER['REQUEST_URI']) {
            $result = db_query_cached($sql, "comments-{$section}");
        } else {
            $result = db_query($sql);
        }
        while ($row = db_fetch_assoc($result)) {
            $commentbuffer[] = $row;
        }
    } else {
        // *** DRAGONBG.COM CORE PATCH START ***
        $sql = "SELECT " . db_prefix("commentary") . ".*, " . db_prefix("accounts") . ".name, " . db_prefix("accounts") . ".acctid, " . db_prefix("accounts") . ".clanrank, " . db_prefix("clans") . ".clanshort FROM " . db_prefix("commentary") . " LEFT JOIN " . db_prefix("accounts") . " ON " . db_prefix("accounts") . ".acctid = " . db_prefix("commentary") . ".author LEFT JOIN " . db_prefix("clans") . " ON " . db_prefix("clans") . ".clanid=" . db_prefix("accounts") . ".clanid WHERE " . ($section ? "section='{$section}' AND " : '') . "( " . db_prefix("accounts") . ".locked=0 OR " . db_prefix("accounts") . ".locked is null ) " . "AND commentid > '{$cid}' " . "ORDER BY commentid ASC LIMIT {$limit}";
        // *** DRAGONBG.COM CORE PATCH END ***
        $result = db_query($sql);
        while ($row = db_fetch_assoc($result)) {
            $commentbuffer[] = $row;
        }
        $commentbuffer = array_reverse($commentbuffer);
    }
    $rowcount = count($commentbuffer);
    if ($rowcount > 0) {
        $session['lastcommentid'] = $commentbuffer[0]['commentid'];
    }
    $counttoday = 0;
    $commentbuffer = modulehook("pagecommentary", $commentbuffer);
    // debug($commentbuffer);
    for ($i = 0; $i < $rowcount; $i++) {
        $row = $commentbuffer[$i];
        $row['comment'] = comment_sanitize($row['comment']);
        $commentids[$i] = $row['commentid'];
        if (date("Y-m-d", strtotime($row['postdate'])) == date("Y-m-d")) {
            if ($row['name'] == $session['user']['name']) {
                $counttoday++;
            }
        }
        $x = 0;
        $ft = "";
        for ($x = 0; strlen($ft) < 5 && $x < strlen($row['comment']); $x++) {
            if (substr($row['comment'], $x, 1) == "`" && strlen($ft) == 0) {
                $x++;
            } else {
                $ft .= substr($row['comment'], $x, 1);
            }
        }
        $link = "bio.php?char=" . $row['acctid'] . "&ret=" . URLEncode($_SERVER['REQUEST_URI']);
        if (substr($ft, 0, 2) == "::") {
            $ft = substr($ft, 0, 2);
        } elseif (substr($ft, 0, 1) == ":") {
            $ft = substr($ft, 0, 1);
        } elseif (substr($ft, 0, 3) == "/me") {
            $ft = substr($ft, 0, 3);
        }
        if ($row['clanrank']) {
            $row['name'] = ($row['clanshort'] > "" ? "{$clanrankcolors[$row['clanrank']]}&lt;`2{$row['clanshort']}{$clanrankcolors[$row['clanrank']]}&gt; `&" : "") . $row['name'];
        }
        if ($ft == "::" || $ft == "/me" || $ft == ":") {
            $x = strpos($row['comment'], $ft);
            if ($x !== false) {
                if ($linkbios) {
                    $op[$i] = str_replace("&amp;", "&", htmlentities(substr($row['comment'], 0, $x), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0<a href='{$link}' style='text-decoration: none'>\n`&{$row['name']}`0</a>\n`& " . str_replace("&amp;", "&", htmlentities(substr($row['comment'], $x + strlen($ft)), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`n";
                } else {
                    $op[$i] = str_replace("&amp;", "&", htmlentities(substr($row['comment'], 0, $x), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`&{$row['name']}`0`& " . str_replace("&amp;", "&", htmlentities(substr($row['comment'], $x + strlen($ft)), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`n";
                }
                $rawc[$i] = str_replace("&amp;", "&", htmlentities(substr($row['comment'], 0, $x), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`&{$row['name']}`0`& " . str_replace("&amp;", "&", htmlentities(substr($row['comment'], $x + strlen($ft)), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`n";
            }
        }
        if ($ft == "/game" && !$row['name']) {
            $x = strpos($row['comment'], $ft);
            if ($x !== false) {
                $op[$i] = str_replace("&amp;", "&", htmlentities(substr($row['comment'], 0, $x), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`&" . str_replace("&amp;", "&", htmlentities(substr($row['comment'], $x + strlen($ft)), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`n";
            }
        }
        if (!isset($op) || !is_array($op)) {
            $op = array();
        }
        if (!array_key_exists($i, $op) || $op[$i] == "") {
            if ($linkbios) {
                $op[$i] = "`0<a href='{$link}' style='text-decoration: none'>`&{$row['name']}`0</a>`3 says, \"`#" . str_replace("&amp;", "&", htmlentities($row['comment'], ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`3\"`0`n";
            } elseif (substr($ft, 0, 5) == '/game' && !$row['name']) {
                $op[$i] = str_replace("&amp;", "&", htmlentities($row['comment'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")));
            } else {
                $op[$i] = "`&{$row['name']}`3 says, \"`#" . str_replace("&amp;", "&", htmlentities($row['comment'], ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`3\"`0`n";
            }
            $rawc[$i] = "`&{$row['name']}`3 says, \"`#" . str_replace("&amp;", "&", htmlentities($row['comment'], ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`3\"`0`n";
        }
        if (!array_key_exists('timestamp', $session['user']['prefs'])) {
            $session['user']['prefs']['timestamp'] = 0;
        }
        $session['user']['prefs']['timeoffset'] = round($session['user']['prefs']['timeoffset'], 1);
        if ($session['user']['prefs']['timestamp'] == 1) {
            if (!isset($session['user']['prefs']['timeformat'])) {
                $session['user']['prefs']['timeformat'] = "[m/d h:ia]";
            }
            $time = strtotime($row['postdate']) + $session['user']['prefs']['timeoffset'] * 60 * 60;
            $s = date("`7" . $session['user']['prefs']['timeformat'] . "`0 ", $time);
            $op[$i] = $s . $op[$i];
        } elseif ($session['user']['prefs']['timestamp'] == 2) {
            $s = reltime(strtotime($row['postdate']));
            $op[$i] = "`7({$s})`0 " . $op[$i];
        }
        if ($message == "X") {
            $op[$i] = "`0({$row['section']}) " . $op[$i];
        }
        if ($row['postdate'] >= $session['user']['recentcomments']) {
            $op[$i] = "<img src='images/new.gif' alt='&gt;' width='3' height='5' align='absmiddle'> " . $op[$i];
        }
        addnav("", $link);
        $auth[$i] = $row['author'];
        if (isset($rawc[$i])) {
            $rawc[$i] = full_sanitize($rawc[$i]);
            $rawc[$i] = htmlentities($rawc[$i], ENT_QUOTES, getsetting("charset", "ISO-8859-1"));
        }
    }
    $i--;
    $outputcomments = array();
    $sect = "x";
    $moderating = false;
    if ($session['user']['superuser'] & SU_EDIT_COMMENTS && $message == "X") {
        $moderating = true;
    }
    $del = translate_inline("Del");
    $scriptname = substr($_SERVER['SCRIPT_NAME'], strrpos($_SERVER['SCRIPT_NAME'], "/") + 1);
    $pos = strpos($_SERVER['REQUEST_URI'], "?");
    $return = $scriptname . ($pos == false ? "" : substr($_SERVER['REQUEST_URI'], $pos));
    $one = strstr($return, "?") == false ? "?" : "&";
    for (; $i >= 0; $i--) {
        $out = "";
        if ($moderating) {
            if ($session['user']['superuser'] & SU_EDIT_USERS) {
                $out .= "`0[ <input type='checkbox' name='comment[{$commentids[$i]}]'> | <a href='user.php?op=setupban&userid=" . $auth[$i] . "&reason=" . rawurlencode($rawc[$i]) . "'>Ban</a> ]&nbsp;";
                addnav("", "user.php?op=setupban&userid={$auth[$i]}&reason=" . rawurlencode($rawc[$i]));
            } else {
                $out .= "`0[ <input type='checkbox' name='comment[{$commentids[$i]}]'> ]&nbsp;";
            }
            $matches = array();
            preg_match("/[(]([^)]*)[)]/", $op[$i], $matches);
            $sect = trim($matches[1]);
            if (substr($sect, 0, 5) != "clan-" || $sect == $section) {
                if (substr($sect, 0, 4) != "pet-") {
                    $out .= $op[$i];
                    if (!isset($outputcomments[$sect]) || !is_array($outputcomments[$sect])) {
                        $outputcomments[$sect] = array();
                    }
                    array_push($outputcomments[$sect], $out);
                }
            }
        } else {
            if ($session['user']['superuser'] & SU_EDIT_COMMENTS) {
                $out .= "`2[<a href='" . $return . $one . "removecomment={$commentids[$i]}&section={$section}&returnpath=" . URLEncode($return) . "'>{$del}</a>`2]`0&nbsp;";
                addnav("", $return . $one . "removecomment={$commentids[$i]}&section={$section}&returnpath=" . URLEncode($return) . "");
            }
            $out .= $op[$i];
            if (!array_key_exists($sect, $outputcomments) || !is_array($outputcomments[$sect])) {
                $outputcomments[$sect] = array();
            }
            array_push($outputcomments[$sect], $out);
        }
    }
    if ($moderating) {
        $scriptname = substr($_SERVER['SCRIPT_NAME'], strrpos($_SERVER['SCRIPT_NAME'], "/") + 1);
        addnav("", "{$scriptname}?op=commentdelete&return=" . URLEncode($_SERVER['REQUEST_URI']));
        $mod_Del1 = htmlentities(translate_inline("Delete Checked Comments"), ENT_COMPAT, getsetting("charset", "ISO-8859-1"));
        $mod_Del2 = htmlentities(translate_inline("Delete Checked & Ban (3 days)"), ENT_COMPAT, getsetting("charset", "ISO-8859-1"));
        $mod_Del_confirm = addslashes(htmlentities(translate_inline("Are you sure you wish to ban this user and have you specified the exact reason for the ban, i.e. cut/pasted their offensive comments?"), ENT_COMPAT, getsetting("charset", "ISO-8859-1")));
        $mod_reason = translate_inline("Reason:");
        $mod_reason_desc = htmlentities(translate_inline("Banned for comments you posted."), ENT_COMPAT, getsetting("charset", "ISO-8859-1"));
        // *** DRAGONBG.COM CORE PATCH START ***
        output_notl("<form action='{$scriptname}?op=commentdelete&return=" . URLEncode($_SERVER['REQUEST_URI']) . "' method='POST' id='comments'>", true);
        // *** DRAGONBG.COM CORE PATCH END ***
        output_notl("<input type='submit' class='button' value=\"{$mod_Del1}\">", true);
        output_notl("<input type='submit' class='button' name='delnban' value=\"{$mod_Del2}\" onClick=\"return confirm('{$mod_Del_confirm}');\">", true);
        // *** DRAGONBG.COM CORE PATCH START ***
        $mod_checkall = htmlspecialchars(translate_inline("Check all"));
        // Check all - by Pr0t3ct0r
        output_notl('<script type="text/javascript">function checkall() { 
			var isChecked = document.getElementById("CheckAllID").checked 
			var f = document.getElementById("comments") 
			for (var i=0;i<f.length;i++) { 
			  if (f.elements[i].type == "checkbox"){ 
				  f.elements[i].checked = isChecked 
			  }
			} 
		}</script>', true);
        output_notl("<input type='checkbox' id='CheckAllID' onclick='checkall()' /> {$mod_checkall}", true);
        output_notl("`n{$mod_reason} <input name='reason0' id='reason0' size='40' value=\"{$mod_reason_desc}\" onChange=\"document.getElementById('reason').value=this.value;\">", true);
        // *** DRAGONBG.COM CORE PATCH END ***
    }
    //output the comments
    ksort($outputcomments);
    reset($outputcomments);
    $sections = commentarylocs();
    $needclose = 0;
    while (list($sec, $v) = each($outputcomments)) {
        if ($sec != "x") {
            output_notl("`n<hr><a href='moderate.php?area=%s'>`b`^%s`0`b</a>`n", $sec, isset($sections[$sec]) ? $sections[$sec] : "({$sec})", true);
            addnav("", "moderate.php?area={$sec}");
        }
        reset($v);
        while (list($key, $val) = each($v)) {
            $args = array('commentline' => $val, 'area' => $section);
            $args = modulehook("viewcommentary", $args);
            $val = $args['commentinfo'] . $args['commentline'];
            output_notl($val, true);
        }
    }
    $sql = "SELECT count(commentid) AS c FROM " . db_prefix("commentary") . " WHERE section='{$section}'";
    $r = db_query($sql);
    $val = db_fetch_assoc($r);
    $val = round($val['c'] / $limit + 0.5, 0) - 1;
    rawoutput("<table cellpadding=0 cellspacing=5 width=100%><tr><td valign=\"top\" width=50%>");
    // *** AJAX CHAT MOD START ***
    if (round($limit / 2, 0) - $counttoday < 3) {
        output("`)(You have %s posts left today)`n`0", round($limit / 2, 0) - $counttoday);
    }
    rawoutput('</div>');
    // *** AJAX CHAT MOD END ***
    if ($moderating && $needclose) {
        modulehook("}collapse");
        $needclose = 0;
    }
    if ($moderating) {
        output_notl("`n");
        rawoutput("<input type='submit' class='button' value=\"{$mod_Del1}\">");
        rawoutput("<input type='submit' class='button' name='delnban' value=\"{$mod_Del2}\" onClick=\"return confirm('{$mod_Del_confirm}');\">");
        output_notl("`n%s ", $mod_reason);
        // *** DRAGONBG.COM CORE PATCH START ***
        rawoutput("<input name='reason' size='40' id='reason' value=\"{$mod_reason_desc}\" onchange=\"document.getElementById('reason0').value=this.value;\">");
        // *** DRAGONBG.COM CORE PATCH END ***
        rawoutput("</form>");
        output_notl("`n");
    }
    if ($session['user']['loggedin']) {
        $args = modulehook("insertcomment", array("section" => $section));
        if (array_key_exists("mute", $args) && $args['mute'] && !($session['user']['superuser'] & SU_EDIT_COMMENTS)) {
            output_notl("%s", $args['mutemsg']);
        } elseif ($counttoday < $limit / 2 || $session['user']['superuser'] & ~SU_DOESNT_GIVE_GROTTO || !getsetting('postinglimit', 1)) {
            if ($message != "X") {
                $message = "`n`@{$message}`n";
                output($message);
                talkform($section, $talkline, $limit, $schema);
            }
        } else {
            $message = "`n`@{$message}`n";
            output($message);
            output("Sorry, you've exhausted your posts in this section for now.`0`n");
        }
    }
    $jump = false;
    if (!isset($session['user']['prefs']['nojump']) || $session['user']['prefs']['nojump'] == false) {
        $jump = true;
    }
    //new-style commentary display with page numbers
    if (!$cc) {
        db_free_result($result);
    }
    tlschema();
    if ($needclose) {
        modulehook("}collapse");
    }
    rawoutput("</td><td valign=\"top\" width=50%>");
    $nlink = comscroll_sanitize($REQUEST_URI);
    $nlink = str_replace("?&", "?", $nlink);
    if (!strpos($nlink, "?")) {
        $nlink = str_replace("&", "?", $nlink);
    }
    $nlink .= "&refresh=1";
    //reinstating back and forward links
    output_notl("`n");
    $prev = translate_inline("&lt;&lt;");
    $next = translate_inline("&gt;&gt;");
    if ($rowcount >= $limit || $cid > 0) {
        $req = comscroll_sanitize($REQUEST_URI) . "&comscroll=" . ($com + 1);
        $req = str_replace("?&", "?", $req);
        if (!strpos($req, "?")) {
            $req = str_replace("&", "?", $req);
        }
        $req .= "&refresh=1";
        if ($jump) {
            $req .= "#{$section}";
        }
        output_notl("<a href=\"{$req}\">{$prev}</a> ", true);
        addnav("", $req);
    }
    output_notl("<a href=\"{$nlink}\">Refresh Commentary</a>", true);
    if ($com > 0 || $cid > 0 && $newadded > $limit) {
        $req = comscroll_sanitize($REQUEST_URI) . "&comscroll=" . ($com - 1);
        $req = str_replace("?&", "?", $req);
        if (!strpos($req, "?")) {
            $req = str_replace("&", "?", $req);
        }
        $req .= "&refresh=1";
        if ($jump) {
            $req .= "#{$section}";
        }
        output_notl(" <a href=\"{$req}\">{$next}</a>", true);
        addnav("", $req);
    }
    //
    addnav("", $nlink);
    output("`n`n`0Jump to commentary page:");
    for ($i = $val; $i >= 0; $i--) {
        $nlink = comscroll_sanitize($REQUEST_URI) . "&comscroll=" . $i;
        $nlink = str_replace("?&", "?", $nlink);
        if (!strpos($nlink, "?")) {
            $nlink = str_replace("&", "?", $nlink);
        }
        $nlink .= "&refresh=1";
        if ($jump) {
            $nlink .= "#{$section}";
        }
        $ndisp = 1 + $val - $i;
        if (httpget('comscroll') != $i) {
            output_notl("<a href=\"{$nlink}\">{$ndisp}</a> ", true);
            addnav("", $nlink);
        } else {
            output_notl("`@{$ndisp}`0 ", true);
        }
    }
    modulehook("commentaryoptions");
    rawoutput("</td></tr></table");
    // *** AJAX CHAT MOD START ***
    modulehook("viewcommentaryfooter");
    // *** AJAX CHAT MOD END ***
}
Exemplo n.º 7
0
 /**
  * Autor / Tutor / Teacher action
  */
 public function index_action($order_by = null, $order = 'asc')
 {
     if ($GLOBALS['perm']->have_perm('root')) {
         throw new AccessDeniedException();
     }
     if ($GLOBALS['perm']->have_perm('admin')) {
         $this->redirect('my_courses/admin');
         return;
     }
     Navigation::activateItem('/browse/my_courses/list');
     PageLayout::setHelpKeyword("Basis.MeineVeranstaltungen");
     PageLayout::setTitle(_("Meine Veranstaltungen"));
     $config_sem = $GLOBALS['user']->cfg->MY_COURSES_SELECTED_CYCLE;
     if (!Config::get()->MY_COURSES_ENABLE_ALL_SEMESTERS && $config_sem == 'all') {
         $config_sem = 'future';
     }
     $this->_my_sem_open = $GLOBALS['user']->cfg->MY_COURSES_OPEN_GROUPS;
     $group_field = $GLOBALS['user']->cfg->MY_COURSES_GROUPING;
     $deputies_enabled = Config::get()->DEPUTIES_ENABLE;
     $default_deputies_enabled = Config::get()->DEPUTIES_DEFAULTENTRY_ENABLE;
     $deputies_edit_about_enabled = Config::get()->DEPUTIES_EDIT_ABOUT_ENABLE;
     $studygroups_enabled = Config::get()->MY_COURSES_ENABLE_STUDYGROUPS;
     $this->config_sem_number = Config::get()->IMPORTANT_SEMNUMBER;
     $sem_create_perm = in_array(Config::get()->SEM_CREATE_PERM, array('root', 'admin', 'dozent')) ? Config::get()->SEM_CREATE_PERM : 'dozent';
     $this->sem_data = SemesterData::GetSemesterArray();
     $sem = $config_sem && $config_sem != '0' ? $config_sem : Config::get()->MY_COURSES_DEFAULT_CYCLE;
     if (Request::option('sem_select')) {
         $sem = Request::get('sem_select', $sem);
     }
     if (!in_array($sem, words('future all last current')) && isset($sem)) {
         Request::set('sem_select', $sem);
     }
     $forced_grouping = in_array(Config::get()->MY_COURSES_FORCE_GROUPING, getValidGroupingFields()) ? Config::get()->MY_COURSES_FORCE_GROUPING : 'sem_number';
     if ($forced_grouping == 'not_grouped') {
         $forced_grouping = 'sem_number';
     }
     if (!$group_field) {
         $group_field = 'sem_number';
     }
     if ($group_field == 'sem_number' && $forced_grouping != 'sem_number') {
         $group_field = $forced_grouping;
     }
     $this->group_field = $group_field === 'not_grouped' ? 'sem_number' : $group_field;
     // Needed parameters for selecting courses
     $params = array('group_field' => $this->group_field, 'order_by' => $order_by, 'order' => $order, 'studygroups_enabled' => $studygroups_enabled, 'deputies_enabled' => $deputies_enabled);
     // Save the semester in session
     $this->sem_courses = MyRealmModel::getPreparedCourses($sem, $params);
     $this->waiting_list = MyRealmModel::getWaitingList($GLOBALS['user']->id);
     $this->sem = $sem;
     $this->order = $order;
     $this->order_by = $order_by;
     $this->default_deputies_enabled = $default_deputies_enabled;
     $this->deputies_edit_about_enabled = $deputies_edit_about_enabled;
     $this->my_bosses = $default_deputies_enabled ? getDeputyBosses($GLOBALS['user']->id) : array();
     // Check for new contents
     $new_contents = $this->check_for_new($this->sem_courses, $this->group_field);
     $this->nav_elements = MyRealmModel::calc_nav_elements($this->sem_courses, $this->group_field);
     //
     if ($tabularasa = $this->flash['tabularasa']) {
         $details = array();
         if ($new_contents) {
             $details[] = sprintf(_('Seit Ihrem letzten Seitenaufruf (%s) sind allerdings neue Inhalte hinzugekommen.'), reltime($tabularasa));
         }
         $message_box = MessageBox::success(_('Alles als gelesen markiert!'), $details);
         PageLayout::postMessage($message_box);
     }
     // create settings url depended on selected cycle
     if (isset($sem) && !in_array($sem, words('future all last current'))) {
         $this->settings_url = sprintf('dispatch.php/my_courses/groups/%s', $sem);
     } else {
         $this->settings_url = 'dispatch.php/my_courses/groups';
     }
     $sidebar = Sidebar::get();
     $sidebar->setImage('sidebar/seminar-sidebar.png');
     $this->setSemesterWidget($sem);
     $setting_widget = new ActionsWidget();
     if ($new_contents) {
         $setting_widget->addLink(_('Alles als gelesen markieren'), $this->url_for('my_courses/tabularasa/' . $sem . '/', time()), Icon::create('accept', 'clickable'));
     }
     $setting_widget->addLink(_('Farbgruppierung ändern'), URLHelper::getLink($this->settings_url), Icon::create('group4', 'clickable'), array('data-dialog' => ''));
     if (Config::get()->MAIL_NOTIFICATION_ENABLE) {
         $setting_widget->addLink(_('Benachrichtigungen anpassen'), URLHelper::getLink('dispatch.php/settings/notification'), Icon::create('mail', 'clickable'));
     }
     if ($sem_create_perm == 'dozent' && $GLOBALS['perm']->have_perm('dozent')) {
         $setting_widget->addLink(_('Neue Veranstaltung anlegen'), URLHelper::getLink('dispatch.php/course/wizard'), Icon::create('seminar+add', 'clickable'));
     }
     $setting_widget->addLink(_('Veranstaltung hinzufügen'), URLHelper::getLink('dispatch.php/search/courses'), Icon::create('seminar', 'clickable'));
     $sidebar->addWidget($setting_widget);
     $this->setGroupingSelector($this->group_field);
 }
Exemplo n.º 8
0
<article class="comment open">
    <time><?php 
echo reltime($comment[3]);
?>
</time>
    <h1>#<?php 
echo $index + 1;
?>
        <a href="<?php 
echo URLHelper::getLink('dispatch.php/profile?username=' . $comment[2]);
?>
">
             <?php 
echo htmlReady($comment[1]);
?>
        </a>
    </h1>
    <?php 
echo formatReady($comment[0]);
?>
</article>
Exemplo n.º 9
0
                </a>
            <? else: ?>
                <?php 
echo htmlReady($file->file->owner->getFullName());
?>
            <? endif; ?>
            </td>
            <td title="<?php 
echo strftime('%x %X', $file->file->mkdate);
?>
" data-sort-value="<?php 
echo $file->file->mkdate;
?>
">
                <?php 
echo reltime($file->file->mkdate);
?>
            </td>
            <td class="options">
            <? if ($full_access): ?>
                <a href="<?php 
echo $controller->url_for('document/files/edit/' . $file->id);
?>
" data-dialog="size=auto" title="<?php 
echo _('Datei bearbeiten');
?>
">
                    <?php 
echo Icon::create('edit', 'clickable')->asImg(16, ["alt" => _('bearbeiten')]);
?>
                </a>
function getcommentary($section, $limit = 25, $talkline, $customsql = false, $showmodlink = false, $returnlink = false)
{
    //$gcstart = getmicrotime(true);
    global $session, $REQUEST_URI, $translation_namespace;
    global $chatloc, $bottomcid;
    if (!$returnlink) {
        $returnlink = URLEncode($_SERVER['REQUEST_URI']);
    }
    if ($showmodlink) {
        $link = buildcommentarylink("&bulkdelete=true&comscroll=" . $com);
        addnav("", $link);
        rawoutput("<form action=" . $link . " id='bulkdelete' method='post'>");
        $del = "Del";
        $undel = "UNDel";
    }
    //stops people from clicking on Bio links in the MoTD
    $nobios = array("motd.php" => true, "runmodule.php?module=global_banter" => true);
    if (!array_key_exists(basename($_SERVER['SCRIPT_NAME']), $nobios)) {
        $nobios[basename($_SERVER['SCRIPT_NAME'])] = false;
    }
    if ($nobios[basename($_SERVER['SCRIPT_NAME'])]) {
        $linkbios = false;
    } else {
        $linkbios = true;
    }
    // Needs to be here because scrolling through the commentary pages, entering a bio, then scrolling again forward
    // then re-entering another bio will lead to $com being smaller than 0 and this will lead to an SQL error later on.
    $com = (int) httpget("comscroll");
    if ($com < 0) {
        $com = 0;
    }
    if (httpget("comscroll") !== false && (int) $session['lastcom'] == $com + 1) {
        $cid = (int) $session['lastcommentid'];
    } else {
        $cid = 0;
    }
    $session['lastcom'] = $com;
    if (!$cid) {
        $cid = 1;
    }
    if ($customsql) {
        $sql = $customsql;
    } else {
        if ($section == "all") {
            $sql = "SELECT * FROM " . db_prefix("commentary") . " WHERE section NOT LIKE 'dwelling%' AND section NOT LIKE 'clan%' AND section NOT LIKE 'pet-%' ORDER BY commentid DESC LIMIT " . $com * $limit . ",{$limit}";
            $result = db_query($sql);
            $viewingallsections = 1;
        } else {
            $start = microtime(true);
            $sql = "SELECT * FROM " . db_prefix("commentary") . " WHERE section='{$section}' ORDER BY commentid DESC LIMIT " . $com * $limit . ",{$limit}";
            if (!$com) {
                //save doing db_fetch_assoc on commentary that's already cached; just unserialize and load it in one chunk
                $commentbuffer = datacache("commentary/latestcommentary_" . $section, 60);
                //debug($commentbuffer);
            }
            if (!is_array($commentbuffer) || $com) {
                $commentbuffer = array();
                $result = db_query($sql);
                while ($row = db_fetch_assoc($result)) {
                    $row['info'] = @stripslashes($row['info']);
                    $row['info'] = @unserialize($row['info']);
                    if (!is_array($row['info'])) {
                        $row['info'] = array();
                    }
                    $row['info']['link'] = buildcommentarylink("&commentid=" . $row['commentid']);
                    $commentbuffer[] = $row;
                }
                if (!$com) {
                    updatedatacache("commentary/latestcommentary_" . $section, $commentbuffer);
                }
            }
        }
    }
    $end = microtime(true);
    $tot = $end - $start;
    //debug($tot);
    //pre-formatting
    $commentbuffer = modulehook("commentbuffer-preformat", $commentbuffer);
    $rowcount = count($commentbuffer);
    if ($rowcount > 0) {
        $session['lastcommentid'] = $commentbuffer[0]['commentid'];
    }
    //figure out whether to handle absolute or relative time
    if (!array_key_exists('timestamp', $session['user']['prefs'])) {
        $session['user']['prefs']['timestamp'] = 0;
    }
    $session['user']['prefs']['timeoffset'] = round($session['user']['prefs']['timeoffset'], 1);
    if (!array_key_exists('commentary_reverse', $session['user']['prefs'])) {
        $session['user']['prefs']['commentary_reverse'] = 0;
    }
    //this array of userids means that with a single query we can figure out who's online and nearby
    $acctidstoquery = array();
    //prepare the actual comment line part of the comment - is it hidden, is it an action, is it a game comment, should we show a moderation link, clan rank colours, posting date abs/rel
    $loop1start = getmicrotime(true);
    $bioretlink = $returnlink;
    $bioretlink = URLEncode(buildcommentarylink("&frombio=true", $returnlink));
    $restorelink = buildcommentarylink("&comscroll=" . $com . "&restorecomment=", $returnlink);
    $removelink = buildcommentarylink("&comscroll=" . $com . "&removecomment=", $returnlink);
    for ($i = 0; $i < $rowcount; $i++) {
        if (!$commentbuffer[$i]['info']['hidecomment'] || $showmodlink) {
            $thiscomment = "";
            if ($viewingallsections) {
                $thiscomment .= "`b" . $row['section'] . "`0`b: ";
            }
            $row = $commentbuffer[$i];
            $row['acctid'] = $row['author'];
            $acctidstoquery[] = $row['author'];
            //$row['comment'] = comment_sanitize($row['comment']);
            if (substr($row['comment'], 0, 1) == ":" || substr($row['comment'], 0, 3) == "/me") {
                $row['skiptalkline'] = true;
                //remove beginning /me
                //$length = strlen($row['comment']);
                if (substr($row['comment'], 0, 3) == "/me") {
                    //debug("Match on ".$row['comment']);
                    $row['comment'] = substr($row['comment'], 3);
                } else {
                    if (substr($row['comment'], 0, 2) == "::") {
                        //debug("Match on ".$row['comment']);
                        $row['comment'] = substr($row['comment'], 2);
                    } else {
                        if (substr($row['comment'], 0, 1) == ":") {
                            //debug("Match on ".$row['comment']);
                            $row['comment'] = substr($row['comment'], 1);
                        }
                    }
                }
            }
            if ($row['info']['gamecomment'] || substr($row['comment'], 0, 5) == "/game" && !$row['name']) {
                //debug("Game Comment: ".$row['comment']);
                $row['gamecomment'] = true;
                $row['skiptalkline'] = true;
                $row['info']['icons'] = array();
                //$length = strlen($row['comment']);
                $row['comment'] = str_replace("/game", "", $row['comment']);
            }
            if ($linkbios && !isset($row['biolink'])) {
                $row['biolink'] = true;
            }
            if ($showmodlink) {
                if ($row['info']['hidecomment']) {
                    //$link = buildcommentarylink("&restorecomment=".$row['commentid']."&comscroll=".$com,$returnlink);
                    $thiscomment .= "`0[<a href='{$restorelink}" . $row['commentid'] . "'>{$undel}</a>]`0 <del>";
                    addnav("", $restorelink . $row['commentid']);
                } else {
                    //$link = buildcommentarylink("&removecomment=".$row['commentid']."&comscroll=".$com,$returnlink);
                    $thiscomment .= "`0[<a href='{$removelink}" . $row['commentid'] . "'>{$del}</a>] <input type='checkbox' name='deletecomment_" . $row['commentid'] . "'> `0 ";
                    addnav("", $removelink . $row['commentid']);
                }
            }
            if (!$row['gamecomment'] && ($row['info']['clanid'] || $row['info']['clanid'] === 0) && $row['info']['clanrank']) {
                $clanrankcolors = array(CLAN_APPLICANT => "`!", CLAN_MEMBER => "`3", CLAN_OFFICER => "`^", CLAN_LEADER => "`&", CLAN_FOUNDER => "`\$");
                $thiscomment .= "`0<a title=\"" . $row['info']['clanname'] . "\">&lt;" . $clanrankcolors[$row['info']['clanrank']] . $row['info']['clanshort'] . "`0&gt;</a>";
            }
            if (!$row['gamecomment']) {
                if ($row['biolink']) {
                    $bio = "bio.php?char=" . $row['acctid'] . "&ret=" . $bioretlink;
                    if (!$row['skiptalkline']) {
                        $thiscomment .= "<a href=\"{$bio}\" style=\"text-decoration: none\">`&" . $row['name'] . "</a>`& ";
                    } else {
                        $thiscomment .= "<a href=\"{$bio}\" style=\"text-decoration: none\">`&" . $row['name'] . "</a>`&";
                    }
                    addnav("", $bio);
                } else {
                    if (!$row['skiptalkline']) {
                        $thiscomment .= "`&" . $row['name'] . "`& ";
                    } else {
                        $thiscomment .= "`&" . $row['name'] . "`&";
                    }
                }
            }
            // if ($row['skiptalkline']){
            // $thiscomment.="`&";
            // }
            if (!$row['skiptalkline']) {
                $thiscomment .= $talkline . " \"";
                if (!isset($row['info']['talkcolour']) || $row['info']['talkcolour'] === false) {
                    $thiscomment .= "`#";
                } else {
                    $thiscomment .= "`" . $row['info']['talkcolour'];
                }
            }
            $thiscomment .= str_replace("&amp;", "&", htmlentities($row['comment'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")));
            $thiscomment .= "`0";
            if (!$row['skiptalkline']) {
                $thiscomment .= "\"";
            }
            if ($row['info']['hidecomment']) {
                $thiscomment .= "</del>";
            }
            $commentbuffer[$i]['comment'] = $thiscomment;
            $commentbuffer[$i]['icons'] = $row['info']['icons'];
            $commentbuffer[$i]['time'] = strtotime($row['postdate']);
            if ($session['user']['prefs']['timestamp'] == 1) {
                if (!isset($session['user']['prefs']['timeformat'])) {
                    $session['user']['prefs']['timeformat'] = "[m/d h:ia]";
                }
                $time = strtotime($row['postdate']) + $session['user']['prefs']['timeoffset'] * 60 * 60;
                $s = date("`7" . $session['user']['prefs']['timeformat'] . "`0 ", $time);
                $commentbuffer[$i]['displaytime'] = $s;
            } elseif ($session['user']['prefs']['timestamp'] == 2) {
                $s = reltime(strtotime($row['postdate']));
                $commentbuffer[$i]['displaytime'] = "<span style='font-family: Courier New, Courier, monospace;'>[{$s}]`0</span> ";
            }
        } else {
            unset($commentbuffer[$i]);
        }
        $bottomcid = $commentbuffer[$i]['commentid'];
    }
    $loop1end = getmicrotime(true);
    $loop1tot = $loop1end - $loop1start;
    //debug("Loop 1: ".$loop1tot);
    //send through a modulehook for additional processing by modules
    $commentbuffer = modulehook("commentbuffer", $commentbuffer);
    //get offline/online/nearby status
    $acctids = join(',', $acctidstoquery);
    $onlinesql = "SELECT acctid, laston, loggedin, chatloc FROM " . db_prefix("accounts") . " WHERE acctid IN ({$acctids})";
    //cache it for 30 seconds
    if (!$com) {
        $onlineresult = db_query_cached($onlinesql, "commentary/whosonline_" . $section, 30);
    } else {
        $onlineresult = db_query($onlinesql);
    }
    $onlinestatus = array();
    $offline = date("Y-m-d H:i:s", strtotime("-" . getsetting("LOGINTIMEOUT", 900) . " seconds"));
    while ($row = db_fetch_assoc($onlineresult)) {
        $onlinestatus[$row['acctid']] = $row;
    }
    $onlinestatus[$session['user']['acctid']]['chatloc'] = $chatloc;
    $commentbuffer = array_values($commentbuffer);
    $rowcount = count($commentbuffer);
    //second loop through - add basic status icons for online/offline/nearby/afk/dnd
    $loop2start = getmicrotime(true);
    for ($i = 0; $i < $rowcount; $i++) {
        if (isset($commentbuffer[$i])) {
            $row = $commentbuffer[$i];
            if ($onlinestatus[$row['author']]['chatloc'] == "AFK") {
                $commentbuffer[$i]['info']['online'] = -1;
                $icon = array('icon' => "images/icons/onlinestatus/afk.png", 'mouseover' => "Away from Keyboard");
                $commentbuffer[$i]['info']['icons']['online'] = $icon;
                continue;
            }
            if ($onlinestatus[$row['author']]['chatloc'] == "DNI") {
                $commentbuffer[$i]['info']['online'] = -1;
                $icon = array('icon' => "images/icons/onlinestatus/dni.png", 'mouseover' => "DNI (please don't try to talk to this player right now!)");
                $commentbuffer[$i]['info']['icons']['online'] = $icon;
                continue;
            }
            if ($onlinestatus[$row['author']]['laston'] < $offline || !$onlinestatus[$row['author']]['loggedin']) {
                $commentbuffer[$i]['info']['online'] = 0;
                $icon = array('icon' => "images/icons/onlinestatus/offline.png", 'mouseover' => "Offline");
            } else {
                if ($onlinestatus[$row['author']]['chatloc'] == $chatloc) {
                    $commentbuffer[$i]['info']['online'] = 2;
                    $icon = array('icon' => "images/icons/onlinestatus/nearby.png", 'mouseover' => "Nearby");
                } else {
                    $commentbuffer[$i]['info']['online'] = 1;
                    $icon = array('icon' => "images/icons/onlinestatus/online.png", 'mouseover' => "Online");
                }
            }
            $commentbuffer[$i]['info']['icons']['online'] = $icon;
        }
    }
    $loop2end = getmicrotime(true);
    $loop2tot = $loop2end - $loop2start;
    //debug("Loop 2: ".$loop2tot);
    //debug($commentbuffer);
    // $gcend = getmicrotime(true);
    // $gctotal = $gcend - $gcstart;
    // debug("getcommentary execution time: ".$gctotal);
    return $commentbuffer;
}
function getcommentary($section, $limit = 25, $talkline = "says", $commentid = 0)
{
    global $session, $REQUEST_URI, $doublepost, $translation_namespace, $counttoday;
    $textreturn = "";
    if ((int) getsetting("expirecontent", 180) > 0 && e_rand(1, 1000) == 1) {
        $sql = "DELETE FROM " . db_prefix("commentary") . " WHERE postdate<'" . date("Y-m-d H:i:s", strtotime("-" . getsetting("expirecontent", 180) . " days")) . "'";
        db_query($sql);
    }
    $sql = "SELECT COUNT(commentid) AS newadded FROM " . db_prefix("commentary") . " LEFT JOIN " . db_prefix("accounts") . " ON " . db_prefix("accounts") . ".acctid = " . db_prefix("commentary") . ".author WHERE section='{$section}' AND " . db_prefix("accounts") . ".locked=0 AND commentid > '{$commentid}'";
    $result = db_query($sql);
    $row = db_fetch_assoc($result);
    if ($row['newadded'] < 1) {
        return $commentid;
    }
    $newadded = $row['newadded'];
    $commentbuffer = array();
    //		if ($commentid == 0) {
    $sql = "SELECT " . db_prefix("commentary") . ".*, " . db_prefix("accounts") . ".name, " . db_prefix("accounts") . ".acctid, " . db_prefix("accounts") . ".clanrank, " . db_prefix("clans") . ".clanshort FROM " . db_prefix("commentary") . " LEFT JOIN " . db_prefix("accounts") . " ON " . db_prefix("accounts") . ".acctid = " . db_prefix("commentary") . ".author LEFT JOIN " . db_prefix("clans") . " ON " . db_prefix("clans") . ".clanid=" . db_prefix("accounts") . ".clanid WHERE " . ($section ? "section='{$section}' AND " : '') . "( " . db_prefix("accounts") . ".locked=0 OR " . db_prefix("accounts") . ".locked is null ) " . "AND commentid > '{$cid}' " . "ORDER BY commentid DESC LIMIT {$limit}";
    $result = db_query($sql);
    while ($row = db_fetch_assoc($result)) {
        $commentbuffer[] = $row;
    }
    /*		} else {
    			$sql = "SELECT " . db_prefix("commentary") . ".*, " .
    				db_prefix("accounts").".name, " . 
    				db_prefix("accounts").".login, " . 
    				db_prefix("accounts").".clanrank, " .
    				db_prefix("clans").".clanshort FROM " .
    				db_prefix("commentary") . " INNER JOIN " .
    				db_prefix("accounts") . " ON " .
    				db_prefix("accounts").".acctid = " .
    				db_prefix("commentary"). ".author LEFT JOIN " .
    				db_prefix("clans") . " ON " .
    				db_prefix("clans") . ".clanid=" .
    				db_prefix("accounts") .".clanid WHERE section = '$section' AND " .
    				db_prefix("accounts") . ".locked=0 AND commentid > '$commentid' ORDER BY commentid ASC LIMIT $limit";
    				$result = db_query($sql);
    				while ($row = db_fetch_assoc($result)) $commentbuffer[] = $row;
    				$commentbuffer = array_reverse($commentbuffer);
    		}
    */
    $rowcount = count($commentbuffer);
    if ($rowcount > 0) {
        $session['lastcommentid'] = $commentbuffer[0]['commentid'];
        $lastcommentid = $commentbuffer[0]['commentid'];
    }
    $counttoday = 0;
    for ($i = 0; $i < $rowcount; $i++) {
        $row = $commentbuffer[$i];
        $row['comment'] = comment_sanitize($row['comment']);
        $commentids[$i] = $row['commentid'];
        if (date("Y-m-d", strtotime($row['postdate'])) == date("Y-m-d")) {
            if ($row['name'] == $session['user']['name']) {
                $counttoday++;
            }
        }
        $x = 0;
        $ft = "";
        for ($x = 0; strlen($ft) < 5 && $x < strlen($row['comment']); $x++) {
            if (substr($row['comment'], $x, 1) == "`" && strlen($ft) == 0) {
                $x++;
            } else {
                $ft .= substr($row['comment'], $x, 1);
            }
        }
        $location = get_module_pref("location", "ajaxcommentary");
        if ($location) {
            $link = "bio.php?char=" . $row['author'] . "&ret=" . $location;
            addnav("", $link);
        } else {
            $link = '';
        }
        if (substr($ft, 0, 2) == "::") {
            $ft = substr($ft, 0, 2);
        } elseif (substr($ft, 0, 1) == ":") {
            $ft = substr($ft, 0, 1);
        } elseif (substr($ft, 0, 3) == "/me") {
            $ft = substr($ft, 0, 3);
        }
        $row['comment'] = holidayize($row['comment'], 'comment');
        $row['name'] = holidayize($row['name'], 'comment');
        $clanrankcolors = array(CLAN_APPLICANT => "`!", CLAN_MEMBER => "`#", CLAN_OFFICER => "`^", CLAN_LEADER => "`&", CLAN_FOUNDER => "`\$");
        if ($row['clanrank']) {
            $row['name'] = ($row['clanshort'] ? "{$clanrankcolors[$row['clanrank']]}&lt;`2{$row['clanshort']}{$clanrankcolors[$row['clanrank']]}&gt; `&" : "") . $row['name'];
        }
        if ($ft == "::" || $ft == "/me" || $ft == ":") {
            $x = strpos($row['comment'], $ft);
            if ($x !== false) {
                $op[$i] = str_replace("&amp;", "&", HTMLEntities(substr($row['comment'], 0, $x), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0" . ($link ? "<a href='{$link}' style='text-decoration: none'>\n" : "") . "`&{$row['name']}`0" . ($link ? "</a>" : "") . "\n`& " . str_replace("&amp;", "&", HTMLEntities(substr($row['comment'], $x + strlen($ft)), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`n";
                $rawc[$i] = str_replace("&amp;", "&", HTMLEntities(substr($row['comment'], 0, $x), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`&{$row['name']}`0`& " . str_replace("&amp;", "&", HTMLEntities(substr($row['comment'], $x + strlen($ft)), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`n";
            }
        }
        if ($ft == "/game" && !$row['name']) {
            $x = strpos($row['comment'], $ft);
            //if ($x!==false){
            $op[$i] = str_replace("&amp;", "&", htmlentities(substr($row['comment'], 0, $x), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`&" . str_replace("&amp;", "&", htmlentities(substr($row['comment'], $x + strlen($ft)), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`n";
            //}
        }
        if (!isset($op) || !is_array($op)) {
            $op = array();
        }
        if (!array_key_exists($i, $op) || $op[$i] == "") {
            $op[$i] = "`0" . ($link ? "<a href='{$link}' style='text-decoration: none'>\n" : "") . "`&{$row['name']}`0" . ($link ? "</a>" : "") . "`3 says, \"`#" . str_replace("&amp;", "&", HTMLEntities($row['comment'], ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`3\"`0`n";
            $rawc[$i] = "`&{$row['name']}`3 says, \"`#" . str_replace("&amp;", "&", HTMLEntities($row['comment'], ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`3\"`0`n";
        }
        if (!array_key_exists('timestamp', $session['user']['prefs'])) {
            $session['user']['prefs']['timestamp'] = 0;
        }
        if ($session['user']['prefs']['timestamp'] == 1) {
            if (!isset($session['user']['prefs']['timeformat'])) {
                $session['user']['prefs']['timeformat'] = "[m/d h:ia]";
            }
            $time = strtotime($row['postdate']) + $session['user']['prefs']['timeoffset'] * 60 * 60;
            $s = "`7" . date($session['user']['prefs']['timeformat'], $time) . "`0 ";
            $op[$i] = $s . $op[$i];
        } elseif ($session['user']['prefs']['timestamp'] == 2) {
            $s = reltime(strtotime($row['postdate']));
            $op[$i] = "`7({$s})`0 " . $op[$i];
        }
        if ($row['postdate'] >= $session['user']['recentcomments']) {
            $op[$i] = "<img src='images/new.gif' alt='&gt;' width='3' height='5' align='absmiddle'> " . $op[$i];
        }
        $auth[$i] = $row['author'];
        $rawc[$i] = full_sanitize($rawc[$i]);
        $rawc[$i] = htmlentities($rawc[$i], ENT_QUOTES, getsetting("charset", "ISO-8859-1"));
    }
    $outputcomments = array();
    $sect = "x";
    for (; $i > -1; $i--) {
        $out = "";
        $out .= $op[$i];
        if (!array_key_exists($sect, $outputcomments) || !is_array($outputcomments[$sect])) {
            $outputcomments[$sect] = array();
        }
        array_push($outputcomments[$sect], $out);
    }
    ksort($outputcomments);
    reset($outputcomments);
    $sections = commentarylocs();
    while (list($sec, $v) = each($outputcomments)) {
        reset($v);
        while (list($key, $val) = each($v)) {
            $args = array('commentline' => $val);
            $args = modulehook("viewcommentary", $args);
            $val = $args['commentline'];
            output_notl($val, true);
        }
    }
    return $lastcommentid;
}
function iitems_trader_run()
{
    global $session;
    //	global $module_prefs;
    $op = httpget('op');
    $id = httpget('id');
    $ret = httpget('ret');
    $return = rawurlencode($ret);
    $tradables = get_tradables();
    // debug($tradables);
    $sql = "SELECT uniqueid, acctid, name, sex FROM " . db_prefix('accounts') . " WHERE acctid = " . $id;
    $result = db_query($sql);
    $tradewith = db_fetch_assoc($result);
    $bioname = $tradewith['name'];
    if ($tradewith['sex'] == 0) {
        $subj = "he";
        $obj = "him";
        $poss = "his";
    } else {
        $subj = "she";
        $obj = "her";
        $poss = "her";
    }
    $hookargs = array();
    $hookargs['tradables'] = $tradables;
    $hookargs['tradewith'] = $tradewith;
    $hookargs['return'] = $return;
    // This hook is to allow modules to remove items from the tradables list if
    // the proposed trading partner does not qualify -- for instance, has no card case.
    //	debug("before iitems_tradables-top hook:");
    //	debug($hookargs);
    $hookargs = modulehook("iitems_tradables-top", $hookargs);
    //	debug("after iitems_tradables-top hook:");
    //	debug($hookargs);
    $tradables = $hookargs['tradables'];
    page_header("Trade!");
    switch ($op) {
        case "trade":
            $cantrade = true;
            if (!isset($hookargs['specialdesc'])) {
                switch (count($tradables)) {
                    case 0:
                        $phrase = "nothing";
                        $cantrade = false;
                        break;
                    case 1:
                        // I know, this isn't quite accurate. Should be 'one type of item' -
                        // but that's programmer-speak. Let's stick to English as much as we can.
                        $phrase = "one item";
                        break;
                    default:
                        $phrase = count($tradables) . " different items";
                        break;
                }
            } else {
                switch (count($tradables) - 1) {
                    case 0:
                        $phrase = "nothing, except ";
                        break;
                    case 1:
                        $phrase = "one item and ";
                        break;
                    default:
                        $phrase = count($tradables) - 1 . " different items and ";
                        break;
                }
                $phrase .= $hookargs['specialdesc'];
            }
            output("Searching through your possessions, you find you have %s you could trade to %s.`n`n", $phrase, $bioname);
            //			debug($tradables);
            if ($cantrade) {
                addnav("Trade");
                foreach ($tradables as $key => $details) {
                    addnav(array("(%s) %s", $details['quantity'], $details['verbosename']), "runmodule.php?module=iitems_trader&op=tradewarn&id={$id}&item={$key}&ret={$return}");
                }
                $hookargs = modulehook("iitems_tradables-link", $hookargs);
            }
            break;
        case "tradewarn":
            $tradableskey = httpget('item');
            if (!get_module_pref('hastraded')) {
                output("Ah, so you're interested in trading your `b%s`b to someone. All right, that could be a very good move, but listen. You only get to control your own actions. What other people do is up to them. Either... make sure you've agreed on the trade beforehand and `b%s`b is someone you trust to give you whatever you're trading this item for... or think of yourself as a kind philanthropist who's generously giving things away.`n`nNo, seriously. Trading is between you and the other person. Talk to %s, negotiate with %s, haggle with %s, conclude the deal. If %s doesn't deliver the goods this time, hey, you'll know who %s is. You don't have to deal with %s again. The admin and game mods are not police and `iwill not`i intervene, so don't even ask.`n`nWith that obligatory warning out of the way...`0`n`n", $tradables[$tradableskey]['verbosename'], $bioname, $obj, $obj, $obj, $subj, $subj, $obj);
            }
            output("You're quite sure you want to trade your %s to %s?`n`n", $tradables[$tradableskey]['verbosename'], $bioname);
            addnav("Trade");
            addnav("Yes, do it!", "runmodule.php?module=iitems_trader&op=tradefinal&id={$id}&item={$tradableskey}&ret={$return}");
            addnav("Wait, no, not that...", "runmodule.php?module=iitems_trader&op=trade&id={$id}&ret={$return}");
            break;
        case "tradefinal":
            $tradableskey = httpget('item');
            $itemid = $tradables[$tradableskey]['itemid'];
            // This hook is to allow special handling of the transfer for collectibles that need to get fancy.
            // (Example - marbles.) When using this hook, you'll have to:
            //      Do your own transfer to the other player
            //      Change the $item-th row in $hookargs['tradables'] to contain the itemid and verbosename
            //        you want to appear in the trading history and the 'Mission accomplished' message
            //      Set $hookargs['specialhandling'] to 1
            $hookargs['specialhandling'] = 0;
            //	debug("before iitems_tradables-final hook:");
            //	debug($hookargs);
            $hookargs = modulehook("iitems_tradables-final", $hookargs);
            //	debug("after iitems_tradables-final hook:");
            //	debug($hookargs);
            $tradables = $hookargs['tradables'];
            if (!isset($hookargs['specialdesc'])) {
                change_item_owner($itemid, $id);
                $message = $tradables[$tradableskey]['feature'] . ": " . $tradables[$tradableskey]['itemid'] . " (" . $tradables[$tradableskey]['verbosename'] . ") to " . $bioname . ".";
                debuglog($message, $id, false, "trade");
                output("Mission accomplished! %s now has your %s.", $bioname, $tradables[$tradableskey]['verbosename']);
                // send a distraction to tell the other player what they just received.
                require_once "lib/systemmail.php";
                $subj = $tradables[$tradableskey]['verbosename'] . " for your collection";
                $body = $session['user']['name'] . " has just traded you a valuable " . $tradables[$tradableskey]['verbosename'] . "! Awesome!";
                systemmail($id, $subj, $body);
            }
            set_module_pref("hastraded", 1);
            break;
        case "history":
            output("`bRecent Trade History of %s`b`n`n", $bioname);
            $dblog = db_prefix('debuglog');
            $accts = db_prefix('accounts');
            $sql = "SELECT date, actor, target, message FROM " . $dblog . " WHERE actor = " . $id . " AND field = 'trade' ORDER BY date DESC";
            $history = array();
            $result = db_query($sql);
            if (db_num_rows($result) > 0) {
                output("Performed the following trades:`n");
                rawoutput("<table border=0 cellpadding=2 cellspacing=1 bgcolor='#999999'>", true);
                rawoutput("<tr class='trhead'><td>timestamp</td><td>(rel)</td><td>trading action</td></tr>");
                $classcount = 1;
                for ($i = 0; $i < db_num_rows($result); $i++) {
                    $classcount++;
                    $class = $classcount % 2 ? "trdark" : "trlight";
                    rawoutput("<tr class='{$class}'><td>");
                    $row = db_fetch_assoc($result);
                    $time = strtotime($row['date']) + $session['user']['prefs']['timeoffset'] * 60 * 60;
                    $abstime = date("m/d h:ia", $time);
                    $reltime = reltime(strtotime($row['date']));
                    output($abstime);
                    rawoutput("</td><td>");
                    output($reltime);
                    rawoutput("</td><td>");
                    output("traded %s`n", $row['message']);
                    rawoutput("</td></tr>");
                    // end the row
                }
                // end of for
                rawoutput("</table>");
            } else {
                output("Performed no trades.`n");
            }
            $sql = "SELECT date, actor, name, target, message FROM " . $dblog . " LEFT JOIN " . $accts . " ON " . $dblog . ".actor = " . $accts . ".acctid WHERE target = " . $id . " AND field = 'trade' ORDER BY date DESC";
            $rhistory = array();
            $result = db_query($sql);
            if (db_num_rows($result) > 0) {
                output("`nReceived the following items in trade:`n");
                rawoutput("<table border=0 cellpadding=2 cellspacing=1 bgcolor='#999999'>", true);
                rawoutput("<tr class='trhead'><td>timestamp</td><td>(rel)</td><td>who</td><td>trading action</td></tr>");
                $classcount = 1;
                for ($i = 0; $i < db_num_rows($result); $i++) {
                    $classcount++;
                    $class = $classcount % 2 ? "trdark" : "trlight";
                    rawoutput("<tr class='{$class}'><td>");
                    $row = db_fetch_assoc($result);
                    $time = strtotime($row['date']) + $session['user']['prefs']['timeoffset'] * 60 * 60;
                    $abstime = date("m/d h:ia", $time);
                    $reltime = reltime(strtotime($row['date']));
                    output($abstime);
                    rawoutput("</td><td>");
                    output($reltime);
                    rawoutput("</td><td>");
                    output($row['name']);
                    rawoutput("</td><td>");
                    output("traded %s`n", $row['message']);
                    rawoutput("</td></tr>");
                    // end the row
                }
                // end of for
                rawoutput("</table>");
            } else {
                output("`nReceived no items in trade.`n");
            }
            break;
    }
    addnav("Back");
    addnav(array("To %s bio", $poss), "bio.php?char={$id}&ret={$return}");
    page_footer();
    return true;
}
 $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'], reltime(strtotime($row['date'])));
 output("`@Status: %s`n", $statuses[$row['status']]);
 if ($row['closedate']) {
     output("`@Last Update: `^%s`@ on `^%s (%s)`n", $row['closer'], $row['closedate'], reltime(strtotime($row['closedate'])));
 }
 output("`@Body:`^`n");
 output("`\$[ipaddress] `^= `3%s`^`n", $row['ip']);
 $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);
 $body = preg_replace("'([\\[][[:alnum:]_.-]+[\\]])'i", "<span class='colLtRed'>\\1</span>", $body);
 rawoutput("<span style='font-family: fixed-width'>" . nl2br($body) . "</span>");
 commentdisplay("`n`@Commentary:`0`n", "pet-{$id}", "Add information", 200);
 if ($viewpageinfo) {
     output("`n`n`@Page Info:`&`n");
     $row['pageinfo'] = stripslashes($row['pageinfo']);
     $body = HTMLEntities($row['pageinfo'], 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);
     $body = preg_replace("'([\\[][[:alnum:]_.-]+[\\]])'i", "<span class='colLtRed'>\\1</span>", $body);
     rawoutput("<span style='font-family: fixed-width'>" . nl2br($body) . "</span>");
Exemplo n.º 14
0
echo $controller->url_for('profile?username='******'username']);
?>
">
            <?php 
echo htmlReady($user['name']);
?>
        </a>
    <? foreach (StudipKing::is_king($user['user_id'], true) as $text) : ?>
        <?php 
echo Icon::create('crown', 'sort', ['title' => $text])->asImg();
?>
    <? endforeach ?>
    </td>
    <td style="white-space: nowrap;">
        <?php 
echo ucfirst(reltime(time() - $user['last_action']));
?>
    </td>
    <td class="actions" nowrap="nowrap">
    <? if (class_exists("Blubber")) : ?>
        <a href="<?php 
echo URLHelper::getLink('plugins.php/blubber/streams/global', array('mention' => $user['username']));
?>
">
            <?php 
echo Icon::create('blubber', 'clickable', ['title' => _('Blubber diesen Nutzer an')])->asImg();
?>
        </a>
    <? endif ?>

        <a href="<?php 
function clancommentaryoverview_formattedtime($timestamp)
{
    global $session;
    if ($session['user']['prefs']['timestamp'] == 1) {
        if (!isset($session['user']['prefs']['timeformat'])) {
            $session['user']['prefs']['timeformat'] = "[m/d h:ia]";
        }
        $time = strtotime("+{$session['user']['prefs']['timeoffset']} hours", $timestamp);
        return date("`7" . $session['user']['prefs']['timeformat'] . "`0", $time);
    } elseif ($session['user']['prefs']['timestamp'] == 2) {
        return "`7(" . reltime($timestamp) . ")`0";
    } else {
        return "";
    }
}
    output_notl("`n");
    $oip = "";
    $dots = 0;
    output("`bSimilar IP's`b`n");
    for ($x = strlen($ip); $x > 0; $x--) {
        if ($dots > 1) {
            break;
        }
        $thisip = substr($ip, 0, $x);
        $sql = "SELECT name, lastip, uniqueid, laston, gentimecount FROM " . db_prefix("accounts") . " WHERE lastip LIKE '{$thisip}%' AND NOT (lastip LIKE '{$oip}') ORDER BY uniqueid";
        //output("$sql`n");
        $result = db_query($sql);
        if (db_num_rows($result) > 0) {
            output("• IP Filter: %s ", $thisip);
            rawoutput("<a href='#' onClick=\"document.getElementById('ip').value='{$thisip}'; document.getElementById('ipradio').checked = true; return false\">");
            output("Use this filter");
            rawoutput("</a>");
            output_notl("`n");
            while ($row = db_fetch_assoc($result)) {
                output("&nbsp;&nbsp;", true);
                output("• (%s) [%s] `%%s`0 - %s hits, last: %s`n", $row['lastip'], $row['uniqueid'], $row['name'], $row['gentimecount'], reltime(strtotime($row['laston'])));
            }
            output_notl("`n");
        }
        if (substr($ip, $x - 1, 1) == ".") {
            $x--;
            $dots++;
        }
        $oip = $thisip . "%";
    }
}
function claneditor_run()
{
    global $session;
    tlschema("claneditor");
    $dt = httpget("dt");
    $op = httpget('op');
    if ($dt != "") {
        $sql = "SELECT * FROM " . db_prefix("clans") . " WHERE clanid='{$dt}'";
        $result = db_query($sql);
        $claninfo = db_fetch_assoc($result);
        if (db_num_rows($result) == 0) {
            $op = "";
        }
    }
    addcommentary();
    $ranks = array(CLAN_APPLICANT => "`!Applicant`0", CLAN_MEMBER => "`#Member`0", CLAN_OFFICER => "`^Officer`0", CLAN_LEADER => "`&Leader`0", CLAN_FOUNDER => "`\$Founder");
    $args = modulehook("clanranks", array("ranks" => $ranks, "clanid" => $dt));
    $ranks = translate_inline($args['ranks'], "clan");
    superusernav();
    addnav("Clans");
    addnav("List Clans", "runmodule.php?module=claneditor&op=list");
    addnav("Create a New Clan", "runmodule.php?module=claneditor&op=new");
    if ($op == "" || $op == "list") {
        page_header("Clan Listing");
        rawoutput("<table border='0' padding='0'><tr><td>");
        $sql = "SELECT MAX(" . db_prefix("clans") . ".clanid) AS clanid, MAX(clanname) AS clanname,count(" . db_prefix("accounts") . ".acctid) AS c FROM " . db_prefix("clans") . " LEFT JOIN " . db_prefix("accounts") . " ON " . db_prefix("clans") . ".clanid=" . db_prefix("accounts") . ".clanid AND clanrank>" . CLAN_APPLICANT . " GROUP BY " . db_prefix("clans") . ".clanid ORDER BY c DESC";
        $result = db_query($sql);
        if (db_num_rows($result) > 0) {
            output("`%Karissa`7 steps in as if by magic, listing the clans for you.`n");
            output("`@`bList of Clans:`b`0`n`n");
            $v = 0;
            $memb_n = translate_inline("(%s members)");
            $memb_1 = translate_inline("(%s member)");
            rawoutput('<table cellspacing="0" cellpadding="2" align="left">');
            output_notl("<tr class='trhead'><td>%s</td><td>%s</td></tr>", translate_inline("`b`&Name of Clan`b"), translate_inline("`&`iNumber of Members`i"), true);
            for ($i = 0; $i < db_num_rows($result); $i++) {
                $row = db_fetch_assoc($result);
                if ($row['c'] == 0) {
                    $sql = "DELETE FROM " . db_prefix("clans") . " WHERE clanid={$row['clanid']}";
                    db_query($sql);
                } else {
                    rawoutput('<tr class="' . ($v % 2 ? "trlight" : "trdark") . '"><td>', true);
                    if ($row['c'] == 1) {
                        $memb = sprintf($memb_1, $row['c']);
                    } else {
                        $memb = sprintf($memb_n, $row['c']);
                    }
                    output_notl("&#149; <a href='runmodule.php?module=claneditor&op=mview&dt=%s'>%s</a></td><td>%s`n", $row['clanid'], full_sanitize(htmlentities($row['clanname']), ENT_COMPAT, getsetting("charset", "ISO-8859-1")), $memb, true);
                    rawoutput('</td></tr>');
                    addnav("", "runmodule.php?module=claneditor&op=mview&dt={$row['clanid']}");
                    $v++;
                }
            }
            rawoutput("</table>", true);
        } else {
            output("`7There are no clans in the database.`n`c");
        }
        rawoutput("</td></tr><tr><td>");
        output_notl("<br>[<a href='runmodule.php?module=claneditor&op=new'>%s</a>]", translate_inline("Create a New Clan"), true);
        addnav("", "runmodule.php?module=claneditor&op=new");
        rawoutput("</td></tr></table>");
        page_footer();
    } elseif ($op == "new") {
        page_header("Clan Creation");
        $apply = httpget('apply');
        if ($apply == 1) {
            $id = httpget("id");
            $ocn = httppost('clanname');
            $ocs = httppost('clanshort');
            $clanname = stripslashes($ocn);
            $clanname = full_sanitize($clanname);
            $clanname = preg_replace("'[^[:alpha:] \\'-]'", "", $clanname);
            $clanname = addslashes($clanname);
            httppostset('clanname', $clanname);
            $clanshort = full_sanitize($ocs);
            $clanshort = preg_replace("'[^[:alpha:]]'", "", $clanshort);
            httppostset('clanshort', $clanshort);
            $sql = "SELECT * FROM " . db_prefix("clans") . " WHERE clanname='{$clanname}'";
            $result = db_query($sql);
            $e = translate_inline("`%Karissa`7 hands you a form to start a clan.");
            $e1 = translate_inline("`%Karissa`7 looks over your form but informs you that your clan name must consist only of letters, spaces, apostrophes, or dashes.  Also, your short name can consist only of letters. She hands you a blank form.");
            $e2 = translate_inline("`%Karissa`7 looks over your form but informs you that you must have at least 5 and no more than 50 characters in your clan's name (and they must consist only of letters, spaces, apostrophes, or dashes), then hands you a blank form.");
            $e3 = translate_inline("`%Karissa`7 looks over your form but informs you that you must have at least 2 and no more than 5 characters in your clan's short name (and they must all be letters), then hands you a blank form.");
            $e4 = translate_inline("`%Karissa`7 looks over your form but informs you that the clan name %s is already taken, and hands you a blank form.");
            $e5 = translate_inline("`%Karissa`7 looks over your form but informs you that the short name %s is already taken, and hands you a blank form.");
            if ($ocs == "" && $ocn == "" && !httppostisset('clanname') && !httppostisset('clanshort')) {
                output_notl($e);
                clanform();
            } elseif ($clanname != $ocn || $clanshort != $ocs) {
                output_notl($e1);
                clanform();
            } elseif (strlen($clanname) < 5 || strlen($clanname) > 50) {
                output_notl($e2);
                clanform();
            } elseif (strlen($clanshort) < 2 || strlen($clanshort) > 5) {
                output_notl($e3);
                clanform();
            } elseif (db_num_rows($result) > 0) {
                output_notl($e4, stripslashes($clanname));
                clanform();
            } else {
                $sql = "SELECT * FROM " . db_prefix("clans") . " WHERE clanshort='{$clanshort}'";
                $result = db_query($sql);
                if (db_num_rows($result) > 0) {
                    output_notl($e5, stripslashes($clanshort));
                    clanform();
                } else {
                    $sql = "INSERT INTO " . db_prefix("clans") . " (clanname,clanshort) VALUES ('{$clanname}','{$clanshort}')";
                    db_query($sql);
                    $clid = db_insert_id();
                    $sql = "UPDATE " . db_prefix("accounts") . " SET clanid='{$clid}',clanrank='" . CLAN_LEADER . "' WHERE acctid='{$id}'";
                    db_query($sql);
                    $subj = "New Clan!";
                    $msg = array("%s`0`^ has made you a new clan!", $session['user']['name']);
                    systemmail($id, $subj, $msg);
                    output("`%Karissa`7 looks over your form, and finding that everything seems to be in order, she takes your fees, stamps the form \"`\$APPROVED`7\" and files it in a drawer.`n`n");
                    output("Congratulations, you've created a new clan named %s!", stripslashes($clanname));
                }
            }
        } elseif ($apply == 0) {
            clanuserform();
        } else {
            output("`7You teleport to the Clan Hall...");
            output("`7You approach `%Karissa`7 and mention that you would like to start a new clan.");
            output("She tells you that there are three requirements to starting a clan.");
            output("First, you have to decide on a full name for your clan.");
            output("Second, you have to decide on an abbreviation for your clan.");
            output("Third you have to decide on the person that should run the clan.");
            $e = translate_inline("`n`n\"`5If you're ok with these three requirements, please fill out the following form,`7\" she says, handing you a sheet of paper.");
            output_notl($e);
            clanuserform();
        }
    } else {
        if ($op != "deleteclan") {
            page_header("The Clan of %s", full_sanitize($claninfo['clanname']));
            output("`n`c`^`bThe Clan of %s`b`c`n`n", full_sanitize($claninfo['clanname']));
        } else {
            page_header("Clan Deletion");
        }
        if ($op == "mview") {
            $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid={$claninfo['motdauthor']}";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $motdauthname = $row['name'];
            $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid={$claninfo['descauthor']}";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $descauthname = $row['name'];
            output("`&`bCurrent MoTD:`b `#by %s`2`n", $motdauthname);
            output_notl(nltoappon($claninfo['clanmotd']) . "`n`n");
            commentdisplay("", "clan-{$claninfo['clanid']}", "Speak into their Clan", 25, "projects");
            output_notl("`n`n");
            modulehook("collapse{", array("name" => "collapsedesc"));
            output("`&`bCurrent Description:`b `#by %s`2`n", $descauthname);
            output_notl(nltoappon($claninfo['clandesc']) . "`n");
            modulehook("}collapse");
            $sql = "SELECT count(*) AS c, clanrank FROM " . db_prefix("accounts") . " WHERE clanid={$claninfo['clanid']} GROUP BY clanrank DESC";
            $result = db_query($sql);
            // begin collapse
            modulehook("collapse{", array("name" => "clanmemberdet"));
            output("`n`bMembership Details:`b`n");
            $leaders = 0;
            while ($row = db_fetch_assoc($result)) {
                output_notl($ranks[$row['clanrank']] . ": " . $row['c'] . "`n");
                if ($row['clanrank'] >= CLAN_OFFICER) {
                    $leaders += $row['c'];
                }
            }
            output("`n");
            $noleader = translate_inline("`^There is currently no leader!  Promoting %s`^ to leader as they are the highest ranking member (or oldest member in the event of a tie).`n`n");
            if ($leaders == 0) {
                //There's no leader here, probably because the leader's account
                //expired.
                $sql = "SELECT name,acctid,clanrank FROM " . db_prefix("accounts") . " WHERE clanid={$dt} ORDER BY clanrank DESC, clanjoindate";
                $result = db_query($sql);
                $row = db_fetch_assoc($result);
                $sql = "UPDATE " . db_prefix("accounts") . " SET clanrank=" . CLAN_LEADER . " WHERE acctid='" . $row['acctid'] . "'";
                db_query($sql);
                output_notl($noleader, $row['name']);
            }
            // end collapse
            modulehook("}collapse");
        } elseif ($op == "deleteclan") {
            if (httpget("sop") == "yes") {
                //notify users of the deletion of the clan
                $sql = "SELECT acctid FROM " . db_prefix("accounts") . " WHERE clanid={$dt}";
                $result = db_query($sql);
                $subj = array("Deletion of %s", $claninfo['clanname']);
                $msg = array("The clan you were in, %s, has closed its doors.\nSorry for any inconvenience.", $claninfo['clanname']);
                while ($row = db_fetch_assoc($result)) {
                    systemmail($row['acctid'], $subj, $msg);
                }
                //change the clan if a user is in this clan
                $sql = "UPDATE " . db_prefix("accounts") . " SET clanid=0,clanrank=" . CLAN_APPLICANT . ",clanjoindate='0000-00-00 00:00:00' WHERE clanid={$dt}";
                db_query($sql);
                //change the current users clan if this user was in that clan
                if ($session['user']['clanid'] == $dt) {
                    $session['user']['clanid'] = 0;
                    $session['user']['clanrank'] = CLAN_APPLICANT;
                    $session['user']['clanjoindate'] = '0000-00-00 00:00:00';
                }
                //drop the clan.
                $sql = "DELETE FROM " . db_prefix("clans") . " WHERE clanid={$dt}";
                db_query($sql);
                module_delete_objprefs('clans', $dt);
                $op = "";
                httpset("op", "");
                unset($claninfo);
                $dt = "";
                output("That clan has been wiped.`n");
                output("`@Users within the clan have been notified.");
            } else {
                output("`%`c`bAre you SURE you want to delete this clan?`b`c`n");
                $dc = translate_inline("Delete this clan? Are you sure!");
                rawoutput("[<a href='runmodule.php?module=claneditor&op=deleteclan&sop=yes&dt={$dt}' onClick='return confirm(\"{$dc}\");'>{$dc}</a>]");
                addnav("", "runmodule.php?module=claneditor&op=deleteclan&sop=yes&dt={$dt}");
            }
        } elseif ($op == "editmodule" || $op == "editmodulesave") {
            $mdule = httpget("mdule");
            if ($op == "editmodulesave") {
                // Save module prefs
                $post = httpallpost();
                reset($post);
                while (list($key, $val) = each($post)) {
                    set_module_objpref("clans", $dt, $key, $val, $mdule);
                }
                output("`^Saved!`0`n");
            }
            rawoutput("<form action='runmodule.php?module=claneditor&op=editmodulesave&dt={$dt}&mdule={$mdule}' method='POST'>");
            module_objpref_edit("clans", $mdule, $dt);
            rawoutput("</form>");
            addnav("", "runmodule.php?module=claneditor&op=editmodulesave&dt={$dt}&mdule={$mdule}");
        } elseif ($op == "updinfo") {
            page_header("Update Clan Information");
            $clanmotd = substr(httppost('clanmotd'), 0, 4096);
            if (httppostisset('clanmotd') && $clanmotd != $claninfo['clanmotd']) {
                if ($clanmotd == "") {
                    $mauthor = 0;
                } else {
                    $mauthor = $session['user']['acctid'];
                }
                $sql = "UPDATE " . db_prefix("clans") . " SET clanmotd='{$clanmotd}',motdauthor={$mauthor} WHERE clanid={$claninfo['clanid']}";
                db_query($sql);
                invalidatedatacache("clandata-{$claninfo['clanid']}");
                $claninfo['clanmotd'] = stripslashes($clanmotd);
                output("Updating MoTD`n");
                $claninfo['motdauthor'] = $mauthor;
            }
            $clandesc = httppost('clandesc');
            if (httppostisset('clandesc') && $clandesc != $claninfo['clandesc']) {
                if ($clandesc == "") {
                    $claninfo['descauthor'] = 0;
                    $dauthor = 0;
                } else {
                    $dauthor = $session['user']['acctid'];
                }
                $sql = "UPDATE " . db_prefix("clans") . " SET clandesc='" . addslashes(substr(stripslashes($clandesc), 0, 4096)) . "',descauthor={$dauthor} WHERE clanid={$claninfo['clanid']}";
                db_query($sql);
                invalidatedatacache("clandata-{$claninfo['clanid']}");
                output("Updating description`n");
                $claninfo['clandesc'] = stripslashes($clandesc);
                $claninfo['descauthor'] = $session['user']['acctid'];
            }
            $customsay = httppost('customsay');
            if (httppostisset('customsay') && $customsay != $claninfo['customsay']) {
                $sql = "UPDATE " . db_prefix("clans") . " SET customsay='{$customsay}' WHERE clanid={$claninfo['clanid']}";
                db_query($sql);
                invalidatedatacache("clandata-{$claninfo['clanid']}");
                output("Updating custom say line`n");
                $claninfo['customsay'] = stripslashes($customsay);
            }
            $clanname = httppost('clanname');
            if ($clanname) {
                $clanname = full_sanitize($clanname);
            }
            $clanshort = httppost('clanshort');
            if ($clanshort) {
                $clanshort = full_sanitize($clanshort);
            }
            if (httppostisset('clanname') && $clanname != $claninfo['clanname']) {
                $sql = "UPDATE " . db_prefix("clans") . " SET clanname='{$clanname}' WHERE clanid={$claninfo['clanid']}";
                output("Updating the clan name`n");
                db_query($sql);
                invalidatedatacache("clandata-{$detail}");
                $claninfo['clanname'] = $clanname;
            }
            if (httppostisset('clanshort') && $clanshort != $claninfo['clanshort']) {
                $sql = "UPDATE " . db_prefix("clans") . " SET clanshort='{$clanshort}' WHERE clanid={$claninfo['clanid']}";
                output("Updating the short clan name`n");
                db_query($sql);
                invalidatedatacache("clandata-{$detail}");
                $claninfo['clanshort'] = $clanshort;
            }
            $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid={$claninfo['motdauthor']}";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $motdauthname = $row['name'];
            $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid={$claninfo['descauthor']}";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $descauthname = $row['name'];
            output("`&`bCurrent MoTD:`b `#by %s`2`n", $motdauthname);
            output_notl(nltoappon($claninfo['clanmotd']) . "`n");
            output("`&`bCurrent Description:`b `#by %s`2`n", $descauthname);
            output_notl(nltoappon($claninfo['clandesc']) . "`n");
            rawoutput("<form action='runmodule.php?module=claneditor&op=updinfo&dt={$dt}' method='POST'>");
            addnav("", "runmodule.php?module=claneditor&op=updinfo&dt={$dt}");
            output("`&`bMoTD:`b `7(4096 chars)`n");
            rawoutput("<textarea name='clanmotd' cols='50' rows='10'>" . htmlentities($claninfo['clanmotd'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "</textarea><br>");
            output("`bRenaming:`b`n");
            output("`iLong Name:`i ");
            rawoutput("<input name='clanname' value=\"" . htmlentities($claninfo['clanname'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "\" maxlength=50 size=50>");
            output("`n`iShort Name:`i ");
            rawoutput("<input name='clanshort' value=\"" . htmlentities($claninfo['clanshort'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "\" maxlength=5 size=5>");
            output_notl("`n");
            output("`n`&`bDescription:`b `7(4096 chars)`n");
            if (httppost('block') > "") {
                $blockdesc = translate_inline("Description blocked for inappropriate usage.");
                $sql = "UPDATE " . db_prefix("clans") . " SET descauthor=4294967295, clandesc='{$blockdesc}' where clanid='" . $claninfo['clanid'] . "'";
                output("Blocking public description`n");
                db_query($sql);
                invalidatedatacache("clandata-" . $claninfo['clanid'] . "");
                $claninfo['blockdesc'] = "";
                $claninfo['descauthor'] = 4294967295.0;
            } elseif (httppost('unblock') > "") {
                $sql = "UPDATE " . db_prefix("clans") . " SET descauthor=0, clandesc='' where clanid='" . $claninfo['clanid'] . "'";
                output("Unblocking public description`n");
                db_query($sql);
                invalidatedatacache("clandata-" . $claninfo['clanid'] . "");
                $claninfo['clandesc'] = "";
                $claninfo['descauthor'] = 0;
            }
            $blocked = translate_inline("The clan has been blocked from posting a description.`n");
            if ($claninfo['descauthor'] == 4294967295.0) {
                output_notl("`b`%" . $blocked . "`b");
            }
            rawoutput("<textarea name='clandesc' cols='50' rows='10'>" . htmlentities($claninfo['clandesc'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "</textarea><br>");
            output("`n`&`bCustom Talk Line`b `7(blank means \"says\" -- 15 chars max)`n");
            rawoutput("<input name='customsay' value=\"" . htmlentities($claninfo['customsay'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "\" maxlength=\"15\"><br/>");
            $save = translate_inline("Save");
            rawoutput("<input type='submit' class='button' value=\"{$save}\">");
            $snu = htmlentities(translate_inline("Save & Unblock public description"), ENT_COMPAT, getsetting("charset", "ISO-8859-1"));
            $snb = htmlentities(translate_inline("Save & Block public description"), ENT_COMPAT, getsetting("charset", "ISO-8859-1"));
            if ($claninfo['descauthor'] == "4294967295") {
                rawoutput("<input type='submit' name='unblock' value=\"{$snu}\" class='button'>");
            } else {
                rawoutput("<input type='submit' name='block' value=\"{$snb}\" class='button'>");
            }
            rawoutput("</form>");
        } elseif ($op == "membership") {
            output("This is the clans current membership:`n");
            $setrank = httpget('setrank');
            $who = httpget('who');
            if ($setrank > "") {
                $sql = "UPDATE " . db_prefix("accounts") . " SET clanrank={$setrank} WHERE login='******'";
                db_query($sql);
            }
            $remove = httpget('remove');
            if ($remove > "") {
                $sql = "UPDATE " . db_prefix("accounts") . " SET clanrank=" . CLAN_APPLICANT . ",clanid=0,clanjoindate='0000-00-00 00:00:00' WHERE login='******' AND clanrank<={$session['user']['clanrank']}";
                db_query($sql);
                //delete unread application emails from this user.
                //breaks if the applicant has had their name changed via
                //dragon kill, superuser edit, or lodge color change
                $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE login='******'";
                $row = db_fetch_assoc(db_query($sql));
                $subj = serialize(array($apply_short, $row['name']));
                $sql = "DELETE FROM " . db_prefix("mail") . " WHERE msgfrom=0 AND seen=0 AND subject='{$subj}'";
                db_query($sql);
            }
            $sql = "SELECT acctid,name,login,clanrank,laston,clanjoindate,dragonkills,level FROM " . db_prefix("accounts") . " WHERE clanid={$claninfo['clanid']} ORDER BY clanrank DESC,clanjoindate";
            $result = db_query($sql);
            rawoutput("<table border='0' cellpadding='2' cellspacing='0'>");
            $rank = translate_inline("Rank");
            $name = translate_inline("Name");
            $lev = translate_inline("Level");
            $dk = translate_inline("Dragon Kills");
            $jd = translate_inline("Join Date");
            $lo = translate_inline("Last On");
            $ops = translate_inline("Operations");
            $promote = translate_inline("Promote");
            $demote = translate_inline("Demote");
            $remove = translate_inline("Remove From The Clan");
            $confirm = translate_inline("Are you sure you wish to remove this member from the clan?");
            rawoutput("<tr class='trhead'><td>{$rank}</td><td>{$name}</td><td>{$lev}</td><td>{$dk}</td><td>{$jd}</td><td>{$lo}</td>" . ($session['user']['clanrank'] > CLAN_MEMBER ? "<td>{$ops}</td>" : "") . "</tr>", true);
            $i = 0;
            $tot = 0;
            while ($row = db_fetch_assoc($result)) {
                $i++;
                $tot += $row['dragonkills'];
                rawoutput("<tr class='" . ($i % 2 ? "trlight" : "trdark") . "'>");
                rawoutput("<td>");
                output_notl($ranks[$row['clanrank']]);
                rawoutput("</td><td>");
                $link = "bio.php?char=" . $row['acctid'] . "&ret=" . urlencode($_SERVER['REQUEST_URI']);
                rawoutput("<a href='{$link}'>", true);
                addnav("", $link);
                output_notl("`&%s`0", $row['name']);
                rawoutput("</a>");
                rawoutput("</td><td align='center'>");
                output_notl("`^%s`0", $row['level']);
                rawoutput("</td><td align='center'>");
                output_notl("`\$%s`0", $row['dragonkills']);
                rawoutput("</td><td>");
                output_notl("`3%s`0", $row['clanjoindate']);
                rawoutput("</td><td>");
                output_notl("`#%s`0", reltime(strtotime($row['laston'])));
                rawoutput("</td>");
                rawoutput("<td>");
                rawoutput("[ <a href='runmodule.php?module=claneditor&op=membership&dt={$dt}&setrank=" . ($row['clanrank'] + 1) . "&who=" . rawurlencode($row['login']) . "'>{$promote}</a> | ");
                addnav("", "runmodule.php?module=claneditor&op=membership&dt={$dt}&setrank=" . ($row['clanrank'] + 1) . "&who=" . rawurlencode($row['login']));
                rawoutput("<a href='runmodule.php?module=claneditor&op=membership&dt={$dt}&setrank=" . ($row['clanrank'] - 1) . "&who=" . rawurlencode($row['login']) . "'>{$demote}</a> | ");
                addnav("", "runmodule.php?module=claneditor&op=membership&dt={$dt}&setrank=" . ($row['clanrank'] - 1) . "&who=" . rawurlencode($row['login']));
                rawoutput("<a href='runmodule.php?module=claneditor&op=membership&dt={$dt}&remove=" . rawurlencode($row['login']) . "' onClick=\"return confirm('{$confirm}');\">{$remove}</a> ]");
                addnav("", "runmodule.php?module=claneditor&op=membership&dt={$dt}&remove=" . rawurlencode($row['login']));
                rawoutput("</td>");
                rawoutput("</tr>");
            }
            rawoutput("</table>");
            output("`n`n`^This clan has a total of `\$%s`^ dragon kills.", $tot);
        }
        if ($dt != "" && isset($claninfo)) {
            addnav("Clan Options");
            addnav("Main View", "runmodule.php?module=claneditor&op=mview&dt={$dt}");
            addnav("Update Clan Information", "runmodule.php?module=claneditor&op=updinfo&dt={$dt}");
            addnav("Delete this Clan", "runmodule.php?module=claneditor&op=deleteclan&dt={$dt}");
            addnav("Update Members", "runmodule.php?module=claneditor&op=membership&dt={$dt}");
            addnav("Module Prefs");
            module_editor_navs("prefs-clans", "runmodule.php?module=claneditor&op=editmodule&dt=" . $claninfo['clanid'] . "&mdule=");
        }
    }
    page_footer();
}
function viewcommentary($section, $message = "Interject your own commentary?", $limit = 10, $talkline = "says", $schema = false)
{
    global $session, $REQUEST_URI, $doublepost, $translation_namespace;
    global $emptypost;
    rawoutput("<a name='{$section}'></a>");
    // Let's add a hook for modules to block commentary sections
    $args = modulehook("blockcommentarea", array("section" => $section));
    if (isset($args['block']) && $args['block'] == "yes") {
        return;
    }
    if ($schema === false) {
        $schema = $translation_namespace;
    }
    tlschema("commentary");
    $nobios = array("motd.php" => true);
    if (!array_key_exists(basename($_SERVER['SCRIPT_NAME']), $nobios)) {
        $nobios[basename($_SERVER['SCRIPT_NAME'])] = false;
    }
    if ($nobios[basename($_SERVER['SCRIPT_NAME'])]) {
        $linkbios = false;
    } else {
        $linkbios = true;
    }
    if ($message == "X") {
        $linkbios = true;
    }
    if ($doublepost) {
        output("`\$`bDouble post?`b`0`n");
    }
    if ($emptypost) {
        output("`\$`bWell, they say silence is a virtue.`b`0`n");
    }
    $clanrankcolors = array("`!", "`#", "`^", "`&", "`\$");
    // Needs to be here because scrolling through the commentary pages, entering a bio, then scrolling again forward
    // then re-entering another bio will lead to $com being smaller than 0 and this will lead to an SQL error later on.
    $com = (int) httpget("comscroll");
    if ($com < 0) {
        $com = 0;
    }
    $cc = false;
    if (httpget("comscroll") !== false && (int) $session['lastcom'] == $com + 1) {
        $cid = (int) $session['lastcommentid'];
    } else {
        $cid = 0;
    }
    $session['lastcom'] = $com;
    if ($com > 0 || $cid > 0) {
        // Find newly added comments.
        $sql = "SELECT COUNT(commentid) AS newadded FROM " . db_prefix("commentary") . " LEFT JOIN " . db_prefix("accounts") . " ON " . db_prefix("accounts") . ".acctid = " . db_prefix("commentary") . ".author WHERE section='{$section}' AND " . "(" . db_prefix("accounts") . ".locked=0 or " . db_prefix('accounts') . ".locked is null) AND commentid > '{$cid}'";
        $result = db_query($sql);
        $row = db_fetch_assoc($result);
        $newadded = $row['newadded'];
    } else {
        $newadded = 0;
    }
    $commentbuffer = array();
    if ($cid == 0) {
        $sql = "SELECT " . db_prefix("commentary") . ".*, " . db_prefix("accounts") . ".name, " . db_prefix("accounts") . ".acctid, " . db_prefix("accounts") . ".clanrank, " . db_prefix("clans") . ".clanshort FROM " . db_prefix("commentary") . " LEFT JOIN " . db_prefix("accounts") . " ON " . db_prefix("accounts") . ".acctid = " . db_prefix("commentary") . ".author LEFT JOIN " . db_prefix("clans") . " ON " . db_prefix("clans") . ".clanid=" . db_prefix("accounts") . ".clanid WHERE section = '{$section}' AND " . "( " . db_prefix("accounts") . ".locked=0 OR " . db_prefix("accounts") . ".locked is null ) " . "ORDER BY commentid DESC LIMIT " . $com * $limit . ",{$limit}";
        if ($com == 0 && strstr($_SERVER['REQUEST_URI'], "/moderate.php") !== $_SERVER['REQUEST_URI']) {
            $result = db_query_cached($sql, "comments-{$section}");
        } else {
            $result = db_query($sql);
        }
        while ($row = db_fetch_assoc($result)) {
            $commentbuffer[] = $row;
        }
    } else {
        $sql = "SELECT " . db_prefix("commentary") . ".*, " . db_prefix("accounts") . ".name, " . db_prefix("accounts") . ".acctid, " . db_prefix("accounts") . ".clanrank, " . db_prefix("clans") . ".clanshort FROM " . db_prefix("commentary") . " LEFT JOIN " . db_prefix("accounts") . " ON " . db_prefix("accounts") . ".acctid = " . db_prefix("commentary") . ".author LEFT JOIN " . db_prefix("clans") . " ON " . db_prefix("clans") . ".clanid=" . db_prefix("accounts") . ".clanid WHERE section = '{$section}' AND " . "( " . db_prefix("accounts") . ".locked=0 OR " . db_prefix("accounts") . ".locked is null ) " . "AND commentid > '{$cid}' " . "ORDER BY commentid ASC LIMIT {$limit}";
        $result = db_query($sql);
        while ($row = db_fetch_assoc($result)) {
            $commentbuffer[] = $row;
        }
        $commentbuffer = array_reverse($commentbuffer);
    }
    $rowcount = count($commentbuffer);
    if ($rowcount > 0) {
        $session['lastcommentid'] = $commentbuffer[0]['commentid'];
    }
    $counttoday = 0;
    for ($i = 0; $i < $rowcount; $i++) {
        $row = $commentbuffer[$i];
        $row['comment'] = comment_sanitize($row['comment']);
        $commentids[$i] = $row['commentid'];
        if (date("Y-m-d", strtotime($row['postdate'])) == date("Y-m-d")) {
            if ($row['name'] == $session['user']['name']) {
                $counttoday++;
            }
        }
        $x = 0;
        $ft = "";
        for ($x = 0; strlen($ft) < 5 && $x < strlen($row['comment']); $x++) {
            if (substr($row['comment'], $x, 1) == "`" && strlen($ft) == 0) {
                $x++;
            } else {
                $ft .= substr($row['comment'], $x, 1);
            }
        }
        $link = "bio.php?char=" . $row['acctid'] . "&ret=" . URLEncode($_SERVER['REQUEST_URI']);
        if (substr($ft, 0, 2) == "::") {
            $ft = substr($ft, 0, 2);
        } elseif (substr($ft, 0, 1) == ":") {
            $ft = substr($ft, 0, 1);
        } elseif (substr($ft, 0, 3) == "/me") {
            $ft = substr($ft, 0, 3);
        }
        $row['comment'] = holidayize($row['comment'], 'comment');
        $row['name'] = holidayize($row['name'], 'comment');
        if ($row['clanrank']) {
            $row['name'] = ($row['clanshort'] > "" ? "{$clanrankcolors[ceil($row['clanrank'] / 10)]}&lt;`2{$row['clanshort']}{$clanrankcolors[ceil($row['clanrank'] / 10)]}&gt; `&" : "") . $row['name'];
        }
        if ($ft == "::" || $ft == "/me" || $ft == ":") {
            $x = strpos($row['comment'], $ft);
            if ($x !== false) {
                if ($linkbios) {
                    $op[$i] = str_replace("&amp;", "&", HTMLEntities(substr($row['comment'], 0, $x), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0<a href='{$link}' style='text-decoration: none'>\n`&{$row['name']}`0</a>\n`& " . str_replace("&amp;", "&", HTMLEntities(substr($row['comment'], $x + strlen($ft)), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`n";
                } else {
                    $op[$i] = str_replace("&amp;", "&", HTMLEntities(substr($row['comment'], 0, $x), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`&{$row['name']}`0`& " . str_replace("&amp;", "&", HTMLEntities(substr($row['comment'], $x + strlen($ft)), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`n";
                }
                $rawc[$i] = str_replace("&amp;", "&", HTMLEntities(substr($row['comment'], 0, $x), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`&{$row['name']}`0`& " . str_replace("&amp;", "&", HTMLEntities(substr($row['comment'], $x + strlen($ft)), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`n";
            }
        }
        if ($ft == "/game" && !$row['name']) {
            $x = strpos($row['comment'], $ft);
            if ($x !== false) {
                $op[$i] = str_replace("&amp;", "&", HTMLEntities(substr($row['comment'], 0, $x), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`&" . str_replace("&amp;", "&", HTMLEntities(substr($row['comment'], $x + strlen($ft)), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`n";
            }
        }
        if (!isset($op) || !is_array($op)) {
            $op = array();
        }
        if (!array_key_exists($i, $op) || $op[$i] == "") {
            if ($linkbios) {
                $op[$i] = "`0<a href='{$link}' style='text-decoration: none'>`&{$row['name']}`0</a>`3 says, \"`#" . str_replace("&amp;", "&", HTMLEntities($row['comment'], ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`3\"`0`n";
            } elseif (substr($ft, 0, 5) == '/game' && !$row['name']) {
                $op[$i] = str_replace("&amp;", "&", HTMLEntities($row['comment'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")));
            } else {
                $op[$i] = "`&{$row['name']}`3 says, \"`#" . str_replace("&amp;", "&", HTMLEntities($row['comment'], ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`3\"`0`n";
            }
            $rawc[$i] = "`&{$row['name']}`3 says, \"`#" . str_replace("&amp;", "&", HTMLEntities($row['comment'], ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`3\"`0`n";
        }
        if (!array_key_exists('timestamp', $session['user']['prefs'])) {
            $session['user']['prefs']['timestamp'] = 0;
        }
        $session['user']['prefs']['timeoffset'] = round($session['user']['prefs']['timeoffset'], 1);
        if ($session['user']['prefs']['timestamp'] == 1) {
            if (!isset($session['user']['prefs']['timeformat'])) {
                $session['user']['prefs']['timeformat'] = "[m/d h:ia]";
            }
            $time = strtotime($row['postdate']) + $session['user']['prefs']['timeoffset'] * 60 * 60;
            $s = date("`7" . $session['user']['prefs']['timeformat'] . "`0 ", $time);
            $op[$i] = $s . $op[$i];
        } elseif ($session['user']['prefs']['timestamp'] == 2) {
            $s = reltime(strtotime($row['postdate']));
            $op[$i] = "`7({$s})`0 " . $op[$i];
        }
        if ($message == "X") {
            $op[$i] = "`0({$row['section']}) " . $op[$i];
        }
        if ($row['postdate'] >= $session['user']['recentcomments']) {
            $op[$i] = "<img src='images/new.gif' alt='&gt;' width='3' height='5' align='absmiddle'> " . $op[$i];
        }
        addnav("", $link);
        $auth[$i] = $row['author'];
        if (isset($rawc[$i])) {
            $rawc[$i] = full_sanitize($rawc[$i]);
            $rawc[$i] = htmlentities($rawc[$i], ENT_QUOTES, getsetting("charset", "ISO-8859-1"));
        }
    }
    $i--;
    $outputcomments = array();
    $sect = "x";
    $moderating = false;
    if ($session['user']['superuser'] & SU_EDIT_COMMENTS && $message == "X") {
        $moderating = true;
    }
    $del = translate_inline("Del");
    $scriptname = substr($_SERVER['SCRIPT_NAME'], strrpos($_SERVER['SCRIPT_NAME'], "/") + 1);
    $pos = strpos($_SERVER['REQUEST_URI'], "?");
    $return = $scriptname . ($pos == false ? "" : substr($_SERVER['REQUEST_URI'], $pos));
    $one = strstr($return, "?") == false ? "?" : "&";
    for (; $i >= 0; $i--) {
        $out = "";
        if ($moderating) {
            if ($session['user']['superuser'] & SU_EDIT_USERS) {
                $out .= "`0[ <input type='checkbox' name='comment[{$commentids[$i]}]'> | <a href='user.php?op=setupban&userid=" . $auth[$i] . "&reason=" . rawurlencode($rawc[$i]) . "'>Ban</a> ]&nbsp;";
                addnav("", "user.php?op=setupban&userid={$auth[$i]}&reason=" . rawurlencode($rawc[$i]));
            } else {
                $out .= "`0[ <input type='checkbox' name='comment[{$commentids[$i]}]'> ]&nbsp;";
            }
            $matches = array();
            preg_match("/[(]([^)]*)[)]/", $op[$i], $matches);
            $sect = trim($matches[1]);
            if (substr($sect, 0, 5) != "clan-" || $sect == $section) {
                if (substr($sect, 0, 4) != "pet-") {
                    $out .= $op[$i];
                    if (!isset($outputcomments[$sect]) || !is_array($outputcomments[$sect])) {
                        $outputcomments[$sect] = array();
                    }
                    array_push($outputcomments[$sect], $out);
                }
            }
        } else {
            if ($session['user']['superuser'] & SU_EDIT_COMMENTS) {
                $out .= "`2[<a href='" . $return . $one . "removecomment={$commentids[$i]}&section={$section}&returnpath=" . URLEncode($return) . "'>{$del}</a>`2]`0&nbsp;";
                addnav("", $return . $one . "removecomment={$commentids[$i]}&section={$section}&returnpath=" . URLEncode($return) . "");
            }
            $out .= $op[$i];
            if (!array_key_exists($sect, $outputcomments) || !is_array($outputcomments[$sect])) {
                $outputcomments[$sect] = array();
            }
            array_push($outputcomments[$sect], $out);
        }
    }
    if ($moderating) {
        $scriptname = substr($_SERVER['SCRIPT_NAME'], strrpos($_SERVER['SCRIPT_NAME'], "/") + 1);
        addnav("", "{$scriptname}?op=commentdelete&return=" . URLEncode($_SERVER['REQUEST_URI']));
        $mod_Del1 = htmlentities(translate_inline("Delete Checked Comments"), ENT_COMPAT, getsetting("charset", "ISO-8859-1"));
        $mod_Del2 = htmlentities(translate_inline("Delete Checked & Ban (3 days)"), ENT_COMPAT, getsetting("charset", "ISO-8859-1"));
        $mod_Del_confirm = addslashes(htmlentities(translate_inline("Are you sure you wish to ban this user and have you specified the exact reason for the ban, i.e. cut/pasted their offensive comments?"), ENT_COMPAT, getsetting("charset", "ISO-8859-1")));
        $mod_reason = translate_inline("Reason:");
        $mod_reason_desc = htmlentities(translate_inline("Banned for comments you posted."), ENT_COMPAT, getsetting("charset", "ISO-8859-1"));
        output_notl("<form action='{$scriptname}?op=commentdelete&return=" . URLEncode($_SERVER['REQUEST_URI']) . "' method='POST'>", true);
        output_notl("<input type='submit' class='button' value=\"{$mod_Del1}\">", true);
        output_notl("<input type='submit' class='button' name='delnban' value=\"{$mod_Del2}\" onClick=\"return confirm('{$mod_Del_confirm}');\">", true);
        output_notl("`n{$mod_reason} <input name='reason0' size='40' value=\"{$mod_reason_desc}\" onChange=\"document.getElementById('reason').value=this.value;\">", true);
    }
    //output the comments
    ksort($outputcomments);
    reset($outputcomments);
    $sections = commentarylocs();
    $needclose = 0;
    while (list($sec, $v) = each($outputcomments)) {
        if ($sec != "x") {
            if ($needclose) {
                modulehook("}collapse");
            }
            output_notl("`n<hr><a href='moderate.php?area=%s'>`b`^%s`0`b</a>`n", $sec, isset($sections[$sec]) ? $sections[$sec] : "({$sec})", true);
            addnav("", "moderate.php?area={$sec}");
            modulehook("collapse{", array("name" => "com-" . $sec));
            $needclose = 1;
        } else {
            modulehook("collapse{", array("name" => "com-" . $section));
            $needclose = 1;
        }
        reset($v);
        while (list($key, $val) = each($v)) {
            $args = array('commentline' => $val);
            $args = modulehook("viewcommentary", $args);
            $val = $args['commentline'];
            output_notl($val, true);
        }
    }
    if ($moderating && $needclose) {
        modulehook("}collapse");
        $needclose = 0;
    }
    if ($moderating) {
        output_notl("`n");
        rawoutput("<input type='submit' class='button' value=\"{$mod_Del1}\">");
        rawoutput("<input type='submit' class='button' name='delnban' value=\"{$mod_Del2}\" onClick=\"return confirm('{$mod_Del_confirm}');\">");
        output_notl("`n%s ", $mod_reason);
        rawoutput("<input name='reason' size='40' id='reason' value=\"{$mod_reason_desc}\">");
        rawoutput("</form>");
        output_notl("`n");
    }
    if ($session['user']['loggedin']) {
        $args = modulehook("insertcomment", array("section" => $section));
        if (array_key_exists("mute", $args) && $args['mute'] && !($session['user']['superuser'] & SU_EDIT_COMMENTS)) {
            output_notl("%s", $args['mutemsg']);
        } elseif ($counttoday < $limit / 2 || $session['user']['superuser'] & ~SU_DOESNT_GIVE_GROTTO || !getsetting('postinglimit', 1)) {
            if ($message != "X") {
                $message = "`n`@{$message}`n";
                output($message);
                talkform($section, $talkline, $limit, $schema);
            }
        } else {
            $message = "`n`@{$message}`n";
            output($message);
            output("Sorry, you've exhausted your posts in this section for now.`0`n");
        }
    }
    $jump = false;
    if (!isset($session['user']['prefs']['nojump']) || $session['user']['prefs']['nojump'] == false) {
        $jump = true;
    }
    $firstu = translate_inline("&lt;&lt; First Unseen");
    $prev = translate_inline("&lt; Previous");
    $ref = translate_inline("Refresh");
    $next = translate_inline("Next &gt;");
    $lastu = translate_inline("Last Page &gt;&gt;");
    if ($rowcount >= $limit || $cid > 0) {
        $sql = "SELECT count(commentid) AS c FROM " . db_prefix("commentary") . " WHERE section='{$section}' AND postdate > '{$session['user']['recentcomments']}'";
        $r = db_query($sql);
        $val = db_fetch_assoc($r);
        $val = round($val['c'] / $limit + 0.5, 0) - 1;
        if ($val > 0) {
            $first = comscroll_sanitize($REQUEST_URI) . "&comscroll=" . $val;
            $first = str_replace("?&", "?", $first);
            if (!strpos($first, "?")) {
                $first = str_replace("&", "?", $first);
            }
            $first .= "&refresh=1";
            if ($jump) {
                $first .= "#{$section}";
            }
            output_notl("<a href=\"{$first}\">{$firstu}</a>", true);
            addnav("", $first);
        } else {
            output_notl($firstu, true);
        }
        $req = comscroll_sanitize($REQUEST_URI) . "&comscroll=" . ($com + 1);
        $req = str_replace("?&", "?", $req);
        if (!strpos($req, "?")) {
            $req = str_replace("&", "?", $req);
        }
        $req .= "&refresh=1";
        if ($jump) {
            $req .= "#{$section}";
        }
        output_notl("<a href=\"{$req}\">{$prev}</a>", true);
        addnav("", $req);
    } else {
        output_notl("{$firstu} {$prev}", true);
    }
    $last = appendlink(comscroll_sanitize($REQUEST_URI), "refresh=1");
    // Okay.. we have some smart-ass (or stupidass, you guess) players
    // who think that the auto-reload firefox plugin is a good way to
    // avoid our timeouts.  Won't they be surprised when I take that little
    // hack away.
    $last = appendcount($last);
    $last = str_replace("?&", "?", $last);
    if ($jump) {
        $last .= "#{$section}";
    }
    //if (!strpos($last,"?")) $last = str_replace("&","?",$last);
    //debug($last);
    output_notl("&nbsp;<a href=\"{$last}\">{$ref}</a>&nbsp;", true);
    addnav("", $last);
    if ($com > 0 || $cid > 0 && $newadded > $limit) {
        $req = comscroll_sanitize($REQUEST_URI) . "&comscroll=" . ($com - 1);
        $req = str_replace("?&", "?", $req);
        if (!strpos($req, "?")) {
            $req = str_replace("&", "?", $req);
        }
        $req .= "&refresh=1";
        if ($jump) {
            $req .= "#{$section}";
        }
        output_notl(" <a href=\"{$req}\">{$next}</a>", true);
        addnav("", $req);
        output_notl(" <a href=\"{$last}\">{$lastu}</a>", true);
    } else {
        output_notl("{$next} {$lastu}", true);
    }
    if (!$cc) {
        db_free_result($result);
    }
    tlschema();
    if ($needclose) {
        modulehook("}collapse");
    }
}
function donationextend_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "donation":
            require_once "lib/gamelog.php";
            gamelog("Donation registered by donationextend");
            $amt = $args['amt'];
            $id = $args['id'];
            $kitty = get_module_setting("kitty");
            $newkitty = $kitty + $amt;
            set_module_setting("kitty", $newkitty);
            //set last player
            if (!get_module_pref("user_shy", "donationextend", $id)) {
                $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid='{$id}'";
                $result = db_query_cached($sql, "donationextend_lastdonator", 300);
                $row = db_fetch_assoc($result);
                $name = $row['name'] . "`0";
                set_module_setting("lastdonator", $name);
            } else {
                set_module_setting("lastdonator", "Anonymous");
            }
            break;
        case "everyfooter":
            //debug($args,true);
            // Set up and decrement the kitty
            require_once "lib/bars.php";
            $last = get_module_setting("lasttick");
            $ext1 = get_module_setting("extend1cost");
            $player = get_module_setting("lastdonator");
            $player = appoencode(stripslashes($player));
            $elapsed = time() - $last;
            $dropped = 0;
            $droppertenseconds = get_module_setting("extend1cost") / 8640;
            if ($elapsed > 10) {
                $dropped = $droppertenseconds;
            }
            $oldkitty = get_module_setting("kitty");
            $newkitty = $oldkitty - $dropped;
            if ($newkitty < 0) {
                $newkitty = 0;
            }
            //set up display output
            $out = "";
            $sql = "SELECT count(acctid) AS c FROM " . db_prefix("accounts") . " WHERE locked=0";
            $result = db_query_cached($sql, "donationextend_totalplayers", 1800);
            $row = db_fetch_assoc($result);
            $totalplayers = $row['c'];
            if ($newkitty > $ext1) {
                $ext2 = get_module_setting("extend2cost");
                if ($newkitty > $ext2) {
                    $over = $newkitty - $ext2;
                    $bar = simplebar($over, $ext2, 70, 5, "AA00AA", "FFFFFF");
                    $overdisp = number_format($over / 100, 2);
                    //represent as time left to end of Special Extend period
                    $droppersec = get_module_setting("extend1cost") / 86400;
                    $secsleft = round($over / $droppersec);
                    $expirationtime = time() + $secsleft;
                    require_once "lib/datetime.php";
                    $expirein = reltime($expirationtime, false);
                    $out .= "<span style='font-size:smaller'><strong>Special Extend active!</strong><br />" . $bar . "Thank you for your support!  Special Extend expires in " . $expirein . "<br /><a href='runmodule.php?module=donationextend' target='_blank' onclick=\"" . popup("runmodule.php?module=donationextend") . ";return false;\">(what's a Special Extend?)</span></a>";
                } else {
                    $moreneeded = $ext2 - $newkitty;
                    $bar = simplebar($newkitty - $ext1, $ext2 - $ext1, 70, 5, "00FF00", "AA00AA");
                    $moredisp = number_format($moreneeded / 100, 2);
                    $out .= "<span style='font-size:smaller'><strong>Extended Play active!</strong><br />" . $bar . "\$" . $moredisp . " more for <a href='runmodule.php?module=donationextend' target='_blank' onclick=\"" . popup("runmodule.php?module=donationextend") . ";return false;\">Special Extend</a>!</span>";
                }
            } else {
                $moreneeded = $ext1 - $newkitty;
                $moredisp = number_format($moreneeded / 100, 2);
                $bar = fadebar($newkitty, $ext1, 57);
                $perplayer = $moreneeded / 100 / $totalplayers;
                if ($perplayer > 1) {
                    $perplayerdisp = "about " . round($moreneeded / $totalplayers, 4) . " cents per player";
                } else {
                    $perplayerdisp = "about \$" . number_format($moreneeded / 100 / $totalplayers, 2) . " per player";
                }
                $out .= $bar;
                if ($newkitty > 0) {
                    $out .= "<span style='font-size:smaller'>\$" . $moredisp . " more (" . $perplayerdisp . ") for <a href='runmodule.php?module=donationextend' target='_blank' onclick=\"" . popup("runmodule.php?module=donationextend") . ";return false;\">Extended Play</a>!</span>";
                } else {
                    if ($session['user']['loggedin']) {
                        $out .= "<span class='colDkRed'><strong>The kitty is empty!</strong></span>  Improbable Island is entirely dependant on your donations to survive.  When the meter is empty, the Island and its creators are in trouble!  Someone please chuck a couple of bucks in the hat!";
                    }
                }
            }
            global $template;
            //debug($template);
            if (strpos($template['footer'], "{paypal_extras}")) {
                //if (isset($template['{paypal_extras}'])){
                //debug("Yes!");
                $rep = "paypal_extras";
            } else {
                //debug("No!");
                $rep = "paypal";
            }
            //$rep = "paypal_extras";
            //insert display output into page
            if (!array_key_exists($rep, $args) || !is_array($args[$rep])) {
                $args[$rep] = array();
            }
            array_push($args[$rep], $out);
            //write values back to database
            if ($elapsed > 10) {
                set_module_setting("lasttick", time());
                set_module_setting("kitty", $newkitty);
            }
            //debug($args,true);
            addcharstat("Misc");
            addcharstat("Misc", "testing testing woohoo!");
            break;
        case "stamina-newday":
            $kitty = get_module_setting("kitty");
            if ($kitty >= get_module_setting("extend1cost")) {
                require_once "modules/staminasystem/lib/lib.php";
                $bonus = get_module_setting("extend1amt");
                if ($kitty > get_module_setting("extend2cost")) {
                    $bonus += get_module_setting("extend2amt");
                    output("`0Because Improbable Island's players have been especially generous, today is a `b`5Special Extended Play`0`b day - you `2gain`0 some Stamina!`n`n");
                } else {
                    output("`0Because Improbable Island's server costs and advertising budget have been covered quite nicely by donations, today is an `b`2Extended Play`0`b day - you `2gain`0 some Stamina!`n`n");
                }
                if ($session['user']['donation'] > 0) {
                    $bonus = $bonus * 2;
                }
                addstamina($bonus);
            }
            break;
    }
    return $args;
}
}
addnav("Game Settings");
addnav("Standard settings", "configuration.php");
addnav("", $REQUEST_URI);
module_editor_navs('settings', 'configuration.php?op=modulesettings&module=');
if ($op == "") {
    $enum = "enumpretrans";
    require_once "lib/datetime.php";
    $details = gametimedetails();
    $offset = getsetting("gameoffsetseconds", 0);
    for ($i = 0; $i <= 86400 / getsetting("daysperday", 4); $i += 300) {
        $off = $details['realsecstotomorrow'] - ($offset - $i);
        if ($off < 0) {
            $off += 86400;
        }
        $x = strtotime("+" . $off . " secs");
        $str = sprintf_translate("In %s at %s (+%s)", reltime($x), date("h:i a", $x), date("H:i", $i));
        $enum .= ",{$i},{$str}";
    }
    rawoutput(tlbutton_clear());
    $setup = array("Game Setup,title", "loginbanner" => "Login Banner (under login prompt: 255 chars)", "maxonline" => "Max # of players online (0 for unlimited), int", "allowcreation" => "Allow creation of new characters,bool", "gameadminemail" => "Admin Email", "emailpetitions" => "Should submitted petitions be emailed to Admin Email address?,bool", "Enter languages here like this: `i(shortname 2 chars) comma (readable name of the language)`i and continue as long as you wish,note", "serverlanguages" => "Languages available on this server", "defaultlanguage" => "Default Language,enum," . getsetting("serverlanguages", "en,English,fr,Français,dk,Danish,de,Deutsch,es,Español,it,Italian"), "edittitles" => "Should DK titles be editable in user editor,bool", "motditems" => "How many items should be shown on the motdlist,int", "Main Page Display,title", "homeskinselect" => "Should the skin selection widget be shown?,bool", "homecurtime" => "Should the current realm time be shown?,bool", "homenewdaytime" => "Should the time till newday be shown?,bool", "homenewestplayer" => "Should the newest player be shown?,bool", "defaultskin" => "What skin should be the default?,theme", "impressum" => "Tell the world something about the person running this server. (e.g. name and address),textarea", "Beta Setup,title", "beta" => "Enable beta features for all players?,bool", "betaperplayer" => "Enable beta features per player?,bool", "Account Creation,title", "defaultsuperuser" => "Flags automatically granted to new players,bitfield," . ($session['user']['superuser'] | SU_ANYONE_CAN_SET) . " ," . SU_INFINITE_DAYS . ",Infinite Days," . SU_VIEW_SOURCE . ",View Source Code," . SU_DEVELOPER . ",Developer Super Powers (special inc list; god mode; auto defeat master; etc)," . SU_DEBUG_OUTPUT . ",Debug Output", "newplayerstartgold" => "Amount of gold to start a new character with,int", "maxrestartgold" => "Maximum amount of gold a player will get after a dragonkill,int", "maxrestartgems" => "Maximum number of gems a player will get after a dragonkill,int", "requireemail" => "Require users to enter their email address,bool", "requirevalidemail" => "Require users to validate their email address,bool", "blockdupeemail" => "One account per email address,bool", "spaceinname" => "Allow spaces in user names,bool", "allowoddadminrenames" => "Allow admins to enter 'illegal' names in the user editor,bool", "selfdelete" => "Allow player to delete their character,bool", "Commentary/Chat,title", "soap" => "Clean user posts (filters bad language and splits words over 45 chars long),bool", "maxcolors" => "Max # of color changes usable in one comment,range,5,40,1", "postinglimit" => "Limit posts to let one user post only up to 50% of the last posts (else turn it off),bool", "Place names and People names,title", "villagename" => "Name for the main village", "innname" => "Name of the inn", "barkeep" => "Name of the barkeep", "barmaid" => "Name of the barmaid", "bard" => "Name of the bard", "clanregistrar" => "Name of the clan registrar", "deathoverlord" => "Name of the death overlord", "Referral Settings,title", "refereraward" => "How many points will be awarded for a referral?,int", "referminlevel" => "What level does the referral need to reach to credit the referer?,int", "Random events,title", "forestchance" => "Chance for Something Special in the Forest,range,0,100,1", "villagechance" => "Chance for Something Special in any village,range,0,100,1", "innchance" => "Chance for Something Special in the Inn,range,0,100,1", "gravechance" => "Chance for Something Special in the Graveyard,range,0,100,1", "gardenchance" => "Chance for Something Special in the Gardens,range,0,100,1", "Paypal,title", "paypalemail" => "Email address of Admin's paypal account", "paypalcurrency" => "Currency type", "paypalcountry-code" => "What country's predominant language do you wish to have displayed in your PayPal screen?,enum\n\t\t,US,United States,DE,Germany,AI,Anguilla,AR,Argentina,AU,Australia,AT,Austria,BE,Belgium,BR,Brazil,CA,Canada\n\t\t,CL,Chile,C2,China,CR,Costa Rica,CY,Cyprus,CZ,Czech Republic,DK,Denmark,DO,Dominican Republic\n\t\t,EC,Ecuador,EE,Estonia,FI,Finland,FR,France,GR,Greece,HK,Hong Kong,HU,Hungary,IS,Iceland,IN,India\n\t\t,IE,Ireland,IL,Israel,IT,Italy,JM,Jamaica,JP,Japan,LV,Latvia,LT,Lithuania,LU,Luxembourg,MY,Malaysia\n\t\t,MT,Malta,MX,Mexico,NL,Netherlands,NZ,New Zealand,NO,Norway,PL,Poland,PT,Portugal,SG,Singapore,SK,Slovakia\n\t\t,SI,Slovenia,ZA,South Africa,KR,South Korea,ES,Spain,SE,Sweden,CH,Switzerland,TW,Taiwan,TH,Thailand,TR,Turkey\n\t\t,GB,United Kingdom,UY,Uruguay,VE,Venezuela", "paypaltext" => "What text should be displayed as item name in the donations screen(player name will be added after it)?", "(standard: 'Legend of the Green Dragon Site Donation from',note", "General Combat,title", "autofight" => "Allow fighting multiple rounds automatically,bool", "autofightfull" => "Allow fighting until fight is over,enum,0,Never,1,Always,2,Only when not allowed to flee", "Training,title", "automaster" => "Masters hunt down truant students,bool", "multimaster" => "Can players gain multiple levels (challenge multiple masters) per game day?,bool", "displaymasternews" => "Display news if somebody fought his master?,bool", "Clans,title", "allowclans" => "Enable Clan System?,bool", "goldtostartclan" => "Gold to start a clan,int", "gemstostartclan" => "Gems to start a clan,int", "officermoderate" => "Can clan officers who are also moderators moderate their own clan even if they cannot moderate all clans?,bool", "New Days,title", "daysperday" => "Game days per calendar day,range,1,6,1", "specialtybonus" => "Extra daily uses in specialty area,range,0,5,1", "newdaycron" => "Let the newday-runonce run via a cronjob,bool", "The directory is necessary! Do not forget to set the correct one in cron.php in your main game folder!!! ONLY experienced admins should use cron jobbing here,note", "`bAlso make sure you setup a cronjob on your machine using confixx/plesk/cpanel or any other admin panel pointing to the cron.php file in your main folder`b,note", "If you do not know what a Cronjob is... leave it turned off. If you want to know more... check out: <a href='http://wiki.dragonprime.net/index.php?title=Cronjob'>http://wiki.dragonprime.net/index.php?title=Cronjob</a>,note", "resurrectionturns" => "Modify (+ or -) the number of turns deducted after a resurrection as an absolute (number) or relative (number followed by %),text", "Forest,title", "turns" => "Forest Fights per day,range,5,30,1", "dropmingold" => "Forest Creatures drop at least 1/4 of max gold,bool", "suicide" => "Allow players to Seek Suicidally?,bool", "suicidedk" => "Minimum DKs before players can Seek Suicidally?,int", "forestgemchance" => "Player will find a gem one in X times,range,10,100,1", "disablebonuses" => "Should monsters which get buffed with extra HP/Att/Def get a gold+exp bonus?,bool", "forestexploss" => "What percentage of experience should be lost?,range,10,100,1", "Multiple Enemies,title", "multifightdk" => "Multiple monsters will attack players above which amount of dragonkills?,range,8,50,1", "multichance" => "The chance for an attack from multiple enemies is,range,0,100,1", "addexp" => "Additional experience (%) per enemy during multifights?,range,0,15", "instantexp" => "During multi-fights hand out experience instantly?,bool", "maxattacks" => "How many enemies will attack per round (max. value),range,1,10", "allowpackofmonsters" => "Allow multiple monsters of the same type to appear in a battle?,bool", "Random values for type of seeking is added to random base.,note", "multibasemin" => "The base number of multiple enemies at minimum is,range,1,100,2", "multibasemax" => "The base number of multiple enemies at maximum is,range,1,100,3", "multislummin" => "The number of multiple enemies at minimum for slumming is,range,0,100,0", "multislummax" => "The number of multiple enemies at maximum for slumming is,range,0,100,1", "multithrillmin" => "The number of multiple enemies at minimum for thrill seeking is,range,0,100,1", "multithrillmax" => "The number of multiple enemies at maximum for thrill seeking is,range,0,100,2", "multisuimin" => "The number of multiple enemies at minimum for suicide is,range,0,100,2", "multisuimax" => "The number of multiple enemies at maximum for suicide is,range,0,100,4", "Stables,title", "allowfeed" => "Does Merick have feed onhand for creatures,bool", "Companions/Mercenaries,title", "enablecompanions" => "Enable the usage of companions,bool", "companionsallowed" => "How many companions are allowed per player,int", "Modules my alter this value on a per player basis!,note", "companionslevelup" => "Are companions allowed to level up?,bool", "Bank Settings,title", "fightsforinterest" => "Max forest fights remaining to earn interest?,range,0,10,1", "maxinterest" => "Max Interest Rate (%),range,5,10,1", "mininterest" => "Min Interest Rate (%),range,0,5,1", "maxgoldforinterest" => "Over what amount of gold does the bank cease paying interest? (0 for unlimited),int", "borrowperlevel" => "Max player can borrow per level (val * level for max),range5,200,5", "allowgoldtransfer" => "Allow players to transfer gold,bool", "transferperlevel" => "Max player can receive from a transfer (val * level),range,5,100,5", "mintransferlev" => "Min level a player (0 DK's) needs to transfer gold,range,1,5,1", "transferreceive" => "Total transfers a player can receive in one day,range,0,5,1", "maxtransferout" => "Amount player can transfer to others (val * level),range,5,100,5", "innfee" => "Fee for express inn payment (x or x%),int", "Mail Settings,title", "mailsizelimit" => "Message size limit per message,int", "inboxlimit" => "Limit # of messages in inbox,int", "oldmail" => "Automatically delete old messages after (days),int", "superuseryommessage" => "Warning to give when attempting to YoM an admin?", "onlyunreadmails" => "Only unread mail count towards the inbox limit?,bool", "PvP,title", "pvp" => "Enable Slay Other Players,bool", "pvpday" => "Player Fights per day,range,1,10,1", "pvpimmunity" => "Days that new players are safe from PvP,range,1,5,1", "pvpminexp" => "Experience below which player is safe from PvP,int", "pvpattgain" => "Percent of victim experience attacker gains on win,floatrange,.25,20,.25", "pvpattlose" => "Percent of experience attacker loses on loss,floatrange,.25,20,.25", "pvpdefgain" => "Percent of attacker experience defender gains on win,floatrange,.25,20,.25", "pvpdeflose" => "Percent of experience defender loses on loss,floatrange,.25,20,.25", "Content Expiration,title", "expirecontent" => "Days to keep comments and news?  (0 = infinite),int", "expiretrashacct" => "Days to keep never logged-in accounts? (0 = infinite),int", "expirenewacct" => "Days to keep 1 level (0 dragon) accounts? (0 =infinite),int", "expireoldacct" => "Days to keep all other accounts? (0 = infinite),int", "LOGINTIMEOUT" => "Seconds of inactivity before auto-logoff,int", "High Load Optimization,title", "This has been moved to the dbconnect.php,note", "LoGDnet Setup,title", "(LoGDnet requires your PHP configuration to have file wrappers enabled!!),note", "logdnet" => "Register with LoGDnet?,bool", "serverurl" => "Server URL", "serverdesc" => "Server Description (75 chars max)", "logdnetserver" => "Master LoGDnet Server (default http://logdnet.logd.com/)", "curltimeout" => "How long we wait for responses from logdnet.logd.com (in seconds),range,1,10,1|2", "Game day Setup,title", "dayduration" => "Day Duration,viewonly", "curgametime" => "Current game time,viewonly", "curservertime" => "Current Server Time,viewonly", "lastnewday" => "Last new day,viewonly", "nextnewday" => "Next new day,viewonly", "gameoffsetseconds" => "Real time to offset new day,{$enum}", "Translation Setup,title", "enabletranslation" => "Enable the use of the translation engine,bool", "It is strongly recommended to leave this feature turned on.,note", "cachetranslations" => "Cache the translations (datacache must be turned on)?,bool", "permacollect" => "Permanently collect untranslated texts (overrides the next settings!),bool", "collecttexts" => "Are we currently collecting untranslated texts?,viewonly", "tl_maxallowed" => "Collect untranslated texts if you have fewer player than this logged in. (0 never collects),int", "charset" => "Which charset should be used for htmlentities?", "Error Notification,title", "Note: you MUST have data caching turned on if you want to use this feature.  Also the first error within any 24 hour period will not generate a notice; I'm sorry: that's really just how it is for technical reasons.,note", "show_notices" => "Show PHP Notice output?,bool", "notify_on_warn" => "Send notification on site warnings?,bool", "notify_on_error" => "Send notification on site errors?,bool", "notify_address" => "Address to notify", "notify_every" => "Only notify every how many minutes for each distinct error?,int", "Miscellaneous Settings,title", "allowspecialswitch" => "The Barkeeper may help you to switch your specialty?,bool", "maxlistsize" => "Maximum number of items to be shown in the warrior list,int");
    $secstonewday = secondstonextgameday($details);
    $useful_vals = array("dayduration" => round($details['dayduration'] / 60 / 60, 0) . " hours", "curgametime" => getgametime(), "curservertime" => date("Y-m-d h:i:s a"), "lastnewday" => date("h:i:s a", strtotime("-{$details['realsecssofartoday']} seconds")), "nextnewday" => date("h:i:s a", strtotime("+{$details['realsecstotomorrow']} seconds")) . " (" . date("H\\h i\\m s\\s", $secstonewday) . ")");
    loadsettings();
    $vals = $settings + $useful_vals;
    rawoutput("<form action='configuration.php?op=save' method='POST'>");
    addnav("", "configuration.php?op=save");
    showform($setup, $vals);
    rawoutput("</form>");
}
page_footer();
Exemplo n.º 21
0
    </tr>
    <tr>
        <td>
            <?php 
echo _('Zuletzt aktiv');
?>
:
        </td>
        <td colspan="2">
        <? if ($user["changed_timestamp"]): ?>
            <abbr title="<?php 
echo strftime('%x %X', $user['changed_timestamp']);
?>
">
                <?php 
echo reltime($user['changed_timestamp'], true, 2);
?>
            </abbr>
        <? else: ?>
            <?php 
echo _('nie benutzt');
?>
        <? endif; ?>
        </td>
    </tr>
    <tr>
        <td>
            <?php 
echo _('Registriert seit');
?>
:
    }
    tlschema($row['tlschema']);
    if ($row['arguments'] > "") {
        $arguments = array();
        $base_arguments = unserialize($row['arguments']);
        array_push($arguments, $row['newstext']);
        while (list($key, $val) = each($base_arguments)) {
            array_push($arguments, $val);
        }
        $news = call_user_func_array("sprintf_translate", $arguments);
        rawoutput(tlbutton_clear());
    } else {
        $news = translate_inline($row['newstext']);
    }
    tlschema();
    $time = reltime(strtotime($row['newsdate']));
    output_notl("`0" . $time . ": " . $news . "`n");
}
if (db_num_rows($result) == 0) {
    output_notl("`c`2-=-`@=-=`2-=-`@=-=`2-=-`@=-=`2-=-`0`c");
    output("`1`b`c Nothing of note happened this day.  All in all a boring day. `c`b`0");
}
output_notl("`c`2-=-`@=-=`2-=-`@=-=`2-=-`@=-=`2-=-`0`c");
if (!$session['user']['loggedin']) {
    addnav("Login Screen", "index.php?r=" . $r);
} else {
    if ($session['user']['alive']) {
        addnav("Continue");
        villagenav();
    } else {
        tlschema("nav");
function findcomm_findcomment($section, $id)
{
    $sql = "SELECT comment,commentid,postdate FROM " . db_prefix("commentary") . " \r\n\t\t\tWHERE section='{$section}' \r\n\t\t\tAND author='{$id}' \r\n\t\t\tORDER BY commentid ASC";
    $res = db_query($sql);
    $str = "";
    $i = 0;
    require_once "lib/datetime.php";
    while ($row = db_fetch_assoc($res)) {
        $relative_time = reltime(strtotime($row['postdate']));
        $str .= "<input name='del[{$row['commentid']}]' type='checkbox'> - ";
        $str .= "`0({$relative_time}) " . $row['comment'] . "`n";
    }
    return $str;
}
function hundredpointrally_run()
{
    global $session;
    page_header("Rally Headquarters");
    $op = httpget('op');
    //load settings
    $joincost = get_module_setting("joincost", "hundredpointrally");
    $data = @unserialize(get_module_setting("data", "hundredpointrally"));
    if (!is_array($data)) {
        $data = array();
        set_module_setting("data", serialize($data), "hundredpointrally");
    }
    //load pref
    $player = @unserialize(get_module_pref("data", "hundredpointrally"));
    if (!is_array($player)) {
        $player = array();
        set_module_pref("data", serialize($player), "hundredpointrally");
    }
    switch ($op) {
        case "start":
            do_forced_nav(false, false);
            require_once "lib/datetime.php";
            $nextstarttime = reltime($data['next']['starttime'], false);
            if (!$data['next']['starttime']) {
                $nextstarttime = "Undetermined amount of time";
            }
            $seed = get_module_setting("jackpotseed", "hundredpointrally");
            if (!isset($data['next']['jackpot']) || $data['next']['jackpot'] < $seed) {
                $data['next']['jackpot'] = $seed;
                set_module_setting("data", serialize($data), "hundredpointrally");
            }
            output("You head into a building decked out with chequered flags.  It smells of petrol and burning rubber, although there are no cars or motorbikes to be seen.  Noticing that the receptionist is a Robot, you surmise that she must be pumping the scent in artificially in order to create atmosphere.  Which figures, really.`n`n\"`7Hello!`0\" she says in a tinny, cheery warble.  \"`7Are you here to sign up for the Hundred-Point Rally?  The next one starts in -`0\" her voice becomes stilted and mechanical for a moment - \"`&%s TO RACE START JACKPOT VALUE OF %s CIGARETTES ENTRY FEE OF %s CIGARETTES`7.`0\"`n`n", strtoupper($nextstarttime), $data['next']['jackpot'], $joincost);
            if ($data['current']['open']) {
                $currentstarttime = reltime($data['current']['starttime'], false);
                output("\"`7Or, if you prefer, the current Rally is still open.  It started -`0\" the same mechanical, halting tone - \"`&%s AGO CURRENT JACKPOT %s CIGARETTES`7.  You'd have a better chance if you waited for the next one, but you can join this one if you're impatient.  It'll cost you the same either way.\"`n`n", strtoupper($currentstarttime), $data['current']['jackpot']);
            }
            addnav("Join a Rally");
            if ($session['user']['gems'] >= $joincost) {
                if (!$player['activenext']) {
                    addnav("Join the `bnext`b Hundred-Point Rally", "runmodule.php?module=hundredpointrally&op=joinnext");
                }
                if (!$player['activecurrent'] && $data['current']['open']) {
                    addnav("Join the `bcurrent`b Hundred-Point Rally", "runmodule.php?module=hundredpointrally&op=joincurrent");
                }
            }
            addnav("What?");
            addnav("Explain this Rally business to me.", "runmodule.php?module=hundredpointrally&op=explain");
            addnav("Exit");
            villagenav();
            break;
        case "explain":
            do_forced_nav(false, false);
            output("\"`7It's very simple,`0\" says the Robot.  \"`7The Hundred-Point Rally is a race around the World Map.  The winner takes the jackpot - the more people signed up for the Rally, the bigger the Jackpot.  You'll be given a series of fifty co-ordinates that you have to visit in sequence, and you'll also be given another fifty co-ordinates that can be visited in any order you like.  The challenge is not only in speed, but also in your ability to determine the most efficient path to hit all one hundred co-ordinates.  Because the race can be quite long, and because the co-ordinates are only revealed once the race has begun, it may or may not be a good idea to spend some time plotting out your route before heading to the first Rally Point.  Each new Rally starts exactly twenty-four hours `&WARNING SYSTEM CLOCK ERROR WHAT THE HELL WHY IS 24 HOURS THE SAME AS SIX DAYS`7 after the last one ends, and a Rally can last for up to 48 hours.`0\"`n`nYou nod.  \"`#Could you explain that part about the system clock error again?`0\"`n`n\"`&What part?`0\"`n`n\"`#Ah.`0\"`n`n`JTo ensure that players from different time zones have a fair shake every now and then, Rallies aren't tied to game time.  When the Robot says \"24 hours,\" she means 24 hours of your time, not game time (which runs six times faster).  If you're signing up for the next Rally and a start time isn't determined yet, you'll get a Distraction exactly 24 hours before the race begins, and another one at the drop of the chequered flag.  We highly recommend that you have Distractions sent to your E-mail if you're a Rally fan, and you can find the relevant option in your Preferences menu in any Outpost.`n`nRallies end as soon as someone hits all one hundred points - so, for example, if a Rally starts at midnight and ends at 2am, the next Rally will start at 2am the next day - and if `ithat`i Rally takes three hours to complete, then the Rally ends at 5am and the next Rally begins at 5am the next day.  This way, we eventually end up going all the way around the clock, giving players in different timezones a chance to compete in the Rally.`0");
            addnav("Okay, then.");
            addnav("Back to Reception", "runmodule.php?module=hundredpointrally&op=start");
            break;
        case "joinnext":
            do_forced_nav(false, false);
            output("You hand over your Cigarettes.  \"`7Very well.  Your entry has been accepted and you will be notified via Distraction when the race starts.  In the meantime, I suggest you buy a very, very fast Mount.`0\"  The Robot tries to smile.  It doesn't come out too well.");
            $data['next']['competitors'][$session['user']['acctid']]['points'] = 0;
            $data['next']['competitors'][$session['user']['acctid']]['name'] = $session['user']['name'];
            $player['activenext'] = true;
            $session['user']['gems'] -= $joincost;
            $data['next']['jackpot'] += floor($joincost * 0.75);
            set_module_pref("data", serialize($player), "hundredpointrally");
            set_module_setting("data", serialize($data), "hundredpointrally");
            addnav("Exit");
            villagenav();
            break;
        case "joincurrent":
            do_forced_nav(false, false);
            output("You hand over your Cigarettes.  \"`7Very well.  Your entry has been accepted.  Now you had better get out there and race!`0\"  The Robot tries to smile.  It doesn't come out too well.");
            $data['current']['competitors'][$session['user']['acctid']]['points'] = 0;
            $data['current']['competitors'][$session['user']['acctid']]['name'] = $session['user']['name'];
            $session['user']['gems'] -= $joincost;
            $data['current']['jackpot'] += floor($joincost * 0.75);
            $player['activecurrent'] = true;
            set_module_pref("data", serialize($player), "hundredpointrally");
            set_module_setting("data", serialize($data), "hundredpointrally");
            addnav("Exit");
            villagenav();
            break;
        case "showpoints":
            popup_header("Rally Points");
            rawoutput("<table cellpadding=5 cellspacing=5 border=0><tr><td valign='top'>");
            output("`0`bSequenced Points`b`nHit each of these World Map points in the prescribed order:`n");
            foreach ($data['current']['sequencedpoints'] as $order => $loc) {
                list($sx, $sy, $sz) = explode(",", $data['current']['sequencedpoints'][$order]);
                if ($player['sequencedpoints'] > $order) {
                    rawoutput("<del>");
                    output("Point %s: `@%s,%s`0`n", $order, $sx, $sy);
                    rawoutput("</del>");
                } else {
                    if ($player['sequencedpoints'] < $order) {
                        output("Point %s: `\$%s,%s`0`n", $order, $sx, $sy);
                    } else {
                        output(">> Point %s: `Q%s,%s`0`n", $order, $sx, $sy);
                    }
                }
            }
            rawoutput("</td><td valign='top'>");
            output("`0`bUnordered Points`b`nHit each of these World Map points in whatever order seems best to you:`n");
            foreach ($data['current']['unorderedpoints'] as $order => $loc) {
                list($ux, $uy, $uz) = explode(",", $loc);
                if (@in_array($loc, $player['unorderedpoints'])) {
                    rawoutput("<del>");
                    output("`@%s,%s`0`n", $ux, $uy);
                    rawoutput("</del>");
                } else {
                    output("`\$%s,%s`0`n", $ux, $uy);
                }
            }
            rawoutput("</td><td valign='top'>");
            $rankings = hundredpointrally_getrankings();
            output("`bCurrent Rankings`b`n");
            foreach ($rankings as $rank => $info) {
                if ($info['acctid'] == $session['user']['acctid']) {
                    output("`J`b>>`b ");
                }
                output("#%s: %s`0 (%s points)`n", $rank + 1, $info['name'], $info['points']);
            }
            rawoutput("</td></tr></table>");
            popup_footer();
            break;
    }
    page_footer();
}
function viewcommentary($section, $message = "Interject your own commentary?", $limit = 10, $talkline = "says", $schema = false)
{
    global $session, $REQUEST_URI, $doublepost, $translation_namespace;
    global $emptypost;
    global $chatloc;
    $chatloc = $section;
    if ($section) {
        rawoutput("<a name='{$section}'></a>");
        // Let's add a hook for modules to block commentary sections
        $args = modulehook("blockcommentarea", array("section" => $section));
        if (isset($args['block']) && $args['block'] == "yes") {
            return;
        }
    }
    //stops people from clicking on Bio links in the MoTD
    $nobios = array("motd.php" => true);
    if (!array_key_exists(basename($_SERVER['SCRIPT_NAME']), $nobios)) {
        $nobios[basename($_SERVER['SCRIPT_NAME'])] = false;
    }
    if ($nobios[basename($_SERVER['SCRIPT_NAME'])]) {
        $linkbios = false;
    } else {
        $linkbios = true;
    }
    if ($doublepost) {
        output("`\$`bDouble post?`b`0`n");
    }
    if ($emptypost) {
        output("`\$`bWell, they say silence is a virtue.`b`0`n");
    }
    // Needs to be here because scrolling through the commentary pages, entering a bio, then scrolling again forward
    // then re-entering another bio will lead to $com being smaller than 0 and this will lead to an SQL error later on.
    $com = (int) httpget("comscroll");
    if ($com < 0) {
        $com = 0;
    }
    $cc = false;
    if (httpget("comscroll") !== false && (int) $session['lastcom'] == $com + 1) {
        $cid = (int) $session['lastcommentid'];
    } else {
        $cid = 0;
    }
    $session['lastcom'] = $com;
    //getting clans takes up far too much in the way of resources.  What we really need is a brand new commentary table with an info field, into which the clan ranks and icons and such can go.
    //Functionality that keeps information updated such as the player's name, their clan, whether or not they're banned etc. can go away.
    if (!$cid) {
        $cid = 1;
    }
    $sql = "SELECT * FROM " . db_prefix("commentary") . " WHERE commentid > '{$cid}' AND section='{$section}' ORDER BY commentid DESC LIMIT " . $com * $limit . ",{$limit}";
    $result = db_query($sql);
    $commentbuffer = array();
    while ($row = db_fetch_assoc($result)) {
        $row['info'] = @unserialize($row['info']);
        if (!is_array($row['info'])) {
            $row['info'] = array();
        }
        $commentbuffer[] = $row;
    }
    debug($commentbuffer);
    $commentbuffer = modulehook("commentbuffer", $commentbuffer);
    debug($commentbuffer);
    $rowcount = count($commentbuffer);
    if ($rowcount > 0) {
        $session['lastcommentid'] = $commentbuffer[0]['commentid'];
    }
    //obtain return link
    $scriptname = substr($_SERVER['SCRIPT_NAME'], strrpos($_SERVER['SCRIPT_NAME'], "/") + 1);
    $pos = strpos($_SERVER['REQUEST_URI'], "?");
    $return = $scriptname . ($pos == false ? "" : substr($_SERVER['REQUEST_URI'], $pos));
    $one = strstr($return, "?") == false ? "?" : "&";
    //figure out whether to handle absolute or relative time
    if (!array_key_exists('timestamp', $session['user']['prefs'])) {
        $session['user']['prefs']['timestamp'] = 0;
    }
    $session['user']['prefs']['timeoffset'] = round($session['user']['prefs']['timeoffset'], 1);
    //this array of userids means that with a single query we can figure out who's online and nearby
    $acctidstoquery = array();
    //prepare the actual comment line part of the comment
    for ($i = 0; $i < $rowcount; $i++) {
        $thiscomment = "";
        $row = $commentbuffer[$i];
        $row['acctid'] = $row['author'];
        $acctidstoquery[] = $row['author'];
        $row['comment'] = comment_sanitize($row['comment']);
        if (substr($row['comment'], 0, 1) == ":" || substr($row['comment'], 0, 3) == "/me") {
            $row['skiptalkline'] = true;
        }
        if (substr($row['comment'], 0, 5) == "/game" && !$row['name'] || $row['info']['gamecomment']) {
            $row['gamecomment'] = true;
            $row['skiptalkline'] = true;
            $row['info']['icons'] = array();
        }
        if ($linkbios) {
            $row['biolink'] = true;
        }
        if ($session['user']['superuser'] & SU_EDIT_COMMENTS) {
            $row['modlink'] = true;
        }
        if ($row['modlink']) {
            $thiscomment .= "`2[<a href='" . $return . $one . "removecomment=" . $row['commentid'] . "&returnpath=" . URLEncode($return) . "'>{$del}</a>`2] ";
            addnav("", $return . $one . "removecomment=" . $row['commentid'] . "&returnpath=" . URLEncode($return) . "");
        }
        if ($row['biolink'] && !$row['gamecomment']) {
            $bio = "bio.php?char=" . $row['acctid'] . "&ret=" . URLEncode($_SERVER['REQUEST_URI']);
            $thiscomment .= "<a href=\"{$bio}\">`0" . $row['name'] . "`0</a> ";
            addnav("", $bio);
        }
        if (!$row['skiptalkline']) {
            $thiscomment .= $talkline . " \"`#";
        }
        $thiscomment .= str_replace("&amp;", "&", htmlentities($row['comment'], ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0\"";
        $commentbuffer[$i]['comment'] = $thiscomment;
        $commentbuffer[$i]['icons'] = $row['info']['icons'];
        $commentbuffer[$i]['time'] = strtotime($row['postdate']);
        if ($session['user']['prefs']['timestamp'] == 1) {
            if (!isset($session['user']['prefs']['timeformat'])) {
                $session['user']['prefs']['timeformat'] = "[m/d h:ia]";
            }
            $time = strtotime($row['postdate']) + $session['user']['prefs']['timeoffset'] * 60 * 60;
            $s = date("`7" . $session['user']['prefs']['timeformat'] . "`0 ", $time);
            $commentbuffer[$i]['displaytime'] = $s;
        } elseif ($session['user']['prefs']['timestamp'] == 2) {
            $s = reltime(strtotime($row['postdate']));
            $commentbuffer[$i]['displaytime'] = "`7({$s})`0 ";
        }
    }
    //get offline/online/nearby status
    $acctids = join(',', $acctidstoquery);
    $onlinesql = "SELECT acctid, laston, loggedin, chatloc FROM " . db_prefix("accounts") . " WHERE acctid IN ({$acctids})";
    $onlineresult = db_query($onlinesql);
    $onlinestatus = array();
    $offline = date("Y-m-d H:i:s", strtotime("-" . getsetting("LOGINTIMEOUT", 900) . " seconds"));
    while ($row = db_fetch_assoc($onlineresult)) {
        $onlinestatus[$row['acctid']] = $row;
    }
    for ($i = 0; $i < $rowcount; $i++) {
        $row = $commentbuffer[$i];
        if ($onlinestatus[$row['author']]['laston'] < $offline || !$onlinestatus[$row['author']]['loggedin']) {
            $commentbuffer[$row]['online'] = 0;
            $commentbuffer[$row]['icons'][] = "images/offline.png";
        } else {
            if ($onlinestatus[$row['author']]['chatloc'] == $chatloc) {
                $commentbuffer[$row]['online'] = 2;
                $commentbuffer[$row]['icons'][] = "images/nearby.png";
            } else {
                $commentbuffer[$row]['online'] = 1;
                $commentbuffer[$row]['icons'][] = "images/online.png";
            }
        }
    }
    $finaloutput = "";
    //output the comments!
    for ($i = 0; $i < $rowcount; $i++) {
        $row = $commentbuffer[$i];
        $icons = $row['icons'];
        foreach ($icons as $icon) {
            $finaloutput .= $icon;
        }
        $finaloutput .= $row['displaytime'];
        $finaloutput .= $row['comment'];
        output_notl("{$finaloutput}`n");
    }
    // debug($commentbuffer);
    //output the comments
    // ksort($outputcomments);
    // reset($outputcomments);
    // $sections = commentarylocs();
    // $needclose = 0;
    // while (list($sec,$v)=each($outputcomments)){
    // if ($sec!="x") {
    // output_notl("`n<hr><a href='moderate.php?area=%s'>`b`^%s`0`b</a>`n",$sec, isset($sections[$sec]) ? $sections[$sec] : "($sec)", true);
    // addnav("", "moderate.php?area=$sec");
    // }
    // reset($v);
    // while (list($key,$val)=each($v)){
    // $args = array('commentline'=>$val,'area'=>$section);
    // $args = modulehook("viewcommentary", $args);
    // $val = $args['commentinfo'].$args['commentline'];
    // output_notl($val, true);
    // }
    // }
    //Output page jumpers
    // $sql = "SELECT count(commentid) AS c FROM " . db_prefix("commentary") . " WHERE section='$section'";
    // $r = db_query($sql);
    // $val = db_fetch_assoc($r);
    // $val = round($val['c'] / $limit + 0.5,0) - 1;
    rawoutput("<table cellpadding=0 cellspacing=5 width=100%><tr><td valign=\"top\" width=50%>");
    if ($session['user']['loggedin']) {
        if ($message != "X") {
            $message = "`n`@{$message}`n";
            output($message);
            talkform($section, $talkline, $limit, $schema);
        }
    }
    $jump = false;
    if (!isset($session['user']['prefs']['nojump']) || $session['user']['prefs']['nojump'] == false) {
        $jump = true;
    }
    //new-style commentary display with page numbers
    // if (!$cc) db_free_result($result);
    // tlschema();
    // if ($needclose) modulehook("}collapse");
    rawoutput("</td><td valign=\"top\" width=50%>");
    $nlink = comscroll_sanitize($REQUEST_URI);
    $nlink = str_replace("?&", "?", $nlink);
    if (!strpos($nlink, "?")) {
        $nlink = str_replace("&", "?", $nlink);
    }
    $nlink .= "&refresh=1";
    //reinstating back and forward links
    output_notl("`n");
    $prev = translate_inline("&lt;&lt;");
    $next = translate_inline("&gt;&gt;");
    if ($rowcount >= $limit || $cid > 0) {
        $req = comscroll_sanitize($REQUEST_URI) . "&comscroll=" . ($com + 1);
        $req = str_replace("?&", "?", $req);
        if (!strpos($req, "?")) {
            $req = str_replace("&", "?", $req);
        }
        $req .= "&refresh=1";
        if ($jump) {
            $req .= "#{$section}";
        }
        output_notl("<a href=\"{$req}\">{$prev}</a> ", true);
        addnav("", $req);
    }
    output_notl("<a href=\"{$nlink}\">Refresh Commentary</a>", true);
    if ($com > 0 || $cid > 0 && $newadded > $limit) {
        $req = comscroll_sanitize($REQUEST_URI) . "&comscroll=" . ($com - 1);
        $req = str_replace("?&", "?", $req);
        if (!strpos($req, "?")) {
            $req = str_replace("&", "?", $req);
        }
        $req .= "&refresh=1";
        if ($jump) {
            $req .= "#{$section}";
        }
        output_notl(" <a href=\"{$req}\">{$next}</a>", true);
        addnav("", $req);
    }
    //
    addnav("", $nlink);
    output("`n`n`0Jump to commentary page:");
    for ($i = $val; $i >= 0; $i--) {
        $nlink = comscroll_sanitize($REQUEST_URI) . "&comscroll=" . $i;
        $nlink = str_replace("?&", "?", $nlink);
        if (!strpos($nlink, "?")) {
            $nlink = str_replace("&", "?", $nlink);
        }
        $nlink .= "&refresh=1";
        if ($jump) {
            $nlink .= "#{$section}";
        }
        $ndisp = 1 + $val - $i;
        if (httpget('comscroll') != $i) {
            output_notl("<a href=\"{$nlink}\">{$ndisp}</a> ", true);
            addnav("", $nlink);
        } else {
            output_notl("`@{$ndisp}`0 ", true);
        }
    }
    modulehook("commentaryoptions");
    rawoutput("</td></tr></table");
    // *** AJAX CHAT MOD START ***
    //modulehook("viewcommentaryfooter");
    // *** AJAX CHAT MOD END ***
}