function showRegionalRecordsSeparate()
{
    #----------------------------------------------------------------------
    global $chosenRegionId;
    require 'regions_get_current_records.php';
    tableBegin('results', 6);
    tableCaption(false, "Single");
    tableHeader(explode('|', 'Event|Result|Person|Citizen of|Competition|'), array(1 => "class='R2'", 5 => 'class="f"'));
    foreach ($results as $result) {
        extract($result);
        if ($type == 'Single') {
            $isNewEvent = !isset($currentEventId) || $eventId != $currentEventId;
            $currentEventId = $eventId;
            tableRow(array($isNewEvent ? eventLink($eventId, $eventCellName) : '', $isNewEvent ? formatValue($value, $format) : '', personLink($personId, $personName), $countryName, competitionLink($competitionId, $competitionName), ''));
        }
    }
    tableCaption(false, "Average");
    tableHeader(explode('|', 'Event|Result|Person|Citizen of|Competition|Result Details'), array(1 => "class='R2'", 5 => 'class="f"'));
    $currentEventId = '';
    foreach ($results as $result) {
        extract($result);
        if ($type == 'Average') {
            $isNewEvent = $eventId != $currentEventId;
            $currentEventId = $eventId;
            tableRow(array($isNewEvent ? eventLink($eventId, $eventCellName) : '', $isNewEvent ? formatValue($value, $format) : '', personLink($personId, $personName), $countryName, competitionLink($competitionId, $competitionName), formatAverageSources(true, $result, $format)));
        }
    }
    tableEnd();
}
function showCompetitionResultsByPerson($resultsTable = 'Results')
{
    #----------------------------------------------------------------------
    global $chosenByPerson, $chosenAllResults, $chosenTop3, $chosenWinners;
    global $chosenCompetitionId;
    #--- Get the results.
    $competitionResults = getCompetitionResults($resultsTable);
    startTimer();
    tableBegin('results', 8);
    foreach ($competitionResults as $result) {
        extract($result);
        $isNewPerson = !isset($previousPersonId) || $personId != $previousPersonId;
        $isNewEvent = !isset($previousEventId) || $eventId != $previousEventId || $isNewPerson;
        #--- Welcome new persons.
        if ($isNewPerson) {
            if (isset($previousPersonId)) {
                tableRowBlank();
            }
            $bo3_as_mo3 = $formatId == '3' && ($eventId == '333bf' || $eventId == '333fm' || $eventId == '333ft');
            $headerAverage = $formatId == 'a' || $formatId == 'm' || $bo3_as_mo3 ? 'Average' : '';
            $headerAllResults = $formatId != '1' ? 'Result Details' : '';
            tableCaptionNew(false, $personId, spaced(array(personLink($personId, $personName), $countryName)));
            tableHeader(explode('|', "Event|Round|Place|Best||{$headerAverage}||{$headerAllResults}"), array(2 => 'class="r"', 3 => 'class="R"', 5 => 'class="R"', 7 => 'class="f"'));
        }
        #--- One result row.
        tableRowStyled($isNewEvent ? '' : 'color:#AAA', array($isNewEvent ? eventLink($eventId, $eventCellName) : '', $roundCellName, $isNewEvent ? "<b>{$pos}</b>" : $pos, formatValue($best, $valueFormat), $regionalSingleRecord, formatValue($average, $valueFormat), $regionalAverageRecord, formatAverageSources($formatId != '1', $result, $valueFormat)));
        $previousPersonId = $personId;
        $previousEventId = $eventId;
    }
    tableEnd();
    stopTimer("printing the huge table");
}
function showBody($eventId)
{
    #----------------------------------------------------------------------
    #--- Get the data
    $rows = dbQuery("\n    SELECT    personId, personName, min(value1+value2+value3) minSum, count(*) means, 0 minSum2, 0 means2\n    FROM      Results\n    WHERE     eventId = '{$eventId}' and (value1>0)+(value2>0)+(value3>0) = 3\n    GROUP BY  personId\n    ORDER BY  minSum, personName\n  ");
    $also2 = $eventId == '444bf' || $eventId == '555bf';
    if ($also2) {
        $rows = array_merge($rows, dbQuery("\n      SELECT    personId, personName, 0 minSum, 0 means, min(greatest(0,value1)+greatest(0,value2)+greatest(0,value3)) minSum2, count(*) means2\n      FROM      Results\n      WHERE     eventId = '{$eventId}' and (value1>0)+(value2>0)+(value3>0) = 2\n      GROUP BY  personId\n      ORDER BY  minSum2, personName\n    "));
    }
    #--- Output the table header
    TableBegin('results', 7);
    TableHeader(array('Pos', 'Name', 'Best Mean', 'Means', $also2 ? 'Best 2-Mean' : '', $also2 ? '2-Means' : '', ''), array('class="r"', 'class="p"', 'class="r"', 'class="r"', 'class="r"', 'class="r"', 'class="f"'));
    #--- Output the table contents
    $listed = array();
    $pos = 0;
    foreach ($rows as $row) {
        list($personId, $personName, $minSum, $means, $minSum2, $means2) = $row;
        if (!isset($listed[$personId])) {
            $mean = formatValue(round($minSum / 3));
            $mean2 = formatValue(round($minSum2 / 2));
            TableRow(array(++$pos, personLink($personId, $personName), $mean, $means, $mean2, $means2, ''));
        }
        $listed[$personId] = true;
    }
    #--- Output the table end
    TableEnd();
}
function formatSub20Streak($data)
{
    extract($data);
    $best = formatValue($best, 'time');
    $worst = formatValue($worst, 'time');
    $average = formatValue($average, 'time');
    return array($idAndName, $length, "<span style='color:#0E0;font-weight:bold'>{$best}</span>", $average, "<span style='color:#E33;font-weight:bold'>{$worst}</span>");
}
function add_blindfold_333_consecutive_successes()
{
    global $lists, $WHERE;
    #--- Get ...
    $results = dbQuery("\n    SELECT personId, value1, value2, value3, value4, value5, year, month\n    FROM Results result, Competitions competition\n    {$WHERE} 1\n      AND eventId = '333bf'\n      AND competition.id = competitionId\n    ORDER BY personId, year, month, day, roundId\n  ");
    foreach (structureBy($results, 'personId') as $personResults) {
        extract($personResults[0]);
        #--- Collect all values of this person, add a 'current DNF' sentinel at the end.
        unset($datedValues);
        foreach ($personResults as $personResult) {
            foreach (range(1, 5) as $i) {
                $v = $personResult["value{$i}"];
                if ($v > 0 || $v == -1) {
                    $datedValues[] = array(getMonthName($personResult['month']) . " {$personResult['year']}", $v);
                }
            }
        }
        $datedValues[] = array('current', -1);
        #--- Find longest streak.
        $streak = array();
        $bestStreak = array();
        $streakFirstDate = "";
        $streakLastDate = "";
        foreach ($datedValues as $dv) {
            if ($dv[1] > 0) {
                if (!$streak) {
                    $streakFirstDate = $dv[0];
                }
                $streakLastDate = $dv[0];
                $streak[] = $dv[1];
            } else {
                if (count($streak) >= count($bestStreak)) {
                    $bestStreak = $streak;
                    $bestStreakFirstDate = $streakFirstDate;
                    $bestStreakLastDate = $dv[0] == 'current' ? '<b>ongoing...</b>' : $streakLastDate;
                }
                $streak = array();
            }
        }
        #--- This person doesn't have any streak? Next person, please.
        if (!$bestStreak) {
            continue;
        }
        #--- Determine properties of the streak.
        $length = count($bestStreak);
        $best = min($bestStreak);
        $worst = max($bestStreak);
        $average = array_sum($bestStreak) / $length;
        #--- Format and memorize this person with its streak
        $persons[] = array($personId, $length, '', '<span style="color:#0C0">' . formatValue($best) . '</span>', $average, '<span style="color:#E00">' . formatValue($worst) . '</span>', "{$bestStreakFirstDate} - {$bestStreakLastDate}");
    }
    usort($persons, 'compareBlindfoldStreaks');
    $persons = array_slice($persons, 0, 10);
    $lists[] = array("blind_streak_3x3", "Rubik's Cube Blindfolded longest success streak", "", "[P] Person [N] Length [t] &nbsp; [r] Best [r] Avg [r] Worst [t] When?", $persons);
}
function showResults()
{
    #----------------------------------------------------------------------
    global $chosenEventId, $chosenRegionId, $chosenYears, $chosenShow, $chosenSingle, $chosenAverage;
    #--- Try the cache
    tryCache('event', $chosenEventId, preg_replace('/ /', '', $chosenRegionId), $chosenYears, preg_replace('/ /', '', $chosenShow), $chosenSingle, $chosenAverage);
    #------------------------------
    # Prepare stuff for the query.
    #------------------------------
    $eventCondition = eventCondition();
    $yearCondition = yearCondition();
    $regionCondition = regionCondition('result');
    $limitCondition = '';
    if (preg_match('/^10+/', $chosenShow, $matches)) {
        $limitNumber = $matches[0];
        $limitCondition = 'LIMIT ' . 2 * $limitNumber;
    }
    $valueSource = $chosenAverage ? 'average' : 'best';
    $valueName = $chosenAverage ? 'Average' : 'Single';
    #------------------------------
    # Get results from database.
    #------------------------------
    if ($chosenShow == 'By Region') {
        require 'includes/events_regions.php';
        return;
    }
    if ($chosenShow == '100 Results' || $chosenShow == '1000 Results') {
        require 'includes/events_results.php';
    } else {
        require 'includes/events_persons.php';
    }
    #------------------------------
    # Show the table.
    #------------------------------
    startTimer();
    $event = getEvent($chosenEventId);
    tableBegin('results', 6);
    tableCaption(true, spaced(array($event['name'], chosenRegionName(), $chosenYears, $chosenShow)));
    $headerSources = $chosenAverage ? 'Result Details' : '';
    tableHeader(explode('|', "Rank|Person|Result|Citizen of|Competition|{$headerSources}"), array(0 => "class='r'", 2 => "class='R2'", 5 => 'class="f"'));
    $ctr = 0;
    foreach ($results as $result) {
        extract($result);
        $ctr++;
        $no = isset($previousValue) && $value == $previousValue ? '&nbsp;' : $ctr;
        if ($limitCondition && $no > $limitNumber) {
            break;
        }
        tableRow(array($no, personLink($personId, $personName), formatValue($value, $event['format']), htmlEntities($countryName), competitionLink($competitionId, $competitionName), formatAverageSources($chosenAverage, $result, $event['format'])));
        $previousValue = $value;
    }
    tableEnd();
    stopTimer("printing the table");
}
function sdRanking()
{
    global $WHERE;
    #--- Get ...
    $results = dbQuery("\n    SELECT personName, personId, value1, value2, value3, value4, value5,\n      (((value1*value1 + value2*value2 + value3*value3 + value4*value4 + value5*value5) / 5) - (((value1 + value2 + value3 + value4 + value5) / 5)*((value1 + value2 + value3 + value4 + value5) / 5))) sd\n    FROM Results result\n    {$WHERE} 1\n      AND eventId = '333'\n      AND value1 > 0\n      AND value2 > 0\n      AND value3 > 0\n      AND value4 > 0\n      AND value5 > 0\n    ORDER BY sd, personName\n    LIMIT 0, 10\n  ");
    foreach ($results as $result) {
        extract($result);
        $rows[] = array($personId, formatValue(sqrt($sd), 'time'), formatAverageSources(true, $result, 'time'));
    }
    return $rows;
}
function showRegionalRecordsHistory()
{
    #----------------------------------------------------------------------
    global $chosenRegionId, $chosenHistory, $chosenMixHist;
    #--- Compute the region condition and the normal record name.
    if (preg_match('/^(world)?$/i', $chosenRegionId)) {
        $regionCondition = "AND recordName = 'WR'";
        $normalRecordName = '';
    } elseif (preg_match('/^_/', $chosenRegionId)) {
        $tmp = dbQuery("SELECT recordName FROM Continents WHERE id = '{$chosenRegionId}'");
        $normalRecordName = $tmp[0][0];
        $regionCondition = "AND recordName in ('WR', '{$normalRecordName}' ) AND continentId = '{$chosenRegionId}'";
    } else {
        $regionCondition = "AND (recordName <> '') AND (result.countryId = '{$chosenRegionId}')";
        $normalRecordName = 'NR';
    }
    #--- Order: normal history or mixed?
    $order = $chosenHistory ? 'event.rank, type, value, year desc, month desc, day desc, roundId desc' : 'year desc, month desc, day desc, roundId desc, event.rank, type, value';
    #--- Get the results.
    $results = dbQuery("\n    SELECT\n      year, month, day,\n\n      event.id         eventId,\n      event.name       eventName,\n      event.cellName   eventCellName,\n\n      result.type      type,\n      result.value     value,\n      event.format     valueFormat,\n                       recordName,\n\n      result.personId   personId,\n      result.personName personName,\n\n      country.name     countryName,\n\n      competition.id   competitionId,\n      competition.cellName competitionName,\n\n      value1, value2, value3, value4, value5\n    FROM\n      (SELECT Results.*, 1 type, best    value, regionalSingleRecord  recordName FROM Results WHERE regionalSingleRecord<>'' UNION\n       SELECT Results.*, 2 type, average value, regionalAverageRecord recordName FROM Results WHERE regionalAverageRecord<>'') result,\n      Events event,\n      Competitions competition,\n      Countries country\n    WHERE " . randomDebug() . "\n      AND event.id = eventId\n      AND event.rank < 1000\n      AND competition.id = competitionId\n      AND country.id = result.countryId\n      {$regionCondition}\n      " . eventCondition() . yearCondition() . "\n    ORDER BY\n      {$order}\n  ");
    #--- Start the table
    if ($chosenHistory) {
        tableBegin('results', 7);
    } else {
        tableBegin('results', 9);
        tableHeader(explode('|', 'Date circa|Event|What|Single|Average|Person|Citizen of|Competition|Result Details'), array(3 => 'class="R2"', 4 => 'class="R2"', 8 => 'class="f"'));
    }
    #--- Process the results.
    $currentEventId = false;
    foreach ($results as $result) {
        extract($result);
        #--- Announce the event (only for normal history, not mixed)
        if ($chosenHistory && $eventId != $currentEventId) {
            $currentEventId = $eventId;
            tableCaptionNew(false, $eventId, eventLink($eventId, $eventName));
            tableHeader(explode('|', '|Single|Average|Person|Citizen of|Competition|Result Details'), array(1 => 'class="R2"', 2 => 'class="R2"', 6 => 'class="f"'));
        }
        #--- Determine how to display the record name.
        if ($recordName != $normalRecordName) {
            $recordName = "<span style='color:#f93;font-weight:bold'>{$recordName}</span>";
        }
        #--- Prepare the table row.
        $data = array($recordName, $type == 1 ? formatValue($value, $valueFormat) : '', $type == 2 ? formatValue($value, $valueFormat) : '', personLink($personId, $personName), $countryName, competitionLink($competitionId, $competitionName), formatAverageSources($type == 2, $result, $valueFormat));
        if ($chosenMixHist) {
            array_unshift($data, sprintf('%4d-%02d-%02d', $year, $month, $day), eventLink($eventId, $eventCellName));
        }
        #--- Show the table row.
        tableRow($data);
    }
    tableEnd();
}
function showResultsByEvents()
{
    #----------------------------------------------------------------------
    global $chosenPersonId;
    $results = dbQuery("\n    SELECT\n                           result.*,\n      event.name           eventName,\n      competition.cellName competitionCellName,\n      event.format         valueFormat,\n      round.cellName       roundCellName\n    FROM\n      Results result,\n      Events  event,\n      Competitions competition,\n      Rounds round\n    WHERE " . randomDebug() . "\n      AND personId = '{$chosenPersonId}'\n      AND event.id = eventId\n      AND event.rank < 1000\n      AND competition.id = competitionId\n      AND round.id = roundId\n    ORDER BY\n      event.rank, year DESC, month DESC, day DESC, competitionCellName, round.rank DESC\n  ");
    tableBegin('results', 8);
    tableCaption(false, "History (<a href='person_map.php?i={$chosenPersonId}'>Map</a>)");
    #--- Process results by event.
    foreach (structureBy($results, 'eventId') as $eventResults) {
        extract($eventResults[0]);
        #--- Announce the event.
        tableCaptionNew(false, $eventId, eventLink($eventId, $eventName));
        tableHeader(explode('|', 'Competition|Round|Place|Best||Average||Result Details'), array(2 => 'class="r"', 3 => 'class="R"', 5 => 'class="R"', 7 => 'class="f"'));
        #--- Initialize.
        $currentCompetitionId = '';
        #--- Compute PB Markers
        //$pbMarkers = [];
        $bestBest = 9999999999;
        $bestAverage = 9999999999;
        foreach (array_reverse($eventResults) as $result) {
            extract($result);
            $pbMarkers[$competitionId][$roundCellName] = 0;
            if ($best > 0 && $best <= $bestBest) {
                $bestBest = $best;
                $pbMarkers[$competitionId][$roundCellName] += 1;
            }
            if ($average > 0 && $average <= $bestAverage) {
                $bestAverage = $average;
                $pbMarkers[$competitionId][$roundCellName] += 2;
            }
        }
        #--- Show the results.
        foreach ($eventResults as $result) {
            extract($result);
            $isNewCompetition = $competitionId != $currentCompetitionId;
            $currentCompetitionId = $competitionId;
            $formatBest = formatValue($best, $valueFormat);
            if ($pbMarkers[$competitionId][$roundCellName] % 2) {
                $formatBest = "<span style='color:#F60;font-weight:bold'>{$formatBest}</span>";
            }
            $formatAverage = formatValue($average, $valueFormat);
            if ($pbMarkers[$competitionId][$roundCellName] > 1) {
                $formatAverage = "<span style='color:#F60;font-weight:bold'>{$formatAverage}</span>";
            }
            tableRowStyled($isNewCompetition ? '' : 'color:#AAA', array($isNewCompetition ? competitionLink($competitionId, $competitionCellName) : '', $roundCellName, $isNewCompetition ? "<b>{$pos}</b>" : $pos, $formatBest, $regionalSingleRecord, $formatAverage, $regionalAverageRecord, formatAverageSources(true, $result, $valueFormat)));
        }
    }
    tableEnd();
}
function showCurrentPersonalRecords()
{
    #----------------------------------------------------------------------
    global $chosenPersonId;
    $bests = dbQuery("\n\n  SELECT * FROM\n\n   (SELECT \n      eventId,\n      best single,\n      worldRank singleRank,\n      continentRank singleRankContinent,\n      countryRank singleRankCountry\n    FROM RanksSingle\n    WHERE personId='{$chosenPersonId}') singles\n    \n    LEFT JOIN\n   \n   (SELECT \n      eventId eC,\n      best average,\n      worldRank averageRank,\n      continentRank averageRankContinent,\n      countryRank averageRankCountry\n    FROM RanksAverage\n    WHERE personId='{$chosenPersonId}') average\n    \n    ON eventId = eC,\n    Events event\n    WHERE\n      eventId = event.id\n    ORDER BY\n      event.rank\n\n\n  ");
    tableBegin('results', 10);
    tableCaption(false, "Current Personal Records");
    tableHeader(explode(" ", "Event NR CR WR Single Average WR CR NR "), array("", "class='r'", "class='r'", "class='R'", "class='R2'", "class='R2'", "class='R'", "class='r'", "class='r'", "class='f'"));
    $oddMessage = "A missing or worse country/continent rank compared to a larger region rank is due to the change of country because results from previous regions don&#39;t count for differing current regions.";
    foreach ($bests as $best) {
        extract($best);
        $odd = $singleRankCountry > $singleRankContinent || $singleRankContinent > $singleRank || $averageRankCountry > $averageRankContinent || $averageRankContinent > $averageRank || !$singleRankCountry && $singleRankContinent || !$singleRankContinent && $singleRank || !$averageRankCountry && $averageRankContinent || !$averageRankContinent && $averageRank;
        tableRow(array(internalEventLink("#{$eventId}", eventCellName($eventId)), "<span style='color:#999'>" . colorMe($singleRankCountry) . "</span>", colorMe($singleRankContinent), colorMe($singleRank), eventLink($eventId, formatValue($single, valueFormat($eventId))), eventAverageLink($eventId, formatValue($average, valueFormat($eventId))), colorMe($averageRank), colorMe($averageRankContinent), "<span style='color:#999'>" . colorMe($averageRankCountry) . "</span>", $odd ? "<a title='{$oddMessage}' style='color:#66F' onclick='alert(\"{$oddMessage}\")'>(*)</a>" : ''));
    }
    tableEnd();
}
function showRegionalRecordsSlim()
{
    #----------------------------------------------------------------------
    global $chosenYears;
    require 'regions_get_current_records.php';
    tableBegin('results', 6);
    $caption = spaced(array(chosenRegionName(), $chosenYears));
    if ($caption) {
        tableCaption(true, $caption);
    } else {
        tableRowBlank();
    }
    tableHeader(explode('|', 'Person|Single|Event|Average|Person|Result Details'), array(1 => "class='R2'", 2 => "class='c'", 3 => "class='R2'", 5 => 'class="f"'));
    #--- Process events.
    foreach (structureBy($results, 'eventId') as $eventResults) {
        $structure = structureBy($eventResults, 'type');
        $singles = $structure[0];
        $averages = isset($structure[1]) ? $structure[1] : array();
        $wasShownSinglePerson = $wasShownAveragePerson = array();
        #--- Process records for this event.
        $first = true;
        while ($singles || $averages) {
            #--- Get next single.
            $s = array_shift($singles);
            if (isset($wasShownSinglePerson[$s['personId']])) {
                $s = false;
            }
            $wasShownSinglePerson[$s['personId']] = true;
            #--- Get next average.
            $a = array_shift($averages);
            if (isset($wasShownAveragePerson[$a['personId']])) {
                $a = false;
            }
            $wasShownAveragePerson[$a['personId']] = true;
            if ($s || $a) {
                tableRow(array($s ? personLink($s['personId'], $s['personName']) : '', $first ? formatValue($s['value'], $s['format']) : '', $first ? eventLink($s['eventId'], $s['eventCellName']) : '', $first ? formatValue($a['value'], $a['format']) : '', $a ? personLink($a['personId'], $a['personName']) : '', $a ? formatAverageSources(true, $a, $a['format']) : ''));
            }
            $first = false;
        }
    }
    tableEnd();
}
function showHistoryOfContinentalRecords()
{
    #----------------------------------------------------------------------
    global $chosenPersonId;
    $results = dbQuery("\n    SELECT\n      result.*,\n      event.format         valueFormat,\n      event.cellName       eventCellName,\n      competition.cellName competitionCellName,\n      round.cellName       roundCellName\n    FROM\n      Results      result,\n      Competitions competition,\n      Events       event,\n      Rounds       round\n    WHERE " . randomDebug() . "\n      AND result.personId = '{$chosenPersonId}'\n      AND ((result.regionalSingleRecord != '' AND result.regionalSingleRecord != 'NR' AND result.regionalSingleRecord != 'WR') OR (result.regionalAverageRecord != '' AND result.regionalAverageRecord != 'NR' AND result.regionalAverageRecord != 'WR'))\n      AND event.id = result.eventId\n      AND event.rank < 1000\n      AND competition.id = result.competitionId\n      AND round.id = result.roundId\n    ORDER BY\n      event.rank, year DESC, month DESC, day DESC, roundId DESC\n  ");
    if (!count($results)) {
        return;
    }
    tableBegin('results', 6);
    tableCaption(false, 'History of Continental Records');
    tableHeader(explode('|', 'Event|Single|Average|Competition|Round|Result Details'), array(1 => "class='R2'", 2 => "class='R2'", 5 => "class='f'"));
    foreach ($results as $result) {
        extract($result);
        if (isset($currentEventId) && $eventId != $currentEventId) {
            tableRowEmpty();
        }
        tableRow(array(isset($currentEventId) && $eventId == $currentEventId ? '' : eventLink($eventId, $eventCellName), ($regionalSingleRecord == '' or $regionalSingleRecord == 'NR' or $regionalSingleRecord == 'WR') ? '' : formatValue($best, $valueFormat), ($regionalAverageRecord == '' or $regionalAverageRecord == 'NR' or $regionalAverageRecord == 'WR') ? '' : formatValue($average, $valueFormat), competitionLink($competitionId, $competitionCellName), $roundCellName, formatAverageSources($regionalAverageRecord != '' and $regionalAverageRecord != 'NR' and $regionalAverageRecord != 'WR', $result, $valueFormat)));
        $currentEventId = $eventId;
    }
    tableEnd();
}
function showRegionalRecordsMixed()
{
    #----------------------------------------------------------------------
    global $chosenRegionId, $chosenYears;
    require 'regions_get_current_records.php';
    tableBegin('results', 6);
    tableCaption(false, spaced(array(chosenRegionName(), $chosenYears)));
    tableHeader(explode('|', 'Type|Result|Person|Citizen of|Competition|Result Details'), array(1 => "class='R2'", 5 => 'class="f"'));
    foreach ($results as $result) {
        extract($result);
        $isNewEvent = !isset($currentEventId) || $eventId != $currentEventId;
        $currentEventId = $eventId;
        $isNewType = $isNewEvent || !isset($currentType) || $type != $currentType;
        $currentType = $type;
        if ($isNewEvent) {
            tableCaption(false, eventLink($eventId, $eventName));
        }
        tableRow(array($isNewType ? $type : '', $isNewType ? formatValue($value, $format) : '', personLink($personId, $personName), $countryName, competitionLink($competitionId, $competitionName), formatAverageSources($type == 'Average', $result, $format)));
    }
    tableEnd();
}
function showWorldChampionshipPodiums()
{
    #----------------------------------------------------------------------
    global $chosenPersonId;
    $results = dbQuery("\n    SELECT\n      result.*,\n      event.format         valueFormat,\n      event.cellName       eventCellName,\n      competition.cellName competitionCellName,\n      year\n    FROM\n      Results      result,\n      Competitions competition,\n      Events       event\n    WHERE " . randomDebug() . "\n      AND best > 0\n      AND pos <= 3\n      AND roundId in ('f', 'c')\n      AND competition.cellName like 'World Championship %'\n      AND result.personId = '{$chosenPersonId}'\n      AND event.id = result.eventId\n      AND competition.id = result.competitionId\n      AND event.rank < 1000\n    ORDER BY\n      year DESC, event.rank\n  ");
    if (!count($results)) {
        return;
    }
    tableBegin('results', 6);
    tableCaption(false, 'World Championship Podiums');
    tableHeader(explode('|', 'Year|Event|Place|Single|Average|Result Details'), array(0 => "class='R2'", 2 => "class='R2'", 3 => "class='r'", 4 => "class='r'", 5 => "class='f'"));
    $lastYear = 0;
    foreach ($results as $result) {
        extract($result);
        if ($year < $lastYear) {
            tableRowEmpty();
        }
        tableRow(array($year != $lastYear ? $year : '', eventLink($eventId, $eventCellName), competitionLink($competitionId, $pos, $eventId, $roundId), formatValue($best, $valueFormat), formatValue($average, $valueFormat), formatAverageSources(true, $result, $valueFormat)));
        $lastYear = $year;
    }
    tableEnd();
}
Esempio n. 15
0
 public static function createStaticAsset($name, $asset, $ext)
 {
     StaticAsset::releaseCurrentField($name);
     $query = "INSERT INTO static_asset (name, asset, current, extension) VALUES ('{$name}', '" . formatValue($asset) . "', 1, '{$ext}')";
     $result = mysql_query($query) or die(sqlError(__FILE__, __LINE__, $query));
 }
