function getRecentRanks($sourceId)
{
    #----------------------------------------------------------------------
    global $WHERE, $sinceDateCondition;
    #--- Get all personal records sorted by event and value
    $records = dbQuery("\n    SELECT   personId, eventId, min({$sourceId}) value\n    FROM     Results result, Competitions competition\n    {$WHERE}   competition.id=competitionId\n      AND    {$sinceDateCondition}\n      AND    {$sourceId}>0\n    GROUP BY eventId, personId\n    ORDER BY eventId, value\n  ");
    #--- Append a sentinel
    $records[] = array('nobody', 'ThisWillCauseTheFinishEventCodeForTheLastEvent');
    #--- Process the personal records, build ranks[event][person]
    foreach ($records as $record) {
        list($personId, $eventId, $value) = $record;
        #--- At new events, finish the previous and reset for the new one
        if ($eventId != $currentEventId) {
            #--- Memorize the previous event's ranks (if any, and if that event is official)
            if ($currentEventId && in_array($currentEventId, getAllEventIds())) {
                $ranks[$currentEventId] = $ranksInCurrentEvent;
            }
            #--- Reset for the new event
            $currentEventId = $eventId;
            unset($currentSize, $currentRank, $currentValue, $ranksInCurrentEvent);
        }
        #--- Update the current event ranklist status
        $currentSize++;
        if ($value != $currentValue) {
            $currentValue = $value;
            $currentRank = $currentSize;
        }
        #--- Memorize the person's rank in this event
        $ranksInCurrentEvent[$personId] = $currentRank;
    }
    #--- Return the event ranks
    return $ranks;
}
function alterTablePreregs()
{
    #----------------------------------------------------------------------
    #--- Alter the field set.
    reportAction("Preregs", "Alter field set");
    dbCommand("\n    ALTER TABLE Preregs\n      ADD    COLUMN `eventIds`  TEXT NOT NULL DEFAULT ''\n  ");
    $i = 0;
    $len = 1000;
    $preregs = dbQuery(" SELECT * FROM Preregs LIMIT {$i},{$len}");
    while (count($preregs) != 0) {
        foreach ($preregs as $prereg) {
            $id = $prereg['id'];
            $eventIds = '';
            foreach (array_merge(getAllEventIds(), getAllUnofficialEventIds()) as $eventId) {
                if ($prereg["E{$eventId}"] != 0) {
                    $eventIds .= "{$eventId} ";
                }
            }
            rtrim($eventIds);
            dbCommand("UPDATE Preregs SET eventIds='{$eventIds}' WHERE id='{$id}'");
        }
        $i += $len;
        $preregs = dbQuery(" SELECT * FROM Preregs LIMIT {$i},{$len}");
    }
    foreach (array_merge(getAllEventIds(), getAllUnofficialEventIds()) as $eventId) {
        dbCommand("ALTER TABLE Preregs\n                 DROP COLUMN `E{$eventId}`");
    }
}
function showResults()
{
    #----------------------------------------------------------------------
    global $chosenRegionId, $chosenSingle, $chosenAverage;
    #------------------------------
    # Prepare stuff for the query.
    #------------------------------
    $regionCondition = regionCondition('result');
    $limitCondition = 'LIMIT 120';
    $valueSource = $chosenAverage ? 'average' : 'best';
    $valueName = $chosenAverage ? 'Average' : 'Single';
    #------------------------------
    # Get results from database.
    #------------------------------
    $limitNumber = 300;
    $ranks = getRanks($valueName, $chosenRegionId);
    list($rows, $header) = sumOfRanks($valueName, getAllEventIds(), $ranks, $limitNumber + 20);
    $header = preg_replace('/ +/', '|', preg_replace('/\\[\\w+\\]/', '', "Rank {$header} "));
    foreach (dbQuery("SELECT id, name FROM Persons WHERE subId=1") as $person) {
        $personName[$person[0]] = $person[1];
    }
    #------------------------------
    # Show the table.
    #------------------------------
    $numColumns = count($rows[0]) + 2;
    $headerAttributes = array(0 => "class='r'", 2 => "class='R2'", $numColumns - 1 => 'class="f"');
    for ($i = 3; $i < $numColumns - 1; $i++) {
        $headerAttributes[$i] = "class='r'";
    }
    tableBegin('results', $numColumns);
    tableCaption(true, chosenRegionName(true));
    #  tableHeader( explode( '|', $header), $headerAttributes );
    $ctr = $previousSumOfRanks = 0;
    $showHeader = true;
    foreach ($rows as $row) {
        $showHeader |= $ctr % 20 == 0;
        list($personId, $sumOfRanks) = $row;
        $ctr++;
        $no = $sumOfRanks == $previousSumOfRanks ? '' : $ctr;
        if ($limitCondition && $no > $limitNumber) {
            break;
        }
        if ($showHeader && $no) {
            tableHeader(explode('|', $header), $headerAttributes);
            $showHeader = false;
        }
        for ($i = 2; $i < $numColumns - 2; $i++) {
            if (preg_match('/^(10|[1-9])$/', $row[$i])) {
                $row[$i] = "<span style='color:#0D0'>{$row[$i]}</span>";
            }
        }
        $row[0] = personLink($row[0], $personName[$row[0]]);
        $row[] = '';
        array_unshift($row, $no);
        tableRow($row);
        $previousSumOfRanks = $sumOfRanks;
    }
    tableEnd();
}
<?php

