function offerChoices()
{
    #----------------------------------------------------------------------
    global $chosenUri;
    global $chosenCompetitionId, $chosenType;
    global $chosenTextHtml, $chosenUriHtml, $chosenSubmitterNameHtml, $chosenSubmitterEmailHtml, $chosenSubmitterCommentHtml;
    if ($chosenUri != '') {
        $success = saveMedium();
        noticeBox2($success, 'Thanks for sending us a link to competition media', 'The reCAPTCHA was not entered correctly. Try it again.');
    }
    echo "<p>All media will be reviewed before listed on the Media page</p>";
    echo "<form method='POST'>\n";
    echo "<table border='0' cellspacing='0' cellpadding='2' width='100%'>\n";
    echo "<tr><td>Competition</td>";
    $optionsComp = "<td><select class='drop' id='competitionId' name='competitionId'>\n";
    foreach (getAllCompetitions() as $competition) {
        $optionId = $competition['id'];
        $optionName = $competition['cellName'];
        if ($optionId == $chosenCompetitionId) {
            $optionsComp .= "<option value='{$optionId}' selected='selected'>{$optionName}</option>\n";
        } else {
            $optionsComp .= "<option value='{$optionId}'>{$optionName}</option>\n";
        }
    }
    $optionsComp .= "</select></td></tr>";
    echo $optionsComp;
    echo "<tr><td>Type</td>";
    echo "<td><select class='drop' id='type' name='type'>\n";
    foreach (array('article', 'report', 'multimedia') as $typeString) {
        if ($typeString == $chosenType) {
            echo "<option value='{$typeString}' selected='selected'>{$typeString}</option>";
        } else {
            echo "<option value='{$typeString}'>{$typeString}</option>";
        }
    }
    $fieldList = array(array('Text', 'text', $chosenTextHtml), array('Link', 'uri', $chosenUriHtml ? "{$chosenUriHtml}" : 'http://'), array('Submitter Name', 'submitterName', $chosenSubmitterNameHtml), array('Submitter Email', 'submitterEmail', $chosenSubmitterEmailHtml), array('Submitter Comment', 'submitterComment', $chosenSubmitterCommentHtml));
    foreach ($fieldList as $field) {
        list($title, $name, $value) = $field;
        echo "<tr><td>{$title}</td><td><input type='text' name='{$name}' value='{$value}' /></td></tr>\n";
    }
    echo "</table>";
    global $config;
    $recaptcha = $config->get('recaptcha');
    echo recaptcha_get_html($recaptcha['publickey'], null, true);
    echo "<input type='submit' class='butt' value='Save' />";
    echo "</form>";
}
function doTheDarnChecking()
{
    #----------------------------------------------------------------------
    global $differencesWereFound;
    #--- Begin form and table.
    echo "<form action='check_regional_record_markers_ACTION.php' method='post'>\n";
    tableBegin('results', 12);
    #--- Do the checking.
    computeRegionalRecordMarkers('best', 'Single');
    computeRegionalRecordMarkers('average', 'Average');
    #--- End table.
    tableEnd();
    #--- Tell the result.
    $date = wcaDate();
    noticeBox2(!$differencesWereFound, "We completely agree.<br />{$date}", "<p>Darn! We disagree!<br />{$date}</p>\n     <p>Choose the changes you agree with above, then click the 'Execute...' button below. It will result in something like the following.\n        If you then go back in your browser and refresh the page, the changes should be visible.</p>\n        \n<pre>\n            Queries similar to the following will be executed:\n              UPDATE Results SET regionalSingleRecord = ? WHERE id = ?\n              UPDATE Results SET regionalAverageRecord = ? WHERE id = ?\n          </pre>");
    #--- If differences were found, offer to fix them.
    if ($differencesWereFound) {
        echo "<center><input type='submit' value='Execute the agreed changes!' /></center>\n";
    }
    #--- Finish the form.
    echo "</form>\n";
}
function checkSimilarResults()
{
    #----------------------------------------------------------------------
    global $competitionCondition, $chosenWhich;
    echo "<hr /><p>Checking <b>" . $chosenWhich . " similar results</b>... (wait for the result message box at the end)</p>\n";
    #--- Get all similar results (except old-new multiblind)
    $rows = pdo_query("\n      SELECT\n          Results.competitionId AS competitionId,\n          Results.personId AS personIdA, Results.personName AS personNameA, Results.eventId AS eventIdA, Results.roundId AS roundIdA,\n          h.personId AS personIdB, h.personName AS personNameB, h.eventId AS eventIdB, h.roundId AS roundIdB,\n          Results.value1 AS value1A, Results.value2 AS value2A, Results.value3 AS value3A, Results.value4 AS value4A, Results.value5 AS value5A,\n          h.value1 AS value1B, h.value2 AS value2B, h.value3 AS value3B, h.value4 AS value4B, h.value5 AS value5B\n      FROM Results\n      JOIN (\n          SELECT competitionId, eventId, roundId, personId, personName, value1, value2, value3, value4, value5\n          FROM Results " . ($competitionCondition ? "JOIN Competitions ON Competitions.id = competitionId " : "") . "WHERE best > 0 " . ($competitionCondition ? $competitionCondition : "") . " AND value3 <> 0\n              AND eventId <> '333mbo'\n      ) h ON Results.competitionId = h.competitionId\n          AND Results.eventId <> '333mbo'\n          AND Results.personId < h.personId\n          AND (\n              (Results.value1 = h.value1 AND h.value1 > 0) +\n              (Results.value2 = h.value2 AND h.value2 > 0) +\n              (Results.value3 = h.value3 AND h.value3 > 0) +\n              (Results.value4 = h.value4 AND h.value4 > 0) +\n              (Results.value5 = h.value5 AND h.value5 > 0) > 2\n              )\n  ");
    tableBegin('results', 4);
    foreach ($rows as $row) {
        $competition = getCompetition($row['competitionId']);
        $competitionName = $competition['cellName'];
        tableCaption(false, competitionLink($row['competitionId'], $competitionName));
        tableHeader(explode('|', "Person|Event|Round|Result Details"), array(3 => 'class="f"'));
        foreach (array('A', 'B') as $letter) {
            $otherLetter = chr(65 + 66 - ord($letter));
            $resultStr = '';
            for ($i = 1; $i <= 5; $i++) {
                $value = $row['value' . $i . $letter];
                if (!$value) {
                    break;
                }
                $resultStr .= "<span class='label label-" . ($value == $row['value' . $i . $otherLetter] ? "danger" : "success") . "'>" . formatValue($value, valueFormat($row['eventId' . $letter])) . "</span> ";
            }
            tableRow(array(personLink($row['personId' . $letter], $row['personName' . $letter]), eventCellName($row['eventId' . $letter]), roundCellName($row['roundId' . $letter]), $resultStr));
        }
    }
    tableEnd();
    #--- Tell the result.
    $date = wcaDate();
    noticeBox2(count($rows) == 0, "No similar results were found.<br />{$date}", "Similar results were found.<br />{$date}");
}
function checkEvents()
{
    #----------------------------------------------------------------------
    global $competitionCondition, $competitionDescription;
    echo "<hr /><p>Checking <b> events for {$competitionDescription}</b>... (wait for the result message box at the end)</p>\n";
    #--- Get events from Results and Competitions
    $eventsResults = dbQuery("SELECT r.competitionId, r.eventId, c.eventSpecs FROM Results r, Competitions c WHERE c.id = r.competitionId AND r.eventId != '333mbo' {$competitionCondition} GROUP BY r.competitionId, r.eventId");
    # Grossness to handle the fact that the competition id in the Competitions table
    # is the "id" column, not the "competitionId" column.
    $competitionConditionForCompetitionsTable = str_replace("competitionId", "id", $competitionCondition);
    $eventsCompetition = dbQuery("SELECT id, eventSpecs FROM Competitions WHERE 1 {$competitionConditionForCompetitionsTable}");
    #--- Group events by competitions.
    foreach ($eventsResults as $eventResults) {
        extract($eventResults);
        $arrayEventsResults[$competitionId][] = $eventId;
    }
    foreach ($eventsCompetition as $eventCompetition) {
        extract($eventCompetition);
        $arrayEventsCompetition[$id] = getEventSpecsEventIds($eventSpecs);
    }
    $ok = true;
    #--- Compare events.
    if ($arrayEventsResults) {
        foreach (array_keys($arrayEventsResults) as $competitionId) {
            # Sort tables to compare them.
            sort($arrayEventsResults[$competitionId], SORT_STRING);
            sort($arrayEventsCompetition[$competitionId], SORT_STRING);
            if ($arrayEventsResults[$competitionId] != $arrayEventsCompetition[$competitionId]) {
                $ok = false;
                echo "<p>Update competition {$competitionId}.<br />\n";
                $intersect = array_intersect($arrayEventsResults[$competitionId], $arrayEventsCompetition[$competitionId]);
                $resultsOnly = array_diff($arrayEventsResults[$competitionId], $arrayEventsCompetition[$competitionId]);
                $competitionOnly = array_diff($arrayEventsCompetition[$competitionId], $arrayEventsResults[$competitionId]);
                echo "  Old events list: " . implode(' ', $intersect) . " <b style='color:#F00'>" . implode(' ', $competitionOnly) . "</b><br />\n";
                echo "  New events list: " . implode(' ', $intersect) . " <b style='color:#3C3'>" . implode(' ', $resultsOnly) . "</b><br />\n";
                dbCommand("UPDATE Competitions SET eventSpecs='" . implode(' ', $arrayEventsResults[$competitionId]) . "' WHERE id='{$competitionId}'");
            }
        }
    }
    noticeBox2($ok, 'No mistakes found in the database', 'Some errors were fixed, you *should* check what has been updated');
}
adminHeadline('Check finished persons');
showDescription();
showChoices();
if ($chosenCheck) {
    echo "<hr /><p>Checking... (wait for the result message box at the end)</p>\n";
    #--- Prepare the data
    getPersonsFromPersons();
    getPersonsFromResults();
    #--- Run the checks
    $success = true;
    checkSpacesInPersons();
    checkSpacesInResults();
    checkTooMuchInResults();
    checkDuplicatesInCompetition();
    #--- Tell the result
    noticeBox2($success, "Finished. All checks successful.<br />" . wcaDate(), "Finished. Some errors found.<br />" . wcaDate());
}
require '../includes/_footer.php';
#----------------------------------------------------------------------
function showDescription()
{
    #----------------------------------------------------------------------
    echo "<p>In this script, a \"person\" always means a triple of id/name/countryId, and \"similar\" always means just name similarity.</p>\n\n";
    echo "<p>I run several phases, listed below. You should always work from top to bottom, i.e. don't work on one phase before all previous phases report \"OK\".</p>\n\n";
    echo "<ul>\n";
    echo "<li><p>Find persons in <strong>Persons</strong> whose name starts or ends with space or has double spaces.</p></li>\n";
    echo "<li><p>Find persons in <strong>Results</strong> whose name starts or ends with space or has double spaces.</p></li>\n";
    echo "<li><p>Find persons in <strong>Results</strong> who have ids but who don't appear in <strong>Persons</strong>. Can be caused by organizers telling you incorrect persons. I show similar persons from <strong>Persons</strong> and offer you to adopt their data. Can also be caused by a person really changing name or countryId, in this case please add this person to the <strong>Persons</strong> table with new subId.</p></li>\n";
    echo "<li><p>Find persons in <strong>Results</strong> that appear more than once in the same round, event and competition. This is the most easily detected case of where an organizer should've added numbers to otherwise equal persons but didn't. Or for example when like in CaltechWinter2007, the roundIds are wrong. <b>Warning:</b> Currently this is only checks the last three months, to prevent a timeout problem.</p></li>\n";
    echo "</ul>";
    echo "<hr />";