Esempio n. 16
0
 public static function createStaticField($name, $value)
 {
     StaticField::releaseCurrentField($name);
     $query = "INSERT INTO static_field (name, value, current) VALUES ('{$name}', '" . formatValue($value) . "', 1)";
     $result = mysql_query($query) or die(sqlError(__FILE__, __LINE__, $query));
 }
 public function rows_as_table($dbrows, $formats = array())
 {
     $ret = "";
     if (!empty($dbrows)) {
         $ret .= "<table class='table table-bordered' border=1>";
         // Print the header
         $ret .= "<thead>";
         if (!empty($dbrows[0])) {
             foreach ($dbrows[0] as $key => $val) {
                 $ret .= "<th>";
                 $ret .= ucwords(str_replace("_", " ", strtolower($key)));
                 $ret .= "</th>";
             }
         }
         $ret .= "</thead>";
         // Print the body of the table
         $ret .= "<tbody>";
         if (!empty($dbrows) && is_array($dbrows)) {
             foreach ($dbrows as $dbrow) {
                 $ret .= "<tr>";
                 if (!empty($dbrow) && is_array($dbrow)) {
                     foreach ($dbrow as $id => $val) {
                         if (is_array($formats) && isset($formats[$id])) {
                             $format = $formats[$id];
                         } else {
                             if (!is_array($formats)) {
                                 $format = $formats;
                             }
                         }
                         $ret .= "<td>";
                         $val = $this->undbize($val);
                         if (isset($format)) {
                             $val = formatValue($val, $format);
                         }
                         $ret .= $val;
                         $ret .= "</td>";
                     }
                 }
                 $ret .= "</tr>";
             }
             $ret .= "</tbody>";
             $ret .= "</table>";
         }
     }
     return $ret;
 }