if (!isset($onlyProvideFunctions)) {
    #--- Get event ranks
    $ranksSingle = getRanks('Single');
    $ranksAverage = getRanks('Average');
    #--- Sum of 3x3/4x4/5x5 ranks, single and average
    list($single) = sumOfRanks('Single', array('333', '444', '555'), $ranksSingle);
    list($average) = sumOfRanks('Average', array('333', '444', '555'), $ranksAverage);
    $lists[] = array("sum_ranks_345", "Sum of 3x3/4x4/5x5 ranks", "Single | Average", "[P] Person [N] Sum [n] 3x3 [n] 4x4 [n] 5x5 [T] | [P] Person [N] Sum [n] 3x3 [n] 4x4 [n] 5x5", my_merge($single, $average));
    #--- Sum of all single ranks
    list($rows, $header) = sumOfRanks('Single', getAllEventIds(), $ranksSingle);
    $lists[] = array("sum_ranks_single", "Sum of all single ranks", "", $header, $rows);
    #--- Sum of all average ranks
    list($rows, $header) = sumOfRanks('Average', getAllEventIds(), $ranksAverage);
    $lists[] = array("sum_ranks_average", "Sum of all average ranks", "", $header, $rows);
}
#----------------------------------------------------------------------
function getRanks($sourceName, $regionId = '')
{
    #----------------------------------------------------------------------
    #--- Build query for the requested region
    $query = "SELECT eventId, personId, worldRank FROM Ranks{$sourceName}";
    if (in_array($regionId, getAllUsedCountriesIds())) {
        $query = "SELECT eventId, personId, countryRank FROM Ranks{$sourceName}, Persons WHERE Persons.id=personId AND subId=1 AND countryId='{$regionId}'";
    }
    if (in_array($regionId, getAllUsedContinentIds())) {
        $query = "SELECT eventId, personId, continentRank FROM Ranks{$sourceName}, Persons, Countries WHERE Persons.id=personId AND subId=1 AND Countries.id=countryId AND continentId='{$regionId}'";
    }
    #--- Process the personal records, build ranks[event][person]
    foreach (dbQuery($query) as $row) {
function savePreregForm()
{
    #----------------------------------------------------------------------
    global $chosenCompetitionId, $competition, $config;
    $personId = getMysqlParam('personId');
    $name = getMysqlParam('name');
    $countryId = getMysqlParam('countryId');
    $gender = getMysqlParam('gender');
    $birthYear = getMysqlParam('birthYear');
    $birthMonth = getMysqlParam('birthMonth');
    $birthDay = getMysqlParam('birthDay');
    $email = getMysqlParam('email');
    $guests = getMysqlParam('guests');
    $comments = getMysqlParam('comments');
    $ip = getMysqlParam('ip');
    if (!$name or !$email or !$gender) {
        noticeBox(false, "Fields 'name', 'gender' and 'email' are required.");
        return false;
    }
    if (!preg_match("/^[_0-9a-zA-Z-]+(\\.[_0-9a-zA-Z-]+)*@[0-9a-zA-Z-]+(\\.[0-9a-zA-Z-]+)*(\\.[a-zA-Z]{2,3})\$/", $email)) {
        noticeBox(false, "Incorrect email address.");
        return false;
    }
    if ($birthYear == date('Y')) {
        noticeBox(false, "Please enter your date of birth.");
        return false;
    }
    if (!$birthYear) {
        $chosenPerson = dbQuery("SELECT * FROM Persons WHERE id='{$personId}'");
        $chosenPerson = $chosenPerson[0];
        $birthYear = $chosenPerson['year'];
        $birthMonth = $chosenPerson['month'];
        $birthDay = $chosenPerson['day'];
    }
    $guests = str_replace(array("\r\n", "\n", "\r", ","), ";", $guests);
    #--- Building query
    $eventIds = '';
    foreach (getAllEventIds() as $eventId) {
        if (getBooleanParam("E{$eventId}")) {
            $eventIds .= "{$eventId} ";
        }
    }
    rtrim($eventIds);
    # Remove last space
    $into = "competitionId, name, personId, countryId, gender, birthYear, birthMonth, birthDay, email, guests, comments, ip, status, eventIds";
    $values = "'{$chosenCompetitionId}', '{$name}', '{$personId}', '{$countryId}', '{$gender}', '{$birthYear}', '{$birthMonth}', '{$birthDay}', '{$email}', '{$guests}', '{$comments}', '{$ip}', 'p', '{$eventIds}'";
    dbCommand("INSERT INTO Preregs ({$into}) VALUES ({$values})");
    $organizers = getCompetitionOrganizers($competition['id']);
    foreach ($organizers as $organizer) {
        $mailEmail = $organizer['email'];
        // load more competition data for a nicer email
        $result = dbQuery("SELECT * FROM Competitions WHERE id='{$chosenCompetitionId}'");
        $competition_data = $result[0];
        $mailBody = "A new competitor has registered for your competition - " . $competition['cellName'] . "! ";
        $mailBody .= "Their information is below.\n-------------------\n";
        if ($personId) {
            $mailBody .= "Name : {$name}";
            $mailBody .= "     {$personId} - https://www.worldcubeassociation.org/results/p.php?i={$personId}\n";
        } else {
            $mailBody .= "Name : {$name}\n";
        }
        $mailBody .= "Country : {$countryId}\n";
        $mailBody .= "Gender : {$gender}\n";
        $mailBody .= "Date of birth : {$birthYear}/{$birthMonth}/{$birthDay}\n";
        $mailBody .= "Email : {$email}\n";
        $mailBody .= "Events : {$eventIds}\n";
        $mailBody .= "Guests : {$guests}\n";
        $mailBody .= "Comments : {$comments}\n";
        $mailBody .= "Ip : {$ip}\n";
        $mailBody .= "-------------------\n";
        $mailBody .= "You may edit this registration (and others) at:\n";
        $mailBody .= "https://www.worldcubeassociation.org/competitions/{$chosenCompetitionId}/registrations";
        $mailSubject = $competition['cellName'] . " - New registration";
        $mail_config = $config->get('mail');
        // only send mails on the real website
        if (preg_match('/^www.worldcubeassociation.org$/', $_SERVER["SERVER_NAME"])) {
            if ($mail_config['pear']) {
                // send smtp mail
                $headers = array('From' => $mail_config['from'], 'To' => $mailEmail, 'Subject' => $mailSubject);
                $smtp = Mail::factory('smtp', array('host' => $mail_config['host'], 'port' => $mail_config['port'], 'auth' => true, 'username' => $mail_config['user'], 'password' => $mail_config['pass']));
                $mail = $smtp->send($mailEmail, $headers, $mailBody);
            } else {
                // normal php mail
                $mailHeaders = "From: \"WCA\" <" . $mail_config['from'] . ">\r\n";
                $mailHeaders .= "Reply-To: board@worldcubeassociation.org\r\n";
                $mailHeaders .= "MIME-Version: 1.0\r\n";
                $mailHeaders .= "Content-Type: text/plain; charset=UTF-8\r\n";
                mail($mailEmail, $mailSubject, $mailBody, $mailHeaders, "-f" . $mail_config['from']);
            }
        } else {
            // just print out message when testing
            noticeBox3(0, "Mail not sent (test website): " . $mailBody);
        }
    }
    noticeBox(true, "Registration complete.<br />Please note that all registrations must be approved by the organizer.<br/>Your registration will appear here within a few days.");
    return true;
}