function dbProblemHistory($limit, $sortname, $sortorder, $req = NULL)
{
    global $db_query_info;
    $db_query_info = array();
    if ($req == NULL) {
        $req = $_REQUEST;
    }
    $db_query_info['type'] = 'problem-history';
    $problemname = getSoft($req, "p", "");
    //which problem?
    $user = getSoft($req, "user", "");
    if ($problemname == "") {
        return __t("You must enter a non-empty problem name.");
    }
    $db_query_info['problem'] = $problemname;
    $resultdesc = array('y' => __t('Did not crash.'), 'Y' => __t('Correct!'), 'N' => __t('Incorrect.'), 'E' => __t('Internal error.'), 'S' => __t('Saved.'), 's' => __t('Saved.'));
    if (!is_user_logged_in()) {
        return __t("You must log in to view past submissions.");
    }
    if ((userIsAdmin() || userIsAssistant()) && $user != "") {
        $u = get_userdata($user);
        if ($u === false) {
            return sprintf(__t("User number %s not found."), $u);
        }
        $db_query_info['viewuser'] = $user;
    } else {
        $u = wp_get_current_user();
    }
    $uid = $u->ID;
    $uname = $u->user_login;
    global $wpdb;
    $table_name = $wpdb->prefix . "pb_submissions";
    $counts = $wpdb->get_results($wpdb->prepare("SELECT COUNT(1), COUNT(userinput) from {$table_name}\nWHERE userid = %d AND problem = %s", $uid, $problemname), ARRAY_N);
    $count = $counts[0][0];
    $showInputColumn = $counts[0][1] > 0;
    if ($count == 0) {
        return sprintf(__t('We do not have record of any submissions from user %1$s for problem %2$s.'), $uname . ' (#' . $uid . ')', $problemname);
    }
    $knownFields = array(__t("time & ID") => "beginstamp", __t("user code") => "usercode", __t("user input") => "userinput", __t("result") => "result");
    if (array_key_exists($sortname, $knownFields)) {
        $sortString = $knownFields[$sortname] . " " . $sortorder . ", ";
    } else {
        $sortString = "";
    }
    $prep = $wpdb->prepare("SELECT ID, beginstamp, usercode, userinput, result from {$table_name}\nWHERE userid = %d AND problem = %s ORDER BY {$sortString} ID DESC" . $limit, $uid, $problemname);
    $flexirows = array();
    foreach ($wpdb->get_results($prep, ARRAY_A) as $r) {
        $cell = array();
        $cell[__t('user code')] = preBox($r['usercode'], -1, -1);
        if ($showInputColumn) {
            $cell[__t('user input')] = $r['userinput'] === NULL ? '<i>' . __t('n/a') . '</i>' : preBox($r['userinput'], -1, 100000);
        }
        if ($problemname != "visualizer") {
            $cell[__t('result')] = getSoft($resultdesc, $r['result'], $r['result']);
        }
        $cell[__t('time &amp; ID')] = str_replace(' ', '<br/>', $r['beginstamp']) . '<br/>#' . $r['ID'];
        $flexirows[] = array('id' => $r['ID'], 'cell' => $cell);
    }
    return array('total' => $count, 'rows' => $flexirows);
}
function send($problem_info, $from, $to, $student, $slug, $body, $noreply)
{
    global $wpdb, $current_user, $lang;
    $unanswered = getUserID() == $student ? 1 : 0;
    if (getUserID() != $student) {
        $wpdb->update($wpdb->prefix . 'pb_mail', array('unanswered' => 0), array('unanswered' => 1, 'ustudent' => $student, 'problem' => $slug));
    }
    if ($noreply != 'false') {
        // don't redirect
        return "#";
    }
    $insert_to = $to;
    if ($to == 0 && $lang != 'en') {
        $insert_to = getSoft(unserialize(CSCIRCLES_ASST_ID_MAP), $lang, $insert_to);
    }
    $wpdb->insert($wpdb->prefix . 'pb_mail', array('ufrom' => $from, 'uto' => $insert_to, 'ustudent' => $student, 'problem' => $slug, 'body' => $body, 'unanswered' => $unanswered), array('%d', '%d', '%d', '%s', '%s', '%d'));
    $mailref = $wpdb->insert_id;
    if (userIsAdmin() || userIsAssistant()) {
        $mFrom = '"' . __t("CS Circles Assistant") . '" <' . CSCIRCLES_BOUNCE_EMAIL . '>';
    } else {
        $mFrom = '"' . $current_user->user_login . '" <' . $current_user->user_email . '>';
    }
    $subject = __t('CS Circles') . ' - ' . __t('message about') . ' ' . $problem_info['publicname'];
    $contents = $body . "\n===\n";
    $contents .= __t("To send a reply message, please visit") . "\n";
    $contents .= cscurl('mail') . "?who={$student}&what={$slug}&which={$mailref}#m\n";
    $contents .= __t("Problem URL:") . " " . $problem_info['url'] . "\n";
    $contents .= "[" . __t("Sent by CS Circles") . " " . cscurl("homepage") . "]";
    if ($to == 0) {
        // same fallback as admin-options.php
        $to_emailaddr = get_option('cscircles_asst_email', get_userdata(1)->user_email);
        $tmp = getSoft(unserialize(CSCIRCLES_ASST_ID_MAP), $lang, -1);
        if ($lang != 'en' && $tmp != -1) {
            $to_emailaddr = get_user_by('id', $tmp)->user_email;
        }
    } else {
        $to_emailaddr = get_user_by('id', $to)->user_email;
    }
    //pyboxlog($mFrom . " " . $to_emailaddr . " " . $subject . " " . $contents);
    pb_mail($mFrom, $to_emailaddr, $subject, $contents);
    if (get_the_author_meta('pbnocc', getUserID()) != 'true') {
        $to_desc = $to == 0 ? "the CS Circles Assistant" : get_user_by('id', $to)->user_login;
        pb_mail($mFrom, $current_user->user_email, __t("SENT:") . " " . $subject, sprintf(__t("THIS IS A COPY of a message you sent to %s."), $to_desc) . "\n\n" . $contents);
    }
    return $mailref;
}
function footsy()
{
    global $popupBoxen;
    echo $popupBoxen;
    if (class_exists('PLL_Base')) {
        echo '<span id="pylangswitcher">';
        //  echo '<li><a id="notice-trans" href="#">notice! (08-30)</a></li>';
        // these are the publicly-available languages
        foreach (unserialize(PRODUCTION_LANGUAGES) as $lang) {
            if ($lang != pll_current_language()) {
                echo '<li><a href="' . get_permalink(pll_get_post(get_the_ID(), $lang)) . '">' . $lang . '</a></li>';
            }
        }
        // these are the ones in development
        if (userIsAdmin() || userIsTranslator() || userIsAssistant()) {
            foreach (unserialize(DEVELOPMENT_LANGUAGES) as $lang) {
                if ($lang != pll_current_language()) {
                    echo '<li><a href="' . get_permalink(pll_get_post(get_the_ID(), $lang)) . '">' . $lang . '</a></li>';
                }
            }
        }
        // old method:  echo pll_the_languages(array('echo'=>0,'display_names_as' => 'slug','hide_current' => 1));
        if (userIsAdmin() || userIsTranslator() || userIsAssistant()) {
            echo '<li><a href="' . admin_url('edit.php?post_type=page') . '">' . __t('Editor') . '</a></li>';
        }
        echo '</span>';
    }
}
function reselector(&$students, $cstudents)
{
    global $wpdb;
    $problem_table = $wpdb->prefix . "pb_problems";
    $problems = $wpdb->get_results("SELECT * FROM {$problem_table} WHERE facultative = 0 AND lang = '" . pll_current_language() . "' AND lesson IS NOT NULL ORDER BY lesson ASC, boxid ASC", ARRAY_A);
    $problemsByNumber = array();
    foreach ($problems as $prow) {
        $problemsByNumber[$prow['slug']] = $prow;
    }
    $gp = getSoft($_GET, "what", "");
    if ($gp != "" && $gp != "console" && !array_key_exists($gp, $problemsByNumber)) {
        echo sprintf(__t("Problem %s not found (at least in current language)"), $gp);
        return;
    }
    $preamble = "<div class='progress-selector'>\n       <form method='get'><table style='border:none'>";
    if ($cstudents > 0 || userIsAssistant()) {
        // slightly leaky but assistants will want to see progress
        $preamble .= "<tr><td>" . sprintf(__t("View mail with one of your students? (you have %s)"), $cstudents) . '</td><td>';
        $options = array();
        $options[''] = __t('Me');
        if (!userIsAdmin()) {
            foreach ($students as $student) {
                $info = get_userdata($student);
                $options[$info->ID] = userString($info->ID);
            }
        }
        if (userIsAdmin()) {
            $preamble .= 'blank: you; "all": all; id#: user (<a href="' . cscurl('allusers') . '">list</a>) <input style = "padding:0px;width:60px" type="text" name="user" value="' . getSoft($_REQUEST, 'user', '') . '">';
        } else {
            $preamble .= optionsHelper($options, 'who');
        }
        $preamble .= "</td></tr>";
    }
    $preamble .= "<tr><td>" . __t("View mail for another problem?") . "</td><td>";
    $options = array();
    $options[''] = 'all problems';
    foreach ($problems as $problem) {
        if ($problem['type'] == 'code') {
            $options[$problem['slug']] = $problem['publicname'];
        }
    }
    $preamble .= optionsHelper($options, 'what') . "</td></tr>";
    $preamble .= "</td></tr><tr><td colspan='2' style='text-align:center'><input style='width: 25%' type='submit' value='" . __t('Submit') . "'/></tr></td></table></form></div>";
    return $preamble;
}
function tweak_polylang_menu()
{
    global $wp_admin_bar;
    if (class_exists('PLL_Base') && is_admin()) {
        if (pybox_on() && !(userIsTranslator() || userIsAdmin() || userIsAssistant())) {
            $wp_admin_bar->remove_node('languages');
        } else {
            $node = $wp_admin_bar->get_node('languages');
            $node->title = ___t('Filter Listed Pages');
            // 'Languages' is confusing
            $wp_admin_bar->add_node($node);
            // update
            /*      $node = $wp_admin_bar->get_node('all'); doesn't exist any more?
                  $node->title = str_replace(__('Show all languages', 'polylang'), ___t('Show all visible'), $node->title); // similar
                  $wp_admin_bar->add_node($node); // update   */
        }
    }
}
function dbEntireHistory($limit, $sortname, $sortorder, $req = NULL)
{
    global $db_query_info;
    $db_query_info = array();
    if ($req == NULL) {
        $req = $_REQUEST;
    }
    $db_query_info['type'] = 'entire-history';
    $user = getSoft($req, "user", "");
    $problem = getSoft($req, "problemhash", "");
    $resultdesc = array('y' => __t('Did not crash.'), 'Y' => __t('Correct!'), 'N' => __t('Incorrect.'), 'E' => __t('Internal error.'), 'S' => __t('Saved.'), 's' => __t('Saved.'));
    global $current_user;
    get_currentuserinfo();
    global $wpdb;
    if (!is_user_logged_in()) {
        return __t("You must log in to view past submissions.");
    }
    if ($user == "all") {
        $u = "all";
    } elseif ($user == "") {
        $u = $current_user;
    } elseif (userIsAdmin() || userIsAssistant()) {
        $u = get_userdata($user);
        if ($u === false) {
            return __t("User number not found.");
        }
    } else {
        $u = get_userdata($user);
        if ($u === false) {
            return __t("User number not found.");
        }
        if (strcasecmp(get_user_meta($user, 'pbguru', true), $current_user->user_login) != 0) {
            return sprintf(__t("User %s does not have you as their guru."), $user);
        }
    }
    if ($user != "") {
        $db_query_info['viewuser'] = $user;
    }
    // make an associative array indexed by slug
    $problemTable = $wpdb->get_results("SELECT slug, publicname, url FROM " . $wpdb->prefix . "pb_problems WHERE slug IS NOT NULL AND lang = '" . currLang2() . "'", OBJECT_K);
    $whereProblem = "1";
    if ($problem != '') {
        if (!array_key_exists($problem, $problemTable)) {
            return sprintf(__t("Problem %s is unknown."), $problem);
        }
        $whereProblem = $wpdb->prepare("problem = %s", $problem);
    }
    $db_query_info['problem'] = $problem;
    $knownFields = array(__t("userid") => "userid", __t("time &amp; ID") => "beginstamp", __t("problem") => "problem", __t("user code") => "usercode", __t("user input") => "userinput", __t("result") => "result");
    if (array_key_exists($sortname, $knownFields)) {
        $sortString = $knownFields[$sortname] . " " . $sortorder . ", ";
    } else {
        $sortString = "";
    }
    $whereStudent = NULL;
    if ($u == "all") {
        $whereStudent = userIsAdmin() ? "1" : "userid in " . getStudentList();
    } else {
        $uid = $u->ID;
        $whereStudent = $wpdb->prepare("userid = %d", $uid);
    }
    $count = $wpdb->get_var("\nSELECT COUNT(1)\nFROM " . $wpdb->prefix . "pb_submissions \nWHERE {$whereStudent} AND {$whereProblem}");
    if ($count == 0) {
        return __t("We do not have record of any submissions.");
    }
    $prep = "\nSELECT userid, ID, beginstamp, usercode, userinput, result, problem\nFROM " . $wpdb->prefix . "pb_submissions \nWHERE {$whereStudent} AND {$whereProblem}\nORDER BY {$sortString} ID DESC " . $limit;
    $flexirows = array();
    foreach ($wpdb->get_results($prep, ARRAY_A) as $r) {
        $cell = array();
        if ($u == "all") {
            $cell[__t('userid')] = str_replace(' ', "<br>", userString($r['userid'], true));
        }
        $p = $r['problem'];
        if (array_key_exists($p, $problemTable)) {
            $cell[__t('problem')] = '<a class="open-same-window" href="' . $problemTable[$p]->url . '">' . $problemTable[$p]->publicname . '</a>';
        } else {
            $cell[__t('problem')] = $p;
        }
        $cell[__t('user code')] = preBox($r['usercode'], -1, -1);
        $cell[__t('user input')] = $r['userinput'] == NULL ? '<i>' . __t('n/a') . '</i>' : preBox($r['userinput'], -1, 100000);
        if ($p != 'visualizer' && $p != 'visualizer-iframe') {
            $cell[__t('result')] = getSoft($resultdesc, $r['result'], '???');
        } else {
            $cell[__t('result')] = '<i>n/a</i>';
        }
        $cell[__t('time &amp; ID')] = str_replace(' ', '<br/>', $r['beginstamp']) . '<br/>#' . $r['ID'];
        $flexirows[] = array('id' => $r['ID'], 'cell' => $cell);
    }
    return array('total' => $count, 'rows' => $flexirows);
}
function dbMail($limit, $sortname, $sortorder, $req = NULL)
{
    global $db_query_info;
    $db_query_info = array();
    $who = getSoft($req === NULL ? $_REQUEST : $req, "who", "");
    $xwho = getSoft($req === NULL ? $_REQUEST : $req, "xwho", "");
    $what = getSoft($req === NULL ? $_REQUEST : $req, "what", "");
    $xwhat = getSoft($req === NULL ? $_REQUEST : $req, "xwhat", "");
    $unans = getSoft($req === NULL ? $_REQUEST : $req, "unans", "");
    $db_query_info['type'] = 'mail-history';
    $db_query_info['who'] = $who;
    $db_query_info['xwho'] = $xwho;
    $db_query_info['what'] = $what;
    $db_query_info['xwhat'] = $xwhat;
    $db_query_info['unans'] = $unans;
    if (!is_user_logged_in()) {
        return __t("You must log in to view past mail.");
    }
    $where = 'WHERE 1';
    if (userIsAdmin()) {
        $where .= ' AND (uto = ' . getUserID() . ' OR uto = 0 OR ufrom = ' . getUserID() . ' OR ufrom = 0)';
    } else {
        $students = getStudents();
        $students[] = getUserID();
        $where .= ' AND (ustudent IN (' . implode(',', $students) . ') OR uto = ' . getUserID() . ' OR ufrom = ' . getUserID() . ' )';
    }
    if ($who != '') {
        if (!is_numeric($who)) {
            return sprintf(__t("%s must be numeric."), "'who'");
        }
        $who = (int) $who;
        if (userIsAdmin() || getUserID() == $who || getUserID() == guruIDID($who) || userIsAssistant()) {
            $where .= ' AND ustudent = ' . $who;
        } else {
            return __t("Access denied.");
        }
    } else {
        if ($xwho != '') {
            if (!is_numeric($xwho)) {
                return sprintf(__t("%s must be numeric."), "'xwho'");
            }
            $xwho = (int) $xwho;
            $where .= ' AND ustudent != ' . $xwho;
        }
    }
    if ($unans != '') {
        if (!is_numeric($unans)) {
            return sprintf(__t("%s must be numeric."), "'unans'");
        }
        $unans = (int) $unans;
        $where .= ' AND unanswered = ' . $unans;
    }
    global $wpdb;
    if ($what != '') {
        $where .= $wpdb->prepare(' AND problem = %s', $what);
    }
    if ($xwhat != '') {
        $where .= $wpdb->prepare(' AND problem != %s', $xwhat);
    }
    $table_name = $wpdb->prefix . "pb_mail";
    $knownFields = array(__t("from") => "ufrom", __t("to") => "uto", __t("when") => "time", __t("message") => "body", __t("problem") => "problem", __t("replied?") => "unanswered");
    $sortString = array_key_exists($sortname, $knownFields) ? $knownFields[$sortname] . " " . $sortorder . ", " : "";
    $count = $wpdb->get_var("SELECT COUNT(1) from {$table_name} {$where}");
    $prep = "SELECT * from {$table_name} {$where} ORDER BY {$sortString} ID DESC" . $limit;
    //   pyboxlog($prep);
    $flexirows = array();
    foreach ($wpdb->get_results($prep, ARRAY_A) as $r) {
        $cell = array();
        $cell[__t('from')] = nicefiedUsername($r['ufrom']);
        $cell[__t('to')] = nicefiedUsername($r['uto']);
        $url = cscurl('mail') . "?who=" . $r['ustudent'] . "&what=" . $r['problem'] . "&which=" . $r['ID'] . "#m";
        $cell[__t('when')] = str_replace(' ', '<br>', $r['time']);
        if ($what == '') {
            $cell[__t('problem')] = $r['problem'];
        }
        if ($unans == '') {
            $cell[__t('replied?')] = $r['unanswered'] == 1 ? __t('no') : __t('yes');
        }
        $cell[__t('message')] = "<a href='{$url}'>" . preBox($r['body']) . "</a>";
        $flexirows[] = array('id' => $r['ID'], 'cell' => $cell);
    }
    return array('total' => $count, 'rows' => $flexirows);
}
function pyUser($options, $content)
{
    if (!is_user_logged_in()) {
        return __t("You must login to view your user page.");
    }
    global $wpdb;
    $user = wp_get_current_user();
    $uid = $user->ID;
    $students = getStudents();
    $cstudents = count($students);
    $problem_table = $wpdb->prefix . "pb_problems";
    $problems = $wpdb->get_results("SELECT * FROM {$problem_table} WHERE facultative = 0 AND lang = '" . currLang2() . "' AND lesson IS NOT NULL ORDER BY lesson ASC, boxid ASC", ARRAY_A);
    $problemsByNumber = array();
    foreach ($problems as $prow) {
        $problemsByNumber[$prow['slug']] = $prow;
    }
    $gp = getSoft($_GET, "problem", "");
    if ($gp != "" && $gp != "console" && !array_key_exists($gp, $problemsByNumber)) {
        echo sprintf(__t("Problem %s not found (at least in current language)"), $gp);
        return;
    }
    if (userIsAdmin() || userIsAssistant() || $cstudents > 0) {
        $preamble = "<div class='progress-selector'>\n       <form method='get'><table style='border:none'><tr><td>" . sprintf(__t("View one of your students? (you have %s)"), $cstudents) . '</td><td>';
        $options = array();
        $options[''] = __t('Show only me');
        $options['all'] = __t('Summary of all my students');
        if (!userIsAdmin()) {
            foreach ($students as $student) {
                $info = get_userdata($student);
                $options[$info->ID] = userString($info->ID);
            }
        }
        if (userIsAdmin()) {
            $preamble .= 'blank: you; "all": all; id#: user (<a href="' . cscurl('allusers') . '">list</a>) <input style = "padding:0px;width:60px" type="text" name="user" value="' . getSoft($_REQUEST, 'user', '') . '">';
        } else {
            $preamble .= optionsHelper($options, 'user');
        }
        $preamble .= '</td></tr><tr><td>';
        $preamble .= __t("Just show submissions for one problem?");
        $options = array();
        $options[''] = __t('Show all');
        $options['console'] = __t('Console');
        foreach ($problems as $problem) {
            if ($problem['type'] == 'code') {
                $options[$problem['slug']] = $problem['publicname'];
            }
        }
        $preamble .= '</td><td>';
        $preamble .= optionsHelper($options, 'problem');
        $preamble .= "</td></tr><tr><td colspan='2' style='text-align:center'><input style='width: 25%' type='submit' value='" . __t('Submit') . "'/></tr></td></table></form></div>";
        echo $preamble;
    }
    $allStudents = isSoft($_GET, 'user', 'all');
    $viewingAsStudent = '' == getSoft($_GET, 'user', '');
    $allProblems = $gp == "";
    if (!$viewingAsStudent) {
        if ($allProblems) {
            $problem_html = "all problems";
        } else {
            if ($gp == 'console') {
                $problem_html = "Console";
            } else {
                $problem_html = "<a href='" . $problemsByNumber[$gp]['url'] . "'>" . $problemsByNumber[$gp]['publicname'] . "</a>";
            }
        }
    }
    if (!$allStudents && array_key_exists('user', $_GET) && $_GET['user'] != '') {
        if (!is_numeric($_GET['user'])) {
            return __t("User id must be numeric.");
        }
        $getuid = (int) $_GET['user'];
        if (userIsAdmin() || userIsAssistant()) {
            if (get_userdata($getuid) === FALSE) {
                return __t("Invalid user id.");
            }
        } else {
            if (!in_array($getuid, $students)) {
                return __t("Invalid user id.");
            }
        }
        $uid = $getuid;
        $user = get_userdata($uid);
        echo "<div class='history-prenote'>" . sprintf(__t("Now viewing %s for "), $problem_html) . userString($uid) . '</div>';
    }
    if ($allStudents) {
        echo "<div class='history-prenote'>" . sprintf(__t("Now viewing %s for all of your students"), $problem_html) . "</div>";
    }
    /***************** end of header ***************/
    $flexigrids = "";
    $completed_table = $wpdb->prefix . "pb_completed";
    if ($allStudents && !$allProblems && $gp != "console") {
        $flexigrids .= niceFlex('perstudent', sprintf(__t("Solutions by my students for %s"), $problemsByNumber[$_GET['problem']]['publicname']), 'problem-summary', 'dbProblemSummary', array('p' => $_GET['problem']));
    }
    $dbparams = array();
    if (getSoft($_GET, 'user', '') != '') {
        $dbparams['user'] = $_GET['user'];
    }
    if (getSoft($_GET, 'problem', '') != '') {
        $dbparams['problemhash'] = $_GET['problem'];
    }
    $flexigrids .= niceFlex('submittedcode', $allProblems ? __t("Submitted code") : sprintf(__t("Submitted code for %s"), $_GET['problem'] == 'console' ? 'Console' : $problemsByNumber[$_GET['problem']]['publicname']), 'entire-history', 'dbEntireHistory', $dbparams);
    $recent = "";
    if (!$allStudents) {
        // queries more than 6 in order to fill out progress table of all problems
        $completed = $wpdb->get_results("SELECT * FROM {$completed_table} WHERE userid = {$uid} ORDER BY time DESC", ARRAY_A);
        $recent .= '<div class="recent"><span class="latest-title">' . __t("Latest problems completed") . ":</span>";
        // but for now we only use 6 entries for "most recently completed" section
        for ($i = 0; $i < count($completed) && $i < 6; $i++) {
            $p = getSoft($problemsByNumber, $completed[$i]['problem'], FALSE);
            if ($p !== FALSE) {
                if (getSoft($_GET, 'user', '') != '') {
                    if ($problemsByNumber[$p['slug']]['type'] == 'code') {
                        $url = '.?user='******'user'] . '&problem=' . $p['slug'];
                    } else {
                        $url = null;
                    }
                } else {
                    $url = $p['url'];
                }
                $recent .= ' <a class="open-same-window problem-completed" ';
                if ($url != null) {
                    $recent .= ' href="' . $url . '" ';
                }
                $recent .= ' title="' . $completed[$i]['time'] . '">' . $p['publicname'] . '</a>';
            } else {
                $recent .= '[' . $completed[$i]['problem'] . ']';
            }
        }
        $recent .= '</div>';
    }
    $submissions_table = $wpdb->prefix . "pb_submissions";
    $studentTable = '';
    if ($allStudents && !userIsAdmin()) {
        $studentList = getStudentList();
        $where = "WHERE userid in {$studentList}";
        if (!$allProblems) {
            $where .= $wpdb->prepare("and problem LIKE %s", $gp);
        }
        // show number of problems each student completed
        $scompleted = $wpdb->get_results("SELECT userid, count(1) as comps from {$completed_table} {$where} GROUP BY userid", OBJECT_K);
        // show number of submissions by each student for this problem
        $ssubmissions = $wpdb->get_results("SELECT userid, count(1) as subs from {$submissions_table} {$where} GROUP BY userid", OBJECT_K);
        $studentTable .= '<div class="history-note">Student listing (click name to drill down)</div>';
        $studentTable .= '<table>';
        foreach (getStudents() as $stu) {
            $studentTable .= '<tr>';
            $studentTable .= '<td>';
            $studentTable .= '<a class="open-same-window" href="?user='******'&problem=' . $gp . '">';
            $studentTable .= userString($stu);
            $studentTable .= '</a></td>';
            $studentTable .= '<td>';
            if ($allProblems) {
                $studentTable .= (array_key_exists($stu, $scompleted) ? $scompleted[$stu]->comps : 0) . ' completed';
            } else {
                $studentTable .= '<img src="' . UFILES . (array_key_exists($stu, $scompleted) ? 'checked' : 'icon') . '.png"/>';
            }
            $studentTable .= '</td>';
            $studentTable .= '<td>';
            $studentTable .= (array_key_exists($stu, $ssubmissions) ? $ssubmissions[$stu]->subs : 0) . ' submissions';
            $studentTable .= '</td>';
            $studentTable .= '</tr>';
        }
        $studentTable .= '</table>';
    }
    $lessons_table = $wpdb->prefix . "pb_lessons";
    $lessons = $wpdb->get_results("SELECT * FROM {$lessons_table} WHERE lang = '" . currLang2() . "'", ARRAY_A);
    $lessonsByNumber = array();
    foreach ($lessons as $lrow) {
        $lessonsByNumber[$lrow['ordering']] = $lrow;
    }
    $overview = '';
    if ($allProblems || !$allStudents) {
        $overview = '<h2 style="margin-top:5px;text-align:center">' . __t('List of all problems') . ' ' . ($allStudents ? __t('(with #completed)') : __t('(with #submissions)')) . '</h2>';
        if (!$viewingAsStudent) {
            $overview .= "<div style='text-align:center'>Click on the <img style='height:1em,width:1em' src='" . UFILES . "/icon.png'> to drill down.</div>";
        }
        $checkIt = array();
        //array from slug to boolean, whether to check the icon
        $showNum = array();
        //array from slug to number, number to display beside each
        if ($allStudents) {
            if (userIsAdmin() || userIsAssistant()) {
                $completed = $wpdb->get_results("SELECT count(userid), problem from {$completed_table} GROUP BY problem", ARRAY_A);
            } else {
                $studentList = getStudentList();
                $completed = $wpdb->get_results("SELECT count(userid), problem from {$completed_table} WHERE userid in {$studentList} GROUP BY problem", ARRAY_A);
            }
            foreach ($completed as $crow) {
                $showNum[$crow['problem']] = $crow['count(userid)'];
            }
        } else {
            $submissions = $wpdb->get_results("SELECT count(1), problem from {$submissions_table} WHERE userid = {$uid} GROUP BY problem", ARRAY_A);
            foreach ($submissions as $srow) {
                $showNum[$srow['problem']] = $srow['count(1)'];
            }
            foreach ($completed as $crow) {
                // this was queried earlier
                $checkIt[$crow['problem']] = TRUE;
            }
        }
        $overview .= '<table style="width:auto;border:none;margin:0px auto;">';
        $lesson = -1;
        $lrow = NULL;
        $llink = "";
        $firstloop = true;
        foreach ($problems as $prow) {
            if ($prow['lesson'] != $lesson) {
                if (!$firstloop) {
                    $overview .= "</td></tr>\n";
                }
                $firstloop = false;
                $overview .= "<tr><td class='lessoninfo'>";
                $lesson = $prow['lesson'];
                $lrow = $lessonsByNumber[$lesson];
                $overview .= '<a class="open-same-window" href="';
                $llink = get_page_link($lrow['id']);
                $overview .= $llink;
                $overview .= '">';
                $overview .= $lrow['number'] . ": " . $lrow['title'];
                $overview .= '</a></td><td>';
            }
            if (!$viewingAsStudent) {
                // drill-down link
                $url = '.?user='******'user'] . '&problem=' . $prow['slug'];
            } else {
                $url = $prow['url'];
            }
            $overview .= '<a class="open-same-window" ';
            if ($url != null) {
                $overview .= ' href="' . $url . '" ';
            }
            $overview .= '>';
            $overview .= '<table class="history-tablette" ><tr class="history-tablette-top"><td>';
            $overview .= '<img style="margin:-10px 0px" title="' . $prow['publicname'] . '" src="' . UFILES . (isSoft($checkIt, $prow['slug'], TRUE) ? 'checked' : 'icon') . '.png"/>';
            $overview .= '</a></td></tr><tr class="history-tablette-bottom"><td>';
            /*      $overview .= '<a class="open-same-window" ';
                  if ($url != null) $overview .= ' href="' . $url . '" ';
                  $overview .= '>';*/
            $overview .= array_key_exists($prow['slug'], $showNum) ? $showNum[$prow['slug']] : '&nbsp;';
            $overview .= '</td></tr></table></a>';
        }
        $overview .= '</table>';
    }
    return "<div class='userpage'>{$flexigrids} {$recent} {$studentTable} {$overview}</div>";
}