Esempio n. 18
0
            } else {
                for ($j = 0; $j < count($cell[$i]); $j++) {
                    $key = $property[$j]['id'];
                    $value = $cell[$i][$j];
                    $pair[$n][$key] = $value;
                }
            }
            $n++;
            //$n should only be raised when $pair[$n] has been filled
        }
    }
    echo '<table>';
    for ($i = 1; $i <= count($pair); $i++) {
        if ($_POST['cu'] == 'create') {
            echo "<tr><td>CREATE</td>\r\n";
            foreach ($pair[$i] as $key => $value) {
                if ($value != "") {
                    echo "<tr><td>LAST</td><td>{$key}</td><td>" . formatValue($value, getDataType($key)) . "</td></tr>\r\n";
                }
            }
        } else {
            $item = getPropertyId($pair[$i]['item'], "item");
            foreach ($pair[$i] as $key => $value) {
                if ($key != "item" && $value != "") {
                    echo "<tr><td>{$item}</td><td>{$key}</td><td>" . formatValue($value, getDataType($key)) . "</td></tr>\r\n";
                }
            }
        }
    }
    echo '</table>';
}
Esempio n. 19
0
echo "</tr>\n";
foreach ($statList as $key => $values) {
    if (!isset($dates) && $key == "average") {
        continue;
    }
    if (!$config["UNUSED_STATS"] && !in_array($key, array("total", "average", "everyHour")) && array_sum(array_column($players, $key)) <= 0) {
        if (!isset($unlisted)) {
            $unlisted = "<b>Non-listés :</b> ";
        }
        $unlisted .= $values[0] . " | ";
        continue;
    }
    echo "<tr>";
    $sorted = $key == $sortStat;
    echo "<th " . (in_array($key, array("total", "average", "everyHour")) ? "" : "title='{$key}'") . "onclick='printStats(" . makeUrl($statCat, $key, $sortPlayer) . ");' " . ($sorted ? " class='sorted'>" : "class='unsorted'>") . "{$values['0']}</td>";
    foreach ($players as $name => $player) {
        $sorted = $name == $sortPlayer || $key == $sortStat;
        echo "<td" . ($sorted ? " class='sorted'>" : ">") . formatValue($player[$key], $statList[$key][1]) . "</td>";
        if ($name == "Total") {
            echo "<td class='blank'></td>";
        }
    }
    echo "</tr>\n";
    if ($key == "everyHour" || $statCat == "biomes" && $key == "total") {
        echo "<tr><td class='blank'></td></tr>\n";
    }
}
echo "</table>";
if ($showUnlisted) {
    echo isset($unlisted) ? "<br>" . substr($unlisted, 0, -3) : "";
}
function computeRegionalRecordMarkers($valueId, $valueName)
{
    #----------------------------------------------------------------------
    global $chosenAnything, $chosenCompetitionId, $differencesWereFound, $previousRecord, $pendingCompetitions, $startDate;
    # -----------------------------
    # Description of the main idea:
    # -----------------------------
    # Get all results that are potential regional records. Process them one
    # event at a time. Inside, process them one competition at a time, in
    # chronological order of start date. Each competition's results are only
    # compared against records of strictly previous competitions, not against
    # parallel competitions. For this, there are these main arrays:
    #
    # - $previousRecord[regionId] is a running collection of each region's record,
    #   covering all competitions *before* the current one.
    #
    # - $record[regionId] is based on $previousRecord and is used and updated
    #   inside the current competition.
    #
    # - $pendingCompetitions[regionId] holds $record of competitions already
    #   processed but not merged into $previousRecord. When a new competition is
    #   encountered, we merge those that ended before the new one into $previousRecord.
    #
    # - $baseRecord[eventId][regionId] is for when a user chose a specific
    #   competition to check. Then we quickly ask the database for the current
    #   region records from before that competition. This could be used for
    #   giving the user a year-option as well, but we don't have that (yet?).
    # -----------------------------
    #--- If a competition was chosen, we need all records from before it
    if ($chosenCompetitionId) {
        $startDate = getCompetitionValue($chosenCompetitionId, "year*10000 + month*100 + day");
        $results = dbQueryHandle("\n      SELECT eventId, result.countryId, continentId, min({$valueId}) value, event.format valueFormat\n      FROM Results result, Competitions competition, Countries country, Events event\n      WHERE {$valueId} > 0\n        AND competition.id = result.competitionId\n        AND country.id     = result.countryId\n        AND event.id       = result.eventId\n        AND year*10000 + if(endMonth,endMonth,month)*100 + if(endDay,endDay,day) < {$startDate}\n      GROUP BY eventId, countryId");
        while ($row = mysql_fetch_row($results)) {
            list($eventId, $countryId, $continentId, $value, $valueFormat) = $row;
            if (isSuccessValue($value, $valueFormat)) {
                foreach (array($countryId, $continentId, 'World') as $regionId) {
                    if (!isset($baseRecord[$eventId][$regionId]) || $value < $baseRecord[$eventId][$regionId]) {
                        $baseRecord[$eventId][$regionId] = $value;
                    }
                }
            }
        }
        mysql_free_result($results);
    } else {
        $competitions = dbQuery("\n      SELECT id, year*10000 + if(endMonth,endMonth,month)*100 + if(endDay,endDay,day) endDate\n      FROM   Competitions competition");
        foreach ($competitions as $competition) {
            $endDate[$competition['id']] = $competition['endDate'];
        }
    }
    #--- The IDs of relevant results (those already marked as region record and those that could be)
    $queryRelevantIds = "\n   (SELECT id FROM Results WHERE regional{$valueName}Record<>'' " . eventCondition() . competitionCondition() . ")\n   UNION\n   (SELECT id\n    FROM\n      Results result,\n      (SELECT eventId, competitionId, roundId, countryId, min({$valueId}) value\n       FROM Results\n       WHERE {$valueId} > 0\n       " . eventCondition() . competitionCondition() . "\n       GROUP BY eventId, competitionId, roundId, countryId) helper\n    WHERE result.eventId       = helper.eventId\n      AND result.competitionId = helper.competitionId\n      AND result.roundId       = helper.roundId\n      AND result.countryId     = helper.countryId\n      AND result.{$valueId}      = helper.value)";
    #--- Get the results, ordered appropriately
    $results = dbQueryHandle("\n    SELECT\n      year*10000 + month*100 + day startDate,\n      result.id resultId,\n      result.eventId,\n      result.competitionId,\n      result.roundId,\n      result.personId,\n      result.personName,\n      result.countryId,\n      result.regional{$valueName}Record storedMarker,\n      {$valueId} value,\n      continentId,\n      continent.recordName continentalRecordName,\n      event.format valueFormat\n    FROM\n      ({$queryRelevantIds}) relevantIds,\n      Results      result,\n      Competitions competition,\n      Countries    country,\n      Continents   continent,\n      Events       event,\n      Rounds       round\n    WHERE 1\n      AND result.id      = relevantIds.id\n      AND competition.id = result.competitionId\n      AND round.id       = result.roundId\n      AND country.id     = result.countryId\n      AND continent.id   = country.continentId\n      AND event.id       = result.eventId\n    ORDER BY event.rank, startDate, competitionId, round.rank, {$valueId}\n  ");
    #--- For displaying the dates, fetch all competitions
    $allCompetitions = array();
    foreach (dbQuery("SELECT * FROM Competitions") as $row) {
        $allCompetitions[$row['id']] = $row;
    }
    #--- Process each result.
    $currentEventId = $announcedEventId = $announcedRoundId = $announcedCompoId = NULL;
    while ($row = mysql_fetch_row($results)) {
        list($startDate, $resultId, $eventId, $competitionId, $roundId, $personId, $personName, $countryId, $storedMarker, $value, $continentId, $continentalRecordName, $valueFormat) = $row;
        #--- Handle failures of multi-attempts.
        if (!isSuccessValue($value, $valueFormat)) {
            continue;
        }
        #--- At new events, reset everything
        if ($eventId != $currentEventId) {
            $currentEventId = $eventId;
            $currentCompetitionId = false;
            $record = $previousRecord = isset($baseRecord[$eventId]) ? $baseRecord[$eventId] : array();
            $pendingCompetitions = array();
        }
        #--- Handle new competitions.
        if ($competitionId != $currentCompetitionId) {
            #--- Add the records of the previously current competition to the set of pending competition records
            if ($currentCompetitionId) {
                $pendingCompetitions[] = array($endDate[$currentCompetitionId], $record);
            }
            #--- Note the current competition
            $currentCompetitionId = $competitionId;
            #--- Prepare the records this competition will be based on
            $pendingCompetitions = array_filter($pendingCompetitions, "handlePendingCompetition");
            $record = $previousRecord;
        }
        #--- Calculate whether it's a new region record and update the records.
        $calcedMarker = '';
        if (!isset($record[$countryId]) || $value <= $record[$countryId]) {
            $calcedMarker = 'NR';
            $record[$countryId] = $value;
            if (!isset($record[$continentId]) || $value <= $record[$continentId]) {
                $calcedMarker = $continentalRecordName;
                $record[$continentId] = $value;
                if (!isset($record['World']) || $value <= $record['World']) {
                    $calcedMarker = 'WR';
                    $record['World'] = $value;
                }
            }
        }
        #--- If stored or calculated marker say it's some regional record at all...
        if ($storedMarker || $calcedMarker) {
            #--- Do stored and calculated agree? Choose colors and update list of differences.
            $same = $storedMarker == $calcedMarker;
            $storedColor = $same ? '999' : 'F00';
            $calcedColor = $same ? '999' : '0E0';
            if (!$same) {
                $selectedIds[] = $resultId;
                $differencesWereFound = true;
            }
            #--- If no filter was chosen, only show differences.
            if (!$chosenAnything && $same) {
                continue;
            }
            #--- Highlight regions if the calculated marker thinks it's a record for them.
            $countryName = $countryId;
            $continentName = substr($continentId, 1);
            $worldName = 'World';
            if ($calcedMarker) {
                $countryName = "<b>{$countryName}</b>";
            }
            if ($calcedMarker && $calcedMarker != 'NR') {
                $continentName = "<b>{$continentName}</b>";
            }
            if ($calcedMarker == 'WR') {
                $worldName = "<b>{$worldName}</b>";
            }
            #--- Recognize new events/rounds/competitions.
            $announceEvent = $eventId != $announcedEventId;
            $announcedEventId = $eventId;
            $announceRound = $roundId != $announcedRoundId;
            $announcedRoundId = $roundId;
            $announceCompo = $competitionId != $announcedCompoId;
            $announcedCompoId = $competitionId;
            #--- If new event, announce it.
            if ($announceEvent) {
                tableCaption(false, "{$eventId} {$valueName}");
                tableHeader(explode('|', 'Date|Competition|Round|Person|Event|Country|Continent|World|Value|Stored|Computed|Agree'), array(7 => "class='R2'"));
            }
            #--- If new round/competition inside an event, add a separator row.
            if (($announceRound || $announceCompo) && !$announceEvent) {
                tableRowEmpty();
            }
            #--- Prepare the checkbox.
            $checkbox = "<input type='checkbox' name='update{$valueName}{$resultId}' value='{$calcedMarker}' />";
            #--- Show the result.
            tableRow(array(competitionDate($allCompetitions[$competitionId]), competitionLink($competitionId, $competitionId), $roundId, personLink($personId, $personName), $eventId, $countryName, $continentName, $worldName, formatValue($value, $valueFormat), "<span style='font-weight:bold;color:#{$storedColor}'>{$storedMarker}</span>", "<span style='font-weight:bold;color:#{$calcedColor}'>{$calcedMarker}</span>", $same ? '' : $checkbox));
        }
    }
    mysql_free_result($results);
}
                    if (isset($this->_foreach['time_tracking'])) {
                        unset($this->_foreach['time_tracking']);
                    }
                    $this->_foreach['time_tracking']['name'] = 'time_tracking';
                    $this->_foreach['time_tracking']['total'] = count($_from = (array) $this->_tpl_vars['time_tracking_categories']);
                    $this->_foreach['time_tracking']['show'] = $this->_foreach['time_tracking']['total'] > 0;
                    if ($this->_foreach['time_tracking']['show']) {
                        $this->_foreach['time_tracking']['iteration'] = 0;
                        foreach ($_from as $this->_tpl_vars['ttc_id'] => $this->_tpl_vars['ttc_title']) {
                            $this->_foreach['time_tracking']['iteration']++;
                            $this->_foreach['time_tracking']['first'] = $this->_foreach['time_tracking']['iteration'] == 1;
                            $this->_foreach['time_tracking']['last'] = $this->_foreach['time_tracking']['iteration'] == $this->_foreach['time_tracking']['total'];
                            ?>
                <td class="default" align="center">
                <?php 
                            echo is_array($_tmp = $this->_tpl_vars['data'][$this->_sections['stats']['index']]['time_tracking'][$this->_tpl_vars['ttc_id']]['median_formatted']) ? $this->_run_mod_handler('formatValue', true, $_tmp, $this->_tpl_vars['data']['0']['time_tracking'][$this->_tpl_vars['ttc_id']]['median'], "", $this->_tpl_vars['data'][$this->_sections['stats']['index']]['time_tracking'][$this->_tpl_vars['ttc_id']]['median']) : formatValue($_tmp, $this->_tpl_vars['data']['0']['time_tracking'][$this->_tpl_vars['ttc_id']]['median'], "", $this->_tpl_vars['data'][$this->_sections['stats']['index']]['time_tracking'][$this->_tpl_vars['ttc_id']]['median']);
                            ?>

                </td>
                <?php 
                        }
                        unset($_from);
                    }
                    ?>
            </tr>
            <?php 
                }
            }
            ?>
        </table>
    </td>
    }
    $result['regionName'] = 'World';
    if ($value == $bestValueOfWorld) {
        $bestOfWorld[] = $result;
    }
}
#----------------------------------------------------------------------
#   Print the table.
#----------------------------------------------------------------------
startTimer();
$regionName = preg_replace('/^_/', '', $chosenRegionId);
$eventName = eventName($chosenEventId);
$headerSources = $chosenAverage ? 'Result Details' : '';
tableBegin('results', 5);
tableCaption(true, spaced(array($eventName, $chosenShow, $regionName, $chosenYears)));
tableHeader(explode('|', "Region|Result|Person|Competition|{$headerSources}"), array(0 => 'class="L"', 1 => "class='R2'", 4 => 'class="f"'));
if (isset($bestOfCountry)) {
    $all = array_merge($bestOfWorld, array(0), $bestOfContinent, array(0), $bestOfCountry);
    foreach ($all as $row) {
        if (!$row) {
            tableRowEmpty();
            continue;
        }
        extract($row);
        $isNewRegion = !isset($previousRegionName) || $regionName != $previousRegionName;
        $previousRegionName = $regionName;
        tableRow(array($isNewRegion ? $regionName : '', $isNewRegion ? formatValue($value, $valueFormat) : '', personLink($personId, $personName), competitionLink($competitionId, $competitionName), formatAverageSources($chosenAverage, $row, $valueFormat)));
    }
}
tableEnd();
stopTimer("printing the table");
 public function testPrint()
 {
     global $db;
     $this->fetch();
     if (!empty($this->rawResults)) {
         echo $db->rows_as_table($this->rawResults);
     } else {
         $cols = $db->column_datatypes($this->table);
         echo "<table class='table table-bordered'><thead>";
         foreach ($cols as $name => $datatype) {
             echo "<th>" . formatValue($name) . "</th>";
         }
         echo "</thead></table>";
     }
 }
