<?php

#----------------------------------------------------------------------
#   Initialization and page contents.
#----------------------------------------------------------------------
$currentSection = 'admin';
require '../includes/_header.php';
require '../includes/_check.php';
analyzeChoices();
adminHeadline('Check results');
$scripts = new WCAClasses\WCAScripts();
$scripts->add('check_results_help.js');
print $scripts->getHTMLAll();
showDescription();
showChoices();
if ($chosenShow) {
    switch ($chosenWhat) {
        case '':
            # Run them all!
        # Run them all!
        case 'individual':
            checkIndividually();
            if ($chosenWhat != '') {
                break;
            }
        case 'ranks':
            checkRelatively();
            if ($chosenWhat != '') {
                break;
            }
        case 'similar':
<?php
#----------------------------------------------------------------------
#   Initialization and page contents.
#----------------------------------------------------------------------

$dontLoadCachedDatabase = true;

error_reporting(E_ALL);
ini_set('display_errors', 1);

$currentSection = 'admin';
require( '../includes/_header.php' );
require( '_helpers.php' );
analyzeChoices();
adminHeadline( 'Compute auxiliary data' );
showDescription();
showChoices();

if( $chosenDoIt ){
  noticeBox3( 0, "Note: At the end of this, when this page is completed, you should see a green success box at the bottom of the page. If not, something went wrong (like an out-of-memory error we recently had, which killed the script)." );

  // Adding best-3 mean computations, for 2014 mean/3 recognition.
  computeBest3();

  computeConciseRecords();
  computeRanks( 'best', 'Single' );
  computeRanks( 'average', 'Average' );
  computeCachedDatabase('../generated/cachedDatabase.php');
  deleteCaches();
  noticeBox3( 1, "Ok, finished.<br />" . wcaDate() );
}
<?php

#----------------------------------------------------------------------
#   Initialization and page contents.
#----------------------------------------------------------------------
$currentSection = 'admin';
require '../includes/_header.php';
analyzeChoices();
adminHeadline('Check rounds/events');
showDescription();
showChoices();
if ($chosenShow) {
    checkRounds();
    checkEvents();
}
require '../includes/_footer.php';
#----------------------------------------------------------------------
function showDescription()
{
    #----------------------------------------------------------------------
    echo "<p style='width:45em'>Check for rounds, to see if rules 9m and 9p about the number of rounds and the qualifications are followed.\n";
    echo "<p style='width:45em'>Check for events, to see if events registered for a competition are the same as events actually happened in the competition.\n";
    echo "<hr />\n";
}
#----------------------------------------------------------------------
function analyzeChoices()
{
    #----------------------------------------------------------------------
    global $chosenCompetitionId, $chosenShow, $competitionCondition, $competitionDescription;
    $chosenCompetitionId = getNormalParam('competitionId');
    $chosenShow = getBooleanParam('show');
<?php

#----------------------------------------------------------------------
#   Initialization and page contents.
#----------------------------------------------------------------------
$currentSection = 'admin';
require '../includes/_header.php';
adminHeadline('Validate media', 'validate_media');
showUpdateSQL();
require '../includes/_footer.php';
#----------------------------------------------------------------------
function showUpdateSQL()
{
    #----------------------------------------------------------------------
    global $mediumId;
    foreach (getRawParamsThisShouldBeAnException() as $key => $value) {
        if (preg_match('/(accept|refuse|info|new|edit|save)(\\d+)/', $key, $match)) {
            $mediumId = $match[2];
            $func = $match[1] . 'Medium';
            $func();
        }
    }
}
#----------------------------------------------------------------------
function refuseMedium()
{
    #----------------------------------------------------------------------
    global $mediumId;
    $command = "DELETE FROM CompetitionsMedia WHERE id='{$mediumId}'";
    dbCommand($command);
    echo "I just did this : \n";
<?php

$jQuery = 1;
$jQuery_chosen = 1;
$currentSection = 'admin';
require '../includes/_header.php';
adminHeadline('Upload Competition Results &amp; Scrambles');
$scripts = new WCAClasses\WCAScripts();
$scripts->add('data_upload_help.js');
print $scripts->getHTMLAll();
// create form structure
$form = new WCAClasses\FormBuilder("results-submission", array('method' => 'POST', 'enctype' => 'multipart/form-data'));
$form->addEntity(new WCAClasses\FormBuilderEntities\Markup("<fieldset><legend>Upload Results &amp; Scrambles</legend>"));
// competition to upload JSON for
$competitions_query = "SELECT id, name, countryId\n                       FROM Competitions\n                       ORDER BY (STR_TO_DATE(CONCAT(year,',',month,',',day),'%Y,%m,%d') BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND DATE_ADD(NOW(), INTERVAL 7 DAY)) DESC,\n                          year DESC, month DESC, day DESC\n                       ";
$competitions = $wcadb_conn->dbQuery($competitions_query);
$options = array();
foreach ($competitions as $competition) {
    $options[$competition->id] = $competition->name . " | " . $competition->id . " | " . $competition->countryId;
}
$competition_element = new WCAClasses\FormBuilderEntities\Select("competitionId", $options);
$competition_element->label("Competition");
$form->addEntity($competition_element);
// competition data area
$form->addEntity(new WCAClasses\FormBuilderEntities\Markup("<div id='notice_area' style='clear: both;'></div>"));
$form->addEntity(new WCAClasses\FormBuilderEntities\Markup("<div class='thick-outlined'>"));
// json file upload element
$file_element = new WCAClasses\FormBuilderEntities\Input("json", "file");
$file_element->attribute("accept", ".json")->label("Select JSON File to Import")->validator("");
$form->addEntity($file_element);
// submit button
<?php

#----------------------------------------------------------------------
#   Initialization and page contents.
#----------------------------------------------------------------------
$currentSection = 'admin';
require '../includes/_header.php';
analyzeChoices();
adminHeadline('Check regional record markers');
showDescription();
showChoices();
if ($chosenShow) {
    doTheDarnChecking();
}
require '../includes/_footer.php';
#----------------------------------------------------------------------
function showDescription()
{
    #----------------------------------------------------------------------
    echo "<p>This computes regional record markers for all successful results (value>0). If a result has a stored or computed regional record marker, it is displayed. If the two markers differ, they're shown in red/green.</p>\n\n";
    echo "<p>Only strictly previous competitions (other.<b>end</b>Date &lt; this.<b>start</b>Date) are used to compare, not overlapping competitions. Thus I might wrongfully compute a too good record status (because a result was actually beaten earlier in an overlapping competition) but I should never wrongfully compute a too bad record status.</p>\n\n";
    echo "<p>Inside the same competition, results are sorted first by round, then by value, and then they're declared records on a first-come-first-served basis. This results in the records-are-updated-at-the-end-of-each-round rule you requested.</p>\n\n";
    echo "<p>A result does not need to beat another to get a certain record status, equaling is good enough.</p>\n\n";
    echo "<p>If you choose 'All' both for event and competition, I only show the differences (otherwise the page would be huge).</p>\n\n";
    echo "<hr />\n\n";
}
#----------------------------------------------------------------------
function analyzeChoices()
{
    #----------------------------------------------------------------------
    global $chosenEventId, $chosenCompetitionId, $chosenShow, $chosenAnything;
<?php

#----------------------------------------------------------------------
#   Initialization and page contents.
#----------------------------------------------------------------------
$currentSection = 'admin';
require '../includes/_header.php';
analyzeChoices();
adminHeadline('Validate media');
showDescription();
offerChoices();
showMedia();
require '../includes/_footer.php';
#----------------------------------------------------------------------
function analyzeChoices()
{
    #----------------------------------------------------------------------
    global $chosenType, $chosenStatus, $chosenRegionId, $chosenOrder;
    $chosenType = getNormalParam('type');
    $chosenStatus = getNormalParam('status');
    $chosenRegionId = getNormalParam('regionId');
    $chosenOrder = getNormalParam('order');
    if (!preg_match('/^(article|report|multimedia)$/', $chosenType)) {
        $chosenType = '';
    }
    if (!preg_match('/^(date|submission)$/', $chosenOrder)) {
        $chosenOrder = 'submission';
    }
    if (!preg_match('/^(pending|accepted)$/', $chosenStatus)) {
        // Do we need a "refused" status ?
        $chosenStatus = 'pending';
<?php

#----------------------------------------------------------------------
#   Initialization and page contents.
#----------------------------------------------------------------------
$currentSection = 'admin';
require '../includes/_header.php';
adminHeadline('Check results', 'check_results');
showUpdateSQL();
require '../includes/_footer.php';
#----------------------------------------------------------------------
function showUpdateSQL()
{
    #----------------------------------------------------------------------
    echo "<pre>I'm doing this:\n";
    foreach (getRawParamsThisShouldBeAnException() as $key => $value) {
        if (preg_match('/^setpos([1-9]\\d*)$/', $key, $match) && preg_match('/^[1-9]\\d*$/', $value)) {
            $id = $match[1];
            $command = "UPDATE Results SET pos={$value} WHERE id={$id}";
            echo "{$command}\n";
            dbCommand($command);
        }
    }
    echo "\nFinished.</pre>\n";
}
function offerChoices () {
#----------------------------------------------------------------------
  global $chosenId, $chosenConfirm;

  adminHeadline( 'Change Person' );

  echo "<p style='width:45em'>Choose 'Fix' if you want to replace a person's information in the database. It will modify the Persons table accordingly and the Results table if the person's name is different. This should be used to fix mistakes in the database.</p>\n";

  echo "<p style='width:45em'>Choose 'Update' if the person's name or country has been changed. It will add a new entry in the Persons table and make it the current information for that person (subId=1) but it will not modify the Results table so previous results keep the old name.</p>\n";

  echo "<hr />";

  echo "<form method='POST'>\n";
  echo "<table class='prereg'>\n";
  textField( 'id', 'WCA Id', $chosenId, 11 );

  if( ! $chosenConfirm ) {
    echo "<tr><td>&nbsp;</td><td style='text-align:center'>";
    echo "<input type='submit' id='confirm' name='confirm' value='Confirm' style='background-color:#9F3;font-weight:bold' /> ";
    echo "</td></tr></table></form>";
    return;
  }

  $persons = dbQuery( "SELECT * FROM Persons WHERE id='$chosenId' AND subId=1" );
  if( count( $persons ) == 0 ){
    noticeBox(false, 'Unknown WCA Id '.$chosenId);
    return;
  }

  $person = array_shift( $persons );
  extract( $person );

  #--- Name
  textField( 'name', 'Name', $name, 50 );

  #--- Country
  $countries = dbQuery( "SELECT * FROM Countries" );
  $fieldC = '';
  foreach( $countries as $country ){
    $cId   = $country['id'  ];
    $cName = $country['name'];
    if( $cId == $countryId )
      $fieldC .= "  <option value=\"$cId\" selected='selected' >$cName</option>\n";
    else
      $fieldC .= "  <option value=\"$cId\">$cName</option>\n";
  }
  echo "  <tr><td width='30%'><label for='countryId'><b>Country</b></label></td>\n";
  echo "      <td><select id='countryId' name='countryId'>\n";
  echo $fieldC;
  echo "      </select></td></tr>\n";

  #--- Gender
  if( $gender == 'm' )
    $fieldG = "Male : <input type='radio' id='gender' name='gender' value='m' checked='checked' /> Female : <input type='radio' id='gender' name='gender' value='f' />";
  else if( $gender == 'f' )
    $fieldG = "Male : <input type='radio' id='gender' name='gender' value='m' /> Female : <input type='radio' id='gender' name='gender' value='f' checked='checked' />";
  else
    $fieldG = "Male : <input type='radio' id='gender' name='gender' value='m' /> Female : <input type='radio' id='gender' name='gender' value='f' />";
  echo "  <tr><td width='30%'><label for='gender'><b>Gender</b></label></td><td>$fieldG</td></tr>\n";

  #--- DoB
  echo "  <tr><td><b>Date of birth</b></td><td>";
  echo numberSelect( "day", "Day", 1, 31, $day );
  echo numberSelect( "month", "Month", 1, 12, $month );
  echo numberSelect( "year", "Year", date("Y"), date("Y")-100, $year );
  echo "</td></tr>\n";  

  #--- Submit
  echo "<tr><td>&nbsp;</td><td style='text-align:center'>";
  echo "<input type='submit' id='update' name='update' value='Update' style='background-color:#9F3;font-weight:bold' /> ";
?>
  <script>
    (function() {
      $('#update').click(function(e) {
        if(!confirm("Are you sure that you want to \"update\", not \"fix\", the competitor's data? (see information above)")) {
          e.preventDefault();
        }
      });
    })();
  </script>
<?php
  echo "<input type='submit' id='fix' name='fix' value='Fix' style='background-color:#9F3;font-weight:bold' /> ";
  echo "</td></tr></table></form>";

}
<?php
#----------------------------------------------------------------------
#   Initialization and page contents.
#----------------------------------------------------------------------

$currentSection = 'admin';
require( '../includes/_header.php' );
analyzeChoices();
adminHeadline( 'Export to public' );
showDescription();
showChoices();

if( $chosenExport ){

  exportPublic( array(
    'Results'      => 'SELECT   competitionId, eventId, roundId, pos,
                                best, average,
                                personName, personId, result.countryId AS personCountryId,
                                formatId, value1, value2, value3, value4, value5,
                                regionalSingleRecord, regionalAverageRecord
                       FROM     Results result, Competitions competition, Events event, Rounds round
                       WHERE    competition.id=competitionId AND event.id=eventId AND round.id=roundId
                       ORDER BY competition.year, competition.month, competition.day, competition.id,
                                event.rank, round.rank, pos, average, best, personName',
    'RanksSingle'  => 'SELECT personId, eventId, best, worldRank, continentRank, countryRank FROM RanksSingle',
    'RanksAverage' => 'SELECT personId, eventId, best, worldRank, continentRank, countryRank FROM RanksAverage',
    'Rounds'       => '*',
    'Events'       => '*',
    'Formats'      => '*',
    'Countries'    => 'SELECT id, name, continentId, 0 as latitude, 0 as longitude, 0 as zoom, iso2 FROM Countries',
    'Continents'   => '*',
<?php

$currentSection = 'admin';
require '../includes/_header.php';
adminHeadline('Check finished persons');
$action = getRawParamThisShouldBeAnException('action');
$command = '';
$params = array();
switch ($action) {
    case "fix_person_name":
        $old_name = getRawParamThisShouldBeAnException('old_name');
        $new_name = getRawParamThisShouldBeAnException('new_name');
        $command = 'UPDATE Persons SET name = ? WHERE name = ?';
        $params = array('ss', &$new_name, &$old_name);
        break;
    case "fix_results_name":
        $old_name = getRawParamThisShouldBeAnException('old_name');
        $new_name = getRawParamThisShouldBeAnException('new_name');
        $command = 'UPDATE Results SET personName = ? WHERE personName = ?';
        $params = array('ss', &$new_name, &$old_name);
        break;
    case "fix_results_data":
        $old_id = getRawParamThisShouldBeAnException('old_id');
        $old_name = getRawParamThisShouldBeAnException('old_name');
        $old_country = getRawParamThisShouldBeAnException('old_country');
        $new_id = getRawParamThisShouldBeAnException('new_id');
        $new_name = getRawParamThisShouldBeAnException('new_name');
        $new_country = getRawParamThisShouldBeAnException('new_country');
        $command = 'UPDATE Results SET personId = ?, personName = ?, countryId = ? WHERE personId = ? AND personName = ? AND countryId = ?';
        $params = array('ssssss', &$new_id, &$new_name, &$new_country, &$old_id, &$old_name, &$old_country);
        break;
<?php
#----------------------------------------------------------------------
#   Initialization and page contents.
#----------------------------------------------------------------------

$currentSection = 'admin';
require( '../includes/_header.php' );
analyzeChoices();
adminHeadline( 'Finish unfinished persons' );
showDescription();
showChoices();

if( $chosenCheck ) {
  getPersons();
  getBirthdates();
  showUnfinishedPersons();
}

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. A person is called \"finished\" if it has a non-empty personId. A \"semi-id\" is the id without the running number at the end.</p>\n\n";

  echo "<p>For each unfinished person in the Results table, I show you the few most similar persons. Then you make choices and click \"update\" at the bottom of the page to show and execute your choices. You can:</p>\n\n";

  echo "<ul>\n";
  echo "  <li><p>Choose the person as \"new\", optionally modifying name, country and semi-id. This will add the person to the Persons table (with appropriately extended id) and change its Results accordingly. If this person has both roman and local names, the syntax for the names to be inserted correctly is 'romanName (localName)'.</p></li>\n";
  echo "  <li><p>Choose another person. This will overwrite the person's name/country/id in the Results table with those of the other person.</p></li>\n";
<?php
#----------------------------------------------------------------------
#   Initialization and page contents.
#----------------------------------------------------------------------

$currentSection = 'admin';
require( '../includes/_header.php' );
adminHeadline( 'Finish unfinished persons', 'persons_finish_unfinished' );
showDescription();

finishUnfinishedPersons();

require( '../includes/_footer.php' );

#----------------------------------------------------------------------
function showDescription () {
#----------------------------------------------------------------------

  echo "<p>The following commands were executed.</p>\n";
  
  echo "<hr />\n";
}

#----------------------------------------------------------------------
function finishUnfinishedPersons () {
#----------------------------------------------------------------------

  #--- Process all cases.
  while( true ){

    #--- Get old name and country from the case.
function importLocalNames () {
#----------------------------------------------------------------------
  global $chosenUpload, $chosenConfirm, $chosenNamesFile, $chosenFilename;

  $oneBad = false;
  $oneGood = false;

  if( $chosenUpload ){

    $upload_path = '../upload/';
    if( $chosenFilename == '' )
      $chosenFilename = 'tmp' . rand();

    if( ! $chosenConfirm )
      move_uploaded_file( $_FILES['namesFile']['tmp_name'], $upload_path . $chosenFilename . '.txt' );

    $nameLines = file( $upload_path . $chosenFilename . '.txt', FILE_SKIP_EMPTY_LINES );

    foreach( $nameLines as $nameLine ){
      $nameLine = rtrim( $nameLine );
      if( count( explode( ',', $nameLine )) != 2 ){
        echo "<span style='color:#F00'>Wrong line syntax: <br /> " . htmlEscape( $nameLine ) . "</span><br />\n";
        $oneBad = true;
        continue;
      }

      list( $wcaId, $localName ) = explode( ',', $nameLine );
      $wcaId = utf8_decode( $wcaId );
      $persons = dbQuery( "SELECT name personName FROM Persons WHERE id='$wcaId' AND subId=1" );

      if( count( $persons ) == 0 ){
        echo "<span style='color:#DB0'>Unknown WCA id " . htmlEscape( $wcaId ) . "</span><br />\n";
        $oneBad = true;
        continue;
      }

      $person = array_shift( $persons );
      extract( $person );

      if( $chosenConfirm ){
        $localName = mysql_real_escape_string( $localName );
        $name = mysql_real_escape_string( extractRomanName( $personName )) . ' (' . $localName . ')';
        $personName = mysql_real_escape_string( $personName );
        dbCommand( "UPDATE Persons SET name='$name' WHERE id='$wcaId' AND subId=1" );
        dbCommand( "UPDATE Results SET personName='$name' WHERE personId='$wcaId' AND personName='$personName'" );
        $oneGood = true;
      }

      else{
        $personLocalName = extractLocalName( $personName );
        if( $localName == ''){
          if( $personLocalName == '' ){}
          else{
            echo "<span style='color:#3C3'>I will remove name ".htmlEscape( $personLocalName )." from ".htmlEscape( $personName )."($wcaId)</span><br />\n";
          }
        }

        else{
          if( $personLocalName == '' ){
            echo "<span style='color:#3C3'>I will add name ".htmlEscape( $localName )." to ".htmlEscape( $personName )."($wcaId)</span><br />\n";
          }
          else{
            echo "<span style='color:#3C3'>I will change name ".htmlEscape( $personLocalName )." to ".htmlEscape( $localName )." for ".htmlEscape( $personName )."($wcaId)</span><br />\n";
          }
        }
      }
    }

    if( $chosenConfirm ){
      if(( $oneGood ) and ( ! $oneBad ))
        noticeBox3( 1, "Complete. All names were updated." );
      if(( $oneGood ) and ( $oneBad ))
        noticeBox3( 0, "Complete. However, some lines were skipped." );
      if(( ! $oneGood ) and ( $oneBad ))
        noticeBox3( -1, "Cound't update anything." );
      if(( ! $oneGood ) and ( ! $oneBad ))
        noticeBox3( 0, "I found an empty text !?" );
      $chosenUpload = false;
      unlink( $upload_path . $chosenFilename . '.txt' );
    }

    else{
      echo "<form method='POST'>\n";
      echo "<input type='hidden' id='namesFile' name='namesFile' value='".htmlEscape($chosenNamesFile)."' />\n";
      echo "<input type='hidden' id='upload' name='upload' value='$chosenUpload' />\n";
      echo "<input type='hidden' id='filename' name='filename' value='".htmlEscape($chosenFilename)."' />\n";
      echo "<input type='submit' id='confirm' name='confirm' value='Confirm' /></form>\n";
    }
  }

  if( ! $chosenUpload ){

    adminHeadline( 'Add local names' );

    echo "<p>You can add or modify local names here, by upload a file containing the names. The file must be a plain text file encoded in UTF-8. Each line must contain: the WCA id, a comma (',') and the name you would like to add. If you want to remove a name from the database, just leave the name part blank.</p>\n";
  
    echo "<p>Example: <br /><br />2009WANG20,王超<br />2009WANG62,王宇欣<br />2009WANG13,王宇轩<br />etc.</p>\n";
    echo "<hr>\n";

    echo "<table class='prereg'>\n";
    echo "  <form method='POST' enctype='multipart/form-data'>\n";
    echo "  <tr><td width='30%'><label for='namesFile'>Upload file: </label></td>\n";
    echo "      <td><input type='file' id='namesFile' name='namesFile' /></td>\n";
    echo "      <td><input type='submit' id='upload' name='upload' value='Upload' /></td></tr></form>\n";
    echo "</table>\n";
  }
}
<?php

#----------------------------------------------------------------------
#   Initialization and page contents.
#----------------------------------------------------------------------
$currentSection = 'admin';
require '../includes/_header.php';
adminHeadline('Check rounds', 'check_rounds');
showUpdateSQL();
require '../includes/_footer.php';
#----------------------------------------------------------------------
function showUpdateSQL()
{
    #----------------------------------------------------------------------
    echo "<pre>I'm doing this:\n";
    foreach (getRawParamsThisShouldBeAnException() as $key => $value) {
        if (preg_match('/^setround(\\w*)\\/(\\w*)\\/(\\w*)$/', $key, $match)) {
            $competitionId = $match[1];
            $eventId = $match[2];
            $roundId = $match[3];
            $updateRounds[$competitionId][$eventId][$roundId] = $value;
        }
        if (preg_match('/^confirmround(\\w*)\\/(\\w*)$/', $key, $match)) {
            $competitionId = $match[1];
            $eventId = $match[2];
            $updateRounds[$competitionId][$eventId]['confirm'] = 1;
            // 'confirm' should not be a valid roundId
        }
        if (preg_match('/^deleteres([1-9]\\d*)$/', $key, $match)) {
            $id = $match[1];
            $command = "DELETE FROM Results WHERE id={$id}";