function showQualifications($competitionId, $eventId, $roundId1, $roundId2)
{
    #----------------------------------------------------------------------
    global $competitionResults1, $competitionResults2, $personsBothRounds;
    getQualifications($competitionId, $eventId, $roundId1, $roundId2);
    tableBegin('results', 8);
    #--- Display competitors only in round 2
    foreach ($competitionResults2 as $key => $result) {
        if (in_array($result['personId'], $personsBothRounds)) {
            continue;
        }
        extract($result);
        #--- Header
        if (!$captionShowed) {
            $anchors = "{$eventId} " . "{$eventId}_{$roundId}";
            $eventHtml = eventLink($eventId, $eventName);
            $caption = spaced(array($eventHtml, $roundName, $formatName));
            tableCaptionNew(false, $anchors, $caption);
            $headerAverage = $formatId == 'a' || $formatId == 'm' ? 'Average' : '';
            $headerAllResults = $formatId != '1' ? 'Result Details' : '';
            tableHeader(explode('|', "Person|Place|Best|{$headerAverage}|Place|Best|{$headerAverage}|"), array(1 => 'class="r"', 2 => 'class="R"', 3 => 'class="R"', 4 => 'class="r"', 5 => 'class="R"', 6 => 'class="R"', 7 => 'class="f"'));
            $captionShowed = true;
        }
        #--- One result row.
        tableRow(array(personLink($personId, $personName), '', '', '', $pos, formatValue($best, $valueFormat), formatValue($average, $valueFormat), ''));
        unset($competitionResults2[$key]);
        // Little speed-up for the second part
    }
    #--- Display the rest
    foreach ($competitionResults1 as $result) {
        extract($result);
        $inRound2 = false;
        foreach ($competitionResults2 as $key => $result2) {
            if ($result2['personId'] == $personId) {
                extract($result2, EXTR_PREFIX_ALL, 'r2');
                unset($competitionResults2[$key]);
                $inRound2 = true;
                $nbQuals += 1;
                break;
            }
        }
        #--- Header
        if (!$captionShowed) {
            $anchors = "{$eventId} " . "{$eventId}_{$roundId}";
            $eventHtml = eventLink($eventId, $eventName);
            $caption = spaced(array($eventHtml, $roundName, $formatName));
            tableCaptionNew(false, $anchors, $caption);
            $headerAverage = $formatId == 'a' || $formatId == 'm' ? 'Average' : '';
            $headerAllResults = $formatId != '1' ? 'Result Details' : '';
            tableHeader(explode('|', "Person|Place|Best|{$headerAverage}|Place|Best|{$headerAverage}|"), array(1 => 'class="r"', 2 => 'class="R"', 3 => 'class="R"', 4 => 'class="r"', 5 => 'class="R"', 6 => 'class="R"', 7 => 'class="f"'));
            $captionShowed = true;
        }
        $offerToDelete = $inRound2 && 4 * $nbQuals > 3 * count($competitionResults1);
        #--- One result row.
        tableRow(array(personLink($personId, $personName), $pos, formatValue($best, $valueFormat), formatValue($average, $valueFormat), $inRound2 ? $r2_pos : "", $inRound2 ? formatValue($r2_best, $r2_valueFormat) : "", $inRound2 ? formatValue($r2_average, $r2_valueFormat) : "", $offerToDelete ? "<input type='checkbox' name='deleteres{$r2_id}' value='1' /> Delete" : ""));
    }
    tableEnd();
}
function showPsychSheet($eventId)
{
    #----------------------------------------------------------------------
    global $chosenCompetitionId;
    echo "<h1>Psych Sheet</h1><br />";
    #--- What's first, single or average?
    $order = count(dbQuery("SELECT * FROM Results WHERE eventId='{$eventId}' AND formatId in ('a','m') LIMIT 1")) ? array('Average', 'Single') : array('Single', 'Average');
    #--- Get singles, averages and preregs.
    $score1 = array();
    foreach (dbQuery("SELECT personId, best, worldRank FROM Ranks{$order[0]} WHERE eventId='{$eventId}'") as $row) {
        $score1[$row['personId']] = array($row['best'], $row['worldRank']);
    }
    $score2 = array();
    foreach (dbQuery("SELECT personId, best, worldRank FROM Ranks{$order[1]} WHERE eventId='{$eventId}'") as $row) {
        $score2[$row['personId']] = array($row['best'], $row['worldRank']);
    }
    $preregs = dbQuery("\n    SELECT personId, name, countryId\n    FROM   Preregs\n    WHERE  competitionId = '{$chosenCompetitionId}'\n      AND  status = 'a'\n      AND  eventIds rlike '[[:<:]]{$eventId}[[:>:]]'\n  ");
    #--- Add singles, averages and a comparison key to the preregs.
    foreach ($preregs as &$prereg) {
        extract($prereg);
        $prereg['score1'] = isset($score1[$personId]) ? $score1[$personId] : array(0, 0);
        # PHP suuuucks
        $prereg['score2'] = isset($score2[$personId]) ? $score2[$personId] : array(0, 0);
        $s1 = isset($score1[$personId]) ? $score1[$personId][1] : 999999999;
        $s2 = isset($score2[$personId]) ? $score2[$personId][1] : 999999999;
        $prereg['cmpKey'] = sprintf('%09d%09d', $s1, $s2);
    }
    unset($prereg);
    # Because otherwise PHP is a weirdo and messes up the table-foreach below.
    #--- Sort the preregs.
    usort($preregs, function ($a, $b) {
        return strcmp($a['cmpKey'], $b['cmpKey']);
    });
    #--- Show the preregs table.
    tableBegin('results', 8);
    tableCaption(false, eventName($eventId));
    tableHeader(explode('|', "Rank|Person|Citizen of|Best {$order[0]}|WR|Best {$order[1]}|WR|"), array(0 => 'class="r"', 3 => 'class="R"', 4 => 'class="R"', 5 => 'class="r"', 6 => 'class="r"', 7 => 'class="f"'));
    $ctr = 0;
    $lastCmpKey = '';
    foreach ($preregs as $prereg) {
        extract($prereg);
        $ctr++;
        $rank = $cmpKey > $lastCmpKey ? $ctr : '';
        $lastCmpKey = $cmpKey;
        tableRow(array($rank, $personId ? personLink($personId, $name) : $name, $countryId, formatValue($score1[0], valueFormat($eventId)), $score1[1], formatValue($score2[0], valueFormat($eventId)), $score2[1], ''));
    }
    tableEnd();
}
 public static function updateValue($id, $value, $name)
 {
     $query = "UPDATE structured_field_value SET value='" . formatValue($value) . "', name='{$name}' WHERE id={$id}";
     $result = mysql_query($query) or die(sqlError(__FILE__, __LINE__, $query));
 }
 public static function updateAsset($id, $asset, $name, $ext)
 {
     $query = "UPDATE structured_field_asset SET asset='" . formatValue($asset) . "', name='{$name}', extension='{$ext}' WHERE id={$id}";
     $result = mysql_query($query) or die(sqlError(__FILE__, __LINE__, $query));
 }
function checkResult($result, &$countryIdSet, &$competitionIdSet, &$eventIdSet, &$formatIdSet, &$roundIdSet)
{
    # pass-by-reference just for speed
    #----------------------------------------------------------------------
    #--- 1) Check the ids (except persons cause they're a bigger beast checked elsewhere)
    if (!isset($countryIdSet[$result['countryId']])) {
        return "bad countryId " . $result['countryId'];
    }
    if (!isset($competitionIdSet[$result['competitionId']])) {
        return "bad competitionId " . $result['competitionId'];
    }
    if (!isset($eventIdSet[$result['eventId']])) {
        return "bad eventId " . $result['eventId'];
    }
    if (!isset($formatIdSet[$result['formatId']])) {
        return "bad formatId " . $result['formatId'];
    }
    if (!isset($roundIdSet[$result['roundId']])) {
        return "bad roundId " . $result['roundId'];
    }
    #--- 2) Let dns, dnf, zer, suc be the number of values of each kind.
    $dns = $dnf = $zer = $suc = 0;
    foreach (range(1, 5) as $i) {
        $value = $result["value{$i}"];
        $dns += $value == -2;
        $dnf += $value == -1;
        $zer += $value == 0;
        $suc += $value > 0;
    }
    #--- 3) Check that no zero-value is followed by a non-zero value.
    foreach (range(1, 4) as $i) {
        if ($result["value{$i}"] == 0 && $result["value" . ($i + 1)] != 0) {
            return "Zero must not be followed by non-zero.";
        }
    }
    #--- 4) Check zer<5 (there must be at least one non-zero value)
    if ($zer == 5) {
        return "There must be at least one non-zero value";
    }
    #--- 5) Check dns+dnf+zer+suc=5 (nothing besides these is allowed)
    if ($dns + $dnf + $zer + $suc != 5) {
        return "Invalid value";
    }
    #--- 6) Sort the successful values into v_1 .. v_suc
    $v = array();
    foreach (range(1, 5) as $i) {
        $value = $result["value{$i}"];
        if ($value > 0) {
            $v[] = $value;
        }
    }
    sort($v);
    array_unshift($v, 0);
    #--- 7) compute best
    $best = $suc > 0 ? $v[1] : ($dnf > 0 ? -1 : -2);
    #--- 8) compute average
    $average = 0;
    $format = $result['formatId'];
    $event = $result['eventId'];
    $bo3_as_mo3 = $format == '3' && ($event == '333bf' || $event == '333fm' || $event == '333ft');
    $scaler = $event == '333fm' ? 100 : 1;
    if ($format == 'm' || $bo3_as_mo3) {
        $average = $zer > 2 ? 0 : ($suc < 3 ? -1 : round(($v[1] + $v[2] + $v[3]) * $scaler / 3));
    }
    if ($format == 'a') {
        $average = $zer > 0 ? 0 : ($suc < 4 ? -1 : round(($v[2] + $v[3] + $v[4]) / 3));
    }
    if ($average > 60000) {
        $average = $average + 50 - ($average + 50) % 100;
    }
    #--- 9) compare the computed best and average with the stored ones
    if ($result['best'] != $best) {
        return "'best' should be {$best}";
    }
    if ($result['average'] != $average) {
        return "'average' should be {$average}";
    }
    #--- 10) check number of zero-values for non-combined rounds
    $round = $result['roundId'];
    if ($round != 'c' && $round != 'd' && $round != 'e' && $round != 'g' && $round != 'h') {
        if ($format == '1' && $zer != 4) {
            return "should have one non-zero value";
        }
        if ($format == '2' && $zer != 3) {
            return "should have two non-zero values";
        }
        if ($format == '3' && $zer != 2) {
            return "should have three non-zero values";
        }
        if ($format == 'm' && $zer != 2) {
            return "should have three non-zero values";
        }
        if ($format == 'a' && $zer != 0) {
            return "shouldn't have zero-values";
        }
    } else {
        if ($format == '2' && $zer < 3) {
            return "should have at most two non-zero values";
        }
        if ($format == '3' && $zer < 2) {
            return "should have at most three non-zero values";
        }
        if ($format == 'm' && $zer < 2) {
            return "should have at most three non-zero values";
        }
    }
    #--- 12) check times over 10 minutes
    if (valueFormat($result['eventId']) == 'time') {
        foreach (range(1, 5) as $i) {
            $value = $result["value{$i}"];
            if ($value > 60000 && $value % 100) {
                return "{$value} should be rounded";
            }
        }
    }
    #--- 13) check correctness of multi results according to H1b and H1c
    if ($result['eventId'] == '333mbf') {
        foreach (range(1, 5) as $i) {
            $value = $result["value{$i}"];
            if ($value < 1) {
                continue;
            }
            $missed = $value % 100;
            $value = intval($value / 100);
            $time = $value % 100000;
            $value = intval($value / 100000);
            $difference = 99 - $value % 100;
            $solved = $difference + $missed;
            $attempted = $solved + $missed;
            if ($time > 3600) {
                return formatValue($result["value{$i}"], 'multi') . " should be below one hour";
            }
            if ($time > 600 * $attempted) {
                return formatValue($result["value{$i}"], 'multi') . " should be below 10 minutes times the number of cubes";
            }
        }
    }
    #--- No error
    return false;
}
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}");
}
    tableBegin('results', 5);
    $lastround = "";
    foreach ($results_view as $result) {
        if ($lastround != $result['eventCellName'] . $result['roundCellName']) {
            $lastround = $result['eventCellName'] . $result['roundCellName'];
            tableCaption(false, $result['eventCellName'] . " - " . $result['roundCellName']);
            tableHeader(array('Person', 'Pos', 'Best', 'Average', 'Details:'), array());
        }
        if ($result['eventId'] == '333fm') {
            $result_format = 'number';
        } elseif ($result['eventId'] == '333mbf') {
            $result_format = 'multi';
        } else {
            $result_format = 'time';
        }
        tableRow(array($result['name'], $result['pos'], formatValue($result['best'], $result_format), formatValue($result['average'], $result_format), formatValue($result['value1'], $result_format) . "&nbsp;&nbsp;&nbsp;" . formatValue($result['value2'], $result_format) . "&nbsp;&nbsp;&nbsp;" . formatValue($result['value3'], $result_format) . "&nbsp;&nbsp;&nbsp;" . formatValue($result['value4'], $result_format) . "&nbsp;&nbsp;&nbsp;" . formatValue($result['value5'], $result_format)));
    }
    tableEnd();
    print "</div>";
} else {
    print "There is no result data to finish importing.";
}
print "</li>";
// Scripts should be run next...
print "<li><p>Run a couple scripts:</p>\n         <ol type='a'>\n           <li><a href='check_results.php?competitionId={$compIdUrl}&show=Show' target='_blank' class='link-external external'>check_results</a></li>\n           <li><a href='persons_check_finished.php?check=+Check+now+' target='_blank' class='link-external external'>persons_check_finished</a></li>\n           <li><a href='persons_finish_unfinished.php?check=+Check+now+' target='_blank' class='link-external external'>persons_finish_unfinished</a></li>\n         </ol>\n       </li>";
// Print Person Data
print "<li>";
$persons_view = $wcadb_conn->boundQuery("SELECT * from InboxPersons WHERE competitionId=? ORDER BY name", array('s', &$compId));
if (count($persons_view) > 0) {
    if (count($results_view) <= 0) {
        print "<p><a href='scripts/import_persons.php?c={$compIdUrl}' class='link-external external call_and_refresh' target='_blank'>Finish importing persons...</a></p>";