Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
teddy => omegaup
<?php
include ("html-to-markdown-2.1.1/HTML_To_Markdown.php");
@include_once ("/opt/omegaup/frontend/server/bootstrap.php");
$omegaup = $conn;
include_once ("teddy.php");
$teddy = $db;
$teddy_casos = "/home/alan/Documents/teddy_migration/teddyonlinejudge.net/opt/teddy-dev/teddy-online-judge/trunk/casos";
$teddy_codigos = "/home/alan/Documents/teddy_migration/teddyonlinejudge.net/opt/teddy-dev/teddy-online-judge/trunk/codigos";
include "util.php";
define("Ubicaciones", 1);
define("SCHOOLS", 2);
define("USERS", 4);
define("PROBLEMS", 8);
define("RUNS", 16);
define("CONTESTS", 32);
define("WRITE_SQL", true);
if (WRITE_SQL) file_put_contents("migration.out", "");
function color_echo($msg, $color = null)
{
$out = "";
switch($color) {
case "green":
$out = "[42m"; //Green background
break;
case "red":
$out = "[41m"; //Red background
break;
case "yellow":
$out = "[43m"; //Yellow background
break;
case "blue":
default:
$out = "[44m"; //Blue background
}
echo chr(27) . "$out" . "$msg" . chr(27) . "[0m\n";
}
color_echo( "====================== teddy->omegaup migration ========================= ");
$proc = $argv[1];
$omegaup->StartTrans();
if ($proc == "restoreomegaup")
{
CleanupDB();
system(" time mysql -u root --password=omegaup omegaup < omegaup.sql");
return;
}
if ($proc == "restoreteddy")
{
system( "time mysql -u root --password=omegaup teddy < latest.sql");
return;
}
set_error_handler(function($errno, $errstr, $errfile, $errline, array $errcontext) {
// error was suppressed with the @-operator
if (0 === error_reporting()) {
return false;
}
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});
if ($proc == "all")
{
$proc = 63;
}
function GetOmegaupSchoolIDFromName( $SchoolName )
{
global $omegaup;
$sql = "SELECT school_id FROM `Schools` where name = \"". mysql_real_escape_string($SchoolName) ."\"";
$o_school = $omegaup->Execute($sql)->GetArray();
if(sizeof ($o_school) == 1 ){ return $o_school[0]["school_id"]; }
return "NULL";
}
function user($user)
{
global $teddy;
global $omegaup;
$sql = "SELECT * from Users where username = \"". mysql_real_escape_string($user) ."\"";
$o_user = $omegaup->Execute($sql)->GetArray();
if(sizeof ($o_user) == 1 ){ return $o_user[0]["user_id"]; }
// No existe el nick, pero tal vez existe su correo
$sql = "SELECT mail from Usuario where "
. " userID = \"". $user. "\"" ;
$t_user = $teddy->Execute($sql)->GetArray();
if (sizeof($t_user) == 1)
{
$sql = "SELECT Users.user_id, username, Emails.email from Users, Emails where "
. " Emails.email = \"". $t_user[0]['mail']. "\" and Users.user_id = Emails.user_id";
$o_usuario = $omegaup->Execute($sql)->GetArray();
if (sizeof($o_usuario) ==1 )
{
return $o_usuario[0]["user_id"];
}
if(sizeof ($o_user) == 1 ){ return $o_user[0]["user_id"]; }
}
else
{
echo "Warning: huh? el usuario $user no existe en teddy .... $sql\n";
}
return NULL;
}
function newrun($rundata)
{
//$r["problem"]->setSubmissions($r["problem"]->getSubmissions() + 1);
}
// teddy probid to oegaup problem_id
function prob($probID)
{
global $omegaup;
global $teddy;
$sql = "SELECT * from Problema where probID = \"". $probID ."\"";
$t_prob = $teddy->Execute($sql)->GetArray();
if (sizeof($t_prob) == 0)
{
echo "Warning: huh? el problema $probID no existe en teddy\n";
return;
}
$alias = prob_alias( $t_prob[0]["titulo"] );
$sql = "SELECT * from Problems where alias = \"". $alias ."\"";
$o_prob = $omegaup->Execute($sql)->GetArray();
if(sizeof ($o_prob) == 0 ){ return NULL; }
return $o_prob[0]["problem_id"];
}
function status($status)
{
switch($status)
{
//('new','waiting','compiling','running','ready')
case "TIEMPO": return "ready";
case "COMPILACION": return "ready";
case "RUNTIME_ERROR": return "ready";
case "OK": return "ready";
case "INCORRECTO": return "ready";
case "NONE": return "ready";
case "NO_SALIDA": return "ready";
case "JUDGING": return "compiling";
case "_WAITING": return "waiting";
case "ERROR": return "ready";
}
}
function veredict($veredict)
{
switch($veredict)
{
// ('AC','PA','PE','WA','TLE',
// 'OLE','MLE','RTE','RFE','CE','JE') NOT NULL,
case "TIEMPO": return "TLE";
case "COMPILACION": return "CE";
case "RUNTIME_ERROR": return "RTE";
case "OK": return "AC";
case "INCORRECTO": return "WA";
case "NONE": return "JE";
case "NO_SALIDA": return "WA";
case "JUDGING": return "JE";
case "_WAITING": return "JE";
case "ERROR": return "JE";
}
}
/* ************************************************
* Ubicaciones
************************************************ */
if ($proc & Ubicaciones)
{
echo "Insertando ubicaciones...\n";
$sql = "SELECT distinct(ubicacion) FROM `Usuario` where LENGTH(ubicacion) > 1
ORDER BY `Usuario`.`ubicacion` ASC ";
$t_ubicaciones = $teddy->Execute($sql)->GetArray();
for ($i = 0; $i < sizeof($t_ubicaciones); $i++)
{
$found = -1;
// Buscar un pais
$sql = "select * from States where name "
. " = \"". mysql_real_escape_string($t_ubicaciones[$i]['ubicacion']). "\" ";
$o_ubicacion = $omegaup->Execute($sql)->GetArray();
if (sizeof($o_ubicacion) ==1 )
{
// estado encontrado
continue;
}
else
{
//buscar en paises
$sql = "select * from Countries where name "
. " = \"". mysql_real_escape_string(trim($t_ubicaciones[$i]['ubicacion'])). "\" ";
$o_ubicacion= $omegaup->Execute($sql)->GetArray();
if (sizeof($o_ubicacion) ==1 )
{
// encontrado, hay un pais pero no un estado, inserta un esatado que se llame igual que el pais
// pais encontrado
//$sql = "INSERT INTO `States` (`state_id`, `country_id`, `state_code`, `name`) "
// . " VALUES (NULL, '". $o_ubicacion[0]['country_id']."', '". $o_ubicacion[0]['country_id']."', '" . $o_ubicacion[0]['name']."');";
//echo "$sql\n";
//if (WRITE_SQL) file_put_contents("migration.out", $sql ."\n",FILE_APPEND | LOCK_EX );
//$omegaup->Execute($sql);
continue;
}
else
{
//Tampoco existe el estado, insertar nuevo.
echo "No existe: " . $t_ubicaciones[$i]['ubicacion']. "\n";
}
}
}
}
/* ************************************************
* schools
************************************************ */
if ($proc & SCHOOLS)
{
echo "\nInsertando escuelas ...\n";
$sql = "SELECT `escuela` , ubicacion
FROM Usuario
WHERE length( escuela ) >2
GROUP BY escuela";
$t_escuelas = $teddy->Execute($sql)->GetArray();
$sql = "SELECT * from Schools";
$o_escuelas = $omegaup->Execute($sql)->GetArray();
$notfound = 0;
for ($i = 0; $i < sizeof($t_escuelas); $i++)
{
if (in_array($t_escuelas[$i]['escuela'] , $fake_schools))
{
continue;
}
$found = -1;
for ($j = 0; $j < sizeof($o_escuelas); $j++)
{
if (strtolower(trim($t_escuelas[$i]['escuela']))
== strtolower($o_escuelas[$j]["name"]))
{
$found = $j;
break;
}
}
if ( $found > -1 )
{
// Escuela encontrada
}
else
{
$notfound++;
// voy a insertar esta nueva escuela, buscar la ubicacion
$sql = "SELECT country_id, state_id FROM `States` where name = \"". mysql_real_escape_string($t_escuelas[$i]['ubicacion']) ."\" ;";
$o_ubicaciones = $omegaup->Execute($sql)->GetArray();
if (sizeof($o_ubicaciones) == 1)
{
//Encontre el estado
$stateid = $o_ubicaciones[0]['state_id'];
$countryid = "\"".$o_ubicaciones[0]['country_id']."\"";
}
else
{
$sql = "SELECT country_id FROM `Countries` where name = \"". mysql_real_escape_string($t_escuelas[$i]['ubicacion']) ."\" ;";
$o_ubicaciones = $omegaup->Execute($sql)->GetArray();
if (sizeof($o_ubicaciones) == 1)
{
//encontre el pais
$stateid = "NULL";
$countryid = "\"".$o_ubicaciones[0]['country_id']."\"";
}
else
{
echo "No country or state for " . $t_escuelas[$i]['ubicacion'] . "\n";
//No hay nada
$stateid = "NULL";
$countryid= "NULL";
}
}
// imprimir escuelas patito
if ($countryid == "NULL" && $stateid == "NULL" && (strlen($t_escuelas[$i]['escuela']) < 3))
{
echo "FAKE? > " . $t_escuelas[$i]['escuela'] . " \n";
}
if ($countryid == "NULL" && $stateid == "NULL" && (strlen($t_escuelas[$i]['escuela']) > 8) && (strpos($t_escuelas[$i]['escuela'], " ") === false))
{
echo "FAKE?? > " . $t_escuelas[$i]['escuela'] . " \n";
}
$sql = "INSERT INTO `Schools` (`school_id`, `state_id`, `country_id`, `name`) VALUES (NULL, ". $stateid .", " .$countryid . ", '"
.mysql_real_escape_string(($t_escuelas[$i]['escuela'])) ."');";
if (WRITE_SQL) file_put_contents("migration.out", $sql ."\n",FILE_APPEND | LOCK_EX );
$omegaup->Execute($sql);
}
}
echo $notfound . " nuevas escuelas\n";
}
/* ************************************************
* users
************************************************ */
if ($proc & USERS)
{
$sql = "select * from Usuario where tried > 0 and (LENGTH(mail) > 0)";
$t_usuarios = $teddy->Execute($sql)->GetArray();
$sql = "SELECT * from Users";
$o_usuarios = $omegaup->Execute($sql)->GetArray();
$ExactamenteEncontrados = 0;
$MailEncontrado = 0;
$NickEncontrados = 0;
$NoEncontrados = 0;
for ($i = 0; $i < sizeof($t_usuarios); $i++)
{
$sql = "SELECT Users.user_id, username from Users, Emails where Users.Username = \"". $t_usuarios[$i]['userID']."\" "
. " and Emails.email = \"". $t_usuarios[$i]['mail']. "\" and Users.user_id = Emails.user_id";
$o_usuario = $omegaup->Execute($sql)->GetArray();
if (sizeof($o_usuario) ==1 )
{
//el usuario existe exactamente
$ExactamenteEncontrados++;
continue;
}
// Mismo Mail
$sql = "SELECT Users.user_id, username, Emails.email from Users, Emails where "
. " Emails.email = \"". $t_usuarios[$i]['mail']. "\" and Users.user_id = Emails.user_id";
$o_usuario = $omegaup->Execute($sql)->GetArray();
if (sizeof($o_usuario) ==1 )
{
// mail encontrado
$MailEncontrado++;
echo "1 correo, 2 nicks >> ". $t_usuarios[$i]['mail'] . " \t\t---teddy: " . $t_usuarios[$i]['userID'] . " - omegaup: " . $o_usuario[0]["username"] . "\n";
continue;
}
// Mismo nick (trouble)
$sql = "SELECT Users.user_id, username, Emails.email from Users, Emails where Users.Username = \"". $t_usuarios[$i]['userID']."\" "
. " and Users.user_id = Emails.user_id";
$o_usuario = $omegaup->Execute($sql)->GetArray();
if (sizeof($o_usuario) ==1 )
{
echo "2 correos, 1 nick \t >> ". $t_usuarios[$i]['userID'] . " \t\t---teddy: " . $t_usuarios[$i]['mail'] . " - omegaup: " . $o_usuario[0]["email"] . "\n";
$NickEncontrados++;
continue;
}
$NoEncontrados++;
$CountryID = "NULL";
$StateID = "NULL";
$SchoolID = "NULL";
if (strlen($t_usuarios[$i]['ubicacion']) > 0)
{
if (array_key_exists($t_usuarios[$i]['ubicacion'], $equivalent_places))
{
$t_usuarios[$i]['ubicacion'] = $equivalent_places[ $t_usuarios[$i]['ubicacion'] ];
}
// Voy a insertar, buscar el estado
$sql = "SELECT * FROM `States` where name = \"". mysql_real_escape_string($t_usuarios[$i]['ubicacion']) ."\" ;";
$o_ubicaciones = $omegaup->Execute($sql)->GetArray();
if (sizeof($o_ubicaciones) == 1)
{
$StateID = $o_ubicaciones[0]['state_id'] ;
$CountryID = "\"" .$o_ubicaciones[0]['country_id'] . "\"" ;
}
else
{
$sql = "SELECT country_id FROM `Countries` where name = \"". mysql_real_escape_string($t_usuarios[$i]['ubicacion']) ."\" ;";
$o_ubicaciones = $omegaup->Execute($sql)->GetArray();
if (sizeof($o_ubicaciones) == 1)
{
$CountryID = "\"" . $o_ubicaciones[0]['country_id'] . "\"" ;
}
else
{
echo "no such state/country : " . $t_usuarios[$i]['ubicacion'] . "\n";
}
}
}
$repeated = array (
"sognare.1@hotmail.com" // este dude tiene un correo y dos nicks
);
if (in_array($t_usuarios[$i]['mail'] , $repeated))
{
echo "Correo repetido >> " . $t_usuarios[$i]['mail'] . "\n";
continue;
}
$sql = "INSERT INTO `Emails` (`email_id`, `email`, `user_id`) VALUES (NULL, \"". $t_usuarios[$i]['mail'] . "\", NULL);";
$omegaup->Execute($sql);
if (WRITE_SQL) file_put_contents("migration.out", $sql ."\n",FILE_APPEND | LOCK_EX );
$MailID = $omegaup->Insert_ID();
// Buscar la escuela de esta persona en omegaup
$SchoolID = GetOmegaupSchoolIDFromName( $t_usuarios[$i]["escuela"] );
$sql = "INSERT INTO `Users`"
. " (`user_id`, `username`, `facebook_user_id`, `password`, `main_email_id`, `name`, `solved`, `submissions`, `country_id`, `state_id`, `school_id`, `scholar_degree`, `graduation_date`, `language_id`, `birth_date`, `last_access`, `verified`, `verification_id`) "
. " VALUES ( "
. "NULL, " // `user_id`
. " \"".$t_usuarios[$i]["userID"]."\", " // `username`
. "NULL, " // `facebook_user_id`
. " \"".$t_usuarios[$i]["pswd"]."\", " // `password`
. "".$MailID.", " // `main_email_id`
. " \"".$t_usuarios[$i]["nombre"]."\", " // `name`
. " ".$t_usuarios[$i]["solved"].", " // `solved`
. " ".$t_usuarios[$i]["tried"].", " // `submissions`
. "$CountryID, " // `country_id`
. "$StateID, " // `state_id`
. "$SchoolID, " // `school_id`
. "NULL, " // `scholar_degree`
. "NULL, " // `graduation_date`
. "1, " // `language_id`
. "NULL, " // `birth_date`
. "CURRENT_TIMESTAMP, " // `last_access`
. "0, " // `verified`
. "NULL" // `verification_id`) "
. ");";
$omegaup->Execute($sql);
$UserID = $omegaup->Insert_ID();
if (WRITE_SQL) file_put_contents("migration.out", $sql ."\n",FILE_APPEND | LOCK_EX );
$sql = "Update `Emails` set user_id = $UserID where `email_id` = $MailID";
$omegaup->Execute($sql);
if (WRITE_SQL) file_put_contents("migration.out", $sql ."\n",FILE_APPEND | LOCK_EX );
}
echo "ExactamenteEncontrados : $ExactamenteEncontrados\n";
echo "MailEncontrado : $MailEncontrado \n";
echo "NickEncontrados : $NickEncontrados \n";
echo "NoEncontrados : $NoEncontrados \n";
}
/* ************************************************
* problemas
************************************************ */
if ($proc & PROBLEMS)
{
color_echo( "\n\n=========================== working on problems =============================");
$sql = "select * from Problema where publico = \"SI\" " ;
$t_problemas = $teddy->Execute($sql)->GetArray();
$ExactamenteEncontrados = 0;
$NoEncontrados = 0;
$pathToMigration = __DIR__;
if(!file_exists("$pathToMigration/zips/"))
system ( "mkdir $pathToMigration/zips/" );
system ( "rm -rf $pathToMigration/zips/*" );
for ($i = 0; $i < sizeof($t_problemas); $i++)
{
$alias = prob_alias( $t_problemas[$i]["titulo"] );
echo "\n=========================== working on $alias ". $t_problemas[$i]['probID'] ."\n";
$sql = "SELECT * from Problems where alias = \"". mysql_real_escape_string( $alias )."\" ";
$o_problema = $omegaup->Execute($sql)->GetArray();
if (sizeof($o_problema) ==1 )
{
//el usuario existe exactamente
echo "Problema duplicado >>" . $t_problemas[$i]['titulo'] . "( ". $alias ." ) \n";
continue;
}
else
{
if ( false === file_exists( "$teddy_casos/" . $t_problemas[$i]['probID'] .".in"))
{
echo "ERROR: No hay casos para " . $t_problemas[$i]['titulo'] . "( ". $alias ." " . $t_problemas[$i]['probID'] . ") \n";
continue;
}
$sql = "INSERT INTO `Problems` "
. "(`problem_id`, `public`, `author_id`, `title`, `alias`, `validator`, `languages`, `server`, `remote_id`, `time_limit`, `memory_limit`, `output_limit`, `visits`, `submissions`, `accepted`, `difficulty`, `creation_date`, `source`, `order`, `tolerance`, `slow`) VALUES ("
. "NULL," // `problem_id`
. "1," // `public`
. "389," /* alanboy */ // `author_id`
. "\"" . $t_problemas[$i]['titulo'] ."\"," // `title`
. "\"" . $alias."\"," // `alias`
. "'token-numeric'," // `validator`
. "'c,cpp,java,py,rb,pl,cs,p,kp,kj,cat,hs,cpp11'," // `languages`
. "NULL," // `server`
. "\"" . $t_problemas[$i]['probID'] ."\"," // `remote_id`
. "\"" . $t_problemas[$i]['tiempoLimite'] ."\"," // `time_limit`
. "'64'," // `memory_limit`
. "'10240'," // `output_limit`
. "0" . "," // . $t_problemas[$i]['vistas'] . "," // `visits`
. $t_problemas[$i]['intentos'] . "," // `submissions`
. $t_problemas[$i]['aceptados'] . "," // `accepted`
. "'0'," // `difficulty`
. "CURRENT_TIMESTAMP ," // `creation_date`
. "\"Teddy Online Judge\"," // `source`
. "'normal'," // `order`
. "'0.000001'," // `tolerance`
. "'0'" // `slow`
. ")";
$omegaup->Execute($sql);
if (WRITE_SQL) file_put_contents("migration.out", $sql ."\n",FILE_APPEND | LOCK_EX );
//Crear el zip para omegaup
mkdir ("$pathToMigration/zips/" . $alias );
mkdir ("$pathToMigration/zips/" . $alias . "/cases" );
$cmd = "cp $teddy_casos/"
. $t_problemas[$i]['probID'] .".*"
. " $pathToMigration/zips/$alias/cases";
printf("Executing $cmd ...\n");
system($cmd);
mkdir ("$pathToMigration/zips/" . $alias . "/statements" );
//if ($t_problemas[$i]['titulo'] == "1979")
//if ($t_problemas[$i]['probID'] == "505")
$prob_markdown = utf8_encode(str_replace ( "<=", "&lt;=", $t_problemas[$i]['problema'] ));
$prob_markdown = (str_replace ( "(data.in)", "", $prob_markdown));
$prob_markdown = (str_replace ( "(data.out)", "", $prob_markdown));
try {
$prob_markdown = html_to_markup ($prob_markdown) ;
} catch (Exception $e) {
color_echo($e->getMessage(), "yellow");
}
file_put_contents("$pathToMigration/zips/" . $alias . "/statements/es.markdown", $prob_markdown);
// Zip
$cmd = "cd $pathToMigration/zips/" . $alias . "/; zip -r prob * > /dev/null";
printf("Executing $cmd ...\n");
system($cmd);
$pathtozip = "$pathToMigration/zips/$alias/$alias.zip";
try{
$p = new ProblemDeployer($alias, ProblemDeployer::CREATE);
$_FILES["problem_contents"] = array();
$_FILES["problem_contents"]["tmp_name"]= "$pathToMigration/zips/$alias/prob.zip";
$p->deploy();
$u = new StdClass();
$u->username = "alanboy";
$p->commit( "Initial commit (migration from teddy)", $u);
}
catch(InvalidParameterException $aiu)
{
color_echo("InvalidParameterException (". $aiu->getMessage() .")", "yellow");
}
catch(Exception $e)
{
color_echo($e, "red");
continue;
}
}
}
}
if ($proc & RUNS)
{
$sql = "select * from Ejecucion where Concurso = -1";
$t_runs = $teddy->Execute($sql)->GetArray();
$nosuchusers = array();
for ($i = 0; $i < sizeof($t_runs); $i++)
{
if (in_array($t_runs[$i]['userID'] , $nosuchusers)) continue;
$user_id = user($t_runs[$i]["userID"]);
$problem_id = prob($t_runs[$i]["probID"]);
if (is_null($user_id))
{
echo "no such user: " . $t_runs[$i]["userID"] . "\n";
array_push($nosuchusers, $t_runs[$i]["userID"] );
continue;
}
if (is_null($problem_id))
{
echo "no such problem: " . $t_runs[$i]["probID"] . "\n";
continue;
}
if (is_null(lang($t_runs[$i]["LANG"])))
{
echo "El run " .$t_runs[$i]["execID"] . " no tiene lenguage, saltando. (user=". $t_runs[$i]["userID"] . ", result=". $t_runs[$i]["status"].") \n";
continue;
}
$sql = "INSERT INTO `Runs` "
. "(`run_id`, `user_id`, `problem_id`, `contest_id`, `guid`, `language`, `status`, `verdict`, `runtime`, `memory`, `score`, `contest_score`, `ip`, `time`, `submit_delay`, `test`, `judged_by`) "
. "VALUES "
. "(NULL, " //`run_id`
. " $user_id, " //`user_id`
. " $problem_id, " //`problem_id`
. " NULL," //`contest_id`
. " '".guid()."', " //`guid`
. " '".lang($t_runs[$i]["LANG"])."', " //`language` `language` enum('c','cpp','java','py','rb','pl','cs','p','kp','kj','cat','hs','cpp11') NOT NULL,
. " '".status($t_runs[$i]["status"])."', " //`status` `status` enum('new','waiting','compiling','running','ready') NOT NULL DEFAULT 'new',
. " '".veredict($t_runs[$i]["status"])."', " //`veredict` `veredict` enum('AC','PA','PE','WA','TLE','OLE','MLE','RTE','RFE','CE','JE') NOT NULL,
. " '".$t_runs[$i]["tiempo"]."', " //`runtime`
. " '0', " //`memory`
. " '0', " //`score`
. " NULL, " //`contest_score` esto dice que no es de un concurso
. " '" . $t_runs[$i]["remoteIP"] . "', " //`ip`
. " '" . $t_runs[$i]["fecha"] . "', " //`time`,
. " '0', " //`submit_delay`
. " '0', " //`test`
. " 'teddyonlinejudge.net' )" ; //`judged_by`)
if (WRITE_SQL) file_put_contents("migration.out", $sql ."\n",FILE_APPEND | LOCK_EX );
$omegaup->Execute($sql);
}
}
if ($proc & CONTESTS)
{
echo "-------------- concursos --------------\n";
$sql = "SELECT * FROM `Concurso` WHERE CID in (SELECT distinct Concurso FROM Ejecucion t WHERE Concurso > 0 ) "
. " and `Titulo` NOT LIKE '%Daily Contest%'";
$t_cocursos = $teddy->Execute($sql)->GetArray();
for ($i = 0; $i < sizeof($t_cocursos); $i++)
{
echo "\n";
$t_owner = user($t_cocursos[$i]["Owner"]);
$exists = true;
$calias = "". prob_alias($t_cocursos[$i]["Titulo"]);
$fix_alias = 0;
do{
$exists = false;
$sql = "SELECT * from Contests where alias = '". $calias ."' ";
$r = $omegaup->Execute($sql)->GetArray();
if (sizeof($r)) {
$exists = true;
$calias .= "2";
$fix_alias ++;
}
}while($exists);
color_echo( "==========================" );
echo "working on contest alias = " . $calias." (teddy cid=".$t_cocursos[$i]["CID"].") \n" ;//`alias`
if (is_null($t_owner))
{
echo "No such user (owner of contest): " . $t_cocursos[$i]["Owner"] . "\n";
$t_owner = user("alanboy");
}
// problemas
$problem_ids = array();
$probs_string = explode(" ", $t_cocursos[$i]["Problemas"]);
for ($a = 0 ; $a < sizeof($probs_string); $a++)
{
$oid = prob($probs_string[$a]) ;
if (!is_null($oid))
{
array_push($problem_ids, $oid );
}
else
echo "Contest: No such problem: " . $probs_string[$a] . "\n";
}
$a = $t_cocursos[$i];
echo " new title = " . $a["Titulo"] . "\n";
echo " new desc = " . $a["Descripcion"] . "\n";
echo "http://127.0.0.1/arena/". $calias . "#ranking\n";
$sql = "INSERT INTO `Contests` "
. " (`contest_id`, `title`, `description`, `start_time`, `finish_time`, `window_length`, `director_id`, `rerun_id`, `public`, `alias`, `scoreboard`, `points_decay_factor`, `partial_score`, `submissions_gap`, `feedback`, `penalty`, `penalty_time_start`, `penalty_calc_policy`, `show_scoreboard_after`, `scoreboard_url`, `scoreboard_url_admin`, `urgent`) "
. " VALUES ( "
. " NULL ," //`contest_id`
. " '".$a["Titulo"]."' ," //`title`
. " '".$a["Descripcion"]."'," //`description`
. " '".$a["Inicio"]."'," //`start_time`
. " '".$a["Final"]."'," //`finish_time`
. " NULL ," //`window_length`
. " ".$t_owner." ," //`director_id`
. " '' ," //`rerun_id`
. " '1' ," //`public`
. " '" .$calias."'," //`alias`
. " '100' ," //`scoreboard`
. " '0' ," //`points_decay_factor`
. " '0' ," //`partial_score`
. " '0' ," //`submissions_gap`
. " '' ," //`feedback`
. " '20' ," //`penalty`
. " 'contest' ," //`penalty_time_start`
. " 'sum' ," //`penalty_calc_policy`
. " '1' ," //`show_scoreboard_after`
. " NULL ," //`scoreboard_url`
. " NULL ," //`scoreboard_url_admin`
. " '0' " //`urgent`
. " )";
if (WRITE_SQL) file_put_contents("migration.out", $sql ."\n",FILE_APPEND | LOCK_EX );
$omegaup->Execute($sql);
$o_ContestID = $omegaup->Insert_ID();
echo " new omegup contest id = " . $o_ContestID . "\n";
$sql = "select * from Ejecucion where Concurso = " . $t_cocursos[$i]["CID"];
$t_runs = $teddy->Execute($sql)->GetArray();
$nosuchusers = array();
// insertar runs para ese concurso
for ($run_index = 0; $run_index < sizeof($t_runs); $run_index++)
{
if (in_array($t_runs[$run_index]['userID'] , $nosuchusers)) continue;
$user_id = user($t_runs[$run_index]["userID"]);
$problem_id = prob($t_runs[$run_index]["probID"]);
if (is_null($user_id))
{
echo "no such user: " . $t_runs[$run_index]["userID"] . "\n";
array_push($nosuchusers, $t_runs[$run_index]["userID"] );
color_Echo("drop contest?", "yellow");
continue;
}
if (is_null($problem_id))
{
echo "no such problem: " . $t_runs[$run_index]["probID"] . "\n";
color_Echo("drop contest?", "yellow");
continue;
}
if (is_null(lang($t_runs[$run_index]["LANG"])))
{
echo "El run " .$t_runs[$run_index]["execID"] . " no tiene lenguage, saltando. (user=". $t_runs[$run_index]["userID"] . ", result=". $t_runs[$run_index]["status"].") \n";
color_Echo("drop contest?", "yellow");
continue;
}
// contest_score := score * Problems_Contests.points
$contest_score = veredict(
$t_runs[$run_index]["status"]) == "AC"
? "100" : "0"; //contest_score
$score = veredict(
$t_runs[$run_index]["status"]) == "AC"
? "1" : "0"; //contest_score
if ($t_runs[$run_index]["fecha"] > $a["Final"])
{
echo "El run " . $t_runs[$run_index]['execID'] . " tiene tiempo > tiempo_final ";
color_Echo("drop contest?", "yellow");
continue;
}
$date1 = new DateTime($t_runs[$run_index]["fecha"]);
$date2 = new DateTime($a["Inicio"]);
$interval = $date1->diff($date2);
$submit_delay = ($interval->y * 365 * 24 * 60 ) +
($interval->m * 30 * 24 * 60 ) +
($interval->d * 24 * 60 ) +
($interval->h * 60 ) +
($interval->i ) ;
echo ".";
$sql = "INSERT INTO `Runs` "
. "(`run_id`, `user_id`, `problem_id`, `contest_id`, `guid`, `language`, `status`, `verdict`, `runtime`, `memory`, `score`, `contest_score`, `ip`, `time`, `submit_delay`, `test`, `judged_by`) "
. "VALUES "
. "(NULL, " //`run_id`
. " $user_id, " //`user_id`
. " $problem_id, " //`problem_id`
. " $o_ContestID," //`contest_id`
. " '".guid()."', " //`guid`
. " '".lang($t_runs[$run_index]["LANG"])."', " //`language` `language` enum('c','cpp','java','py','rb','pl','cs','p','kp','kj','cat','hs','cpp11') NOT NULL,
. " '".status($t_runs[$run_index]["status"])."', " //`status` `status` enum('new','waiting','compiling','running','ready') NOT NULL DEFAULT 'new',
. " '".veredict($t_runs[$run_index]["status"])."', " //`veredict` `veredict` enum('AC','PA','PE','WA','TLE','OLE','MLE','RTE','RFE','CE','JE') NOT NULL,
. " '".$t_runs[$run_index]["tiempo"]."', " //`runtime`
. " '0', " //`memory`
. " '$score', " // 0 - 1 //`score`
. " '$contest_score', " // 0 - 100 //`contest_score`
. " '" . $t_runs[$run_index]["remoteIP"] . "', "//`ip`
. " '" . $t_runs[$run_index]["fecha"] . "', " //`time`,
. " $submit_delay, " //`submit_delay`
. " '0', " //`test`
. " 'teddyonlinejudge.net' )" ; //`judged_by`)
if (WRITE_SQL) file_put_contents("migration.out", $sql ."\n",FILE_APPEND | LOCK_EX );
$omegaup->Execute($sql);
}// Runs
// Insertar relacion Contest-Problema
foreach ($problem_ids as $omegauppid)
{
$sql = "INSERT INTO `Contest_Problems` (`contest_id`, `problem_id`, `points`, `order`) VALUES (?, ?, ?, ?)";
$values = array($o_ContestID, $omegauppid, 100, 1);
if (WRITE_SQL) file_put_contents("migration.out", $sql ."\n",FILE_APPEND | LOCK_EX );
$omegaup->Execute($sql, $values);
}
// Insertar relacion Contest-Users
$sql = "SELECT distinct userID FROM `Ejecucion` WHERE `Concurso` = " . $t_cocursos[$i]["CID"] ;
$t_contest_users = $teddy->Execute($sql)->GetArray();
foreach ($t_contest_users as $user_in_contest)
{
// Contest_Problem
$sql = "INSERT INTO `Contests_Users` (`user_id`, `contest_id`, `access_time`, `score`, `time`) VALUES (?,?,?,?,?)";
$o_user = user($user_in_contest["userID"]);
$values = array( $o_user, $o_ContestID, $t_cocursos[$i]["Inicio"], 0, 0);
$omegaup->Execute($sql, $values);
if (WRITE_SQL) file_put_contents("migration.out", $sql ."\n",FILE_APPEND | LOCK_EX );
// Contest_Problem_Opened
foreach ($problem_ids as $omegauppid)
{
$sql = "INSERT INTO `Contest_Problem_Opened` ( `contest_id`, `problem_id`, `user_id`, `open_time`) VALUES (?,?,?,?)";
$o_user = user($user_in_contest["userID"]);
$values = array( $o_ContestID, $omegauppid, $o_user, $t_cocursos[$i]["Inicio"]);
$omegaup->Execute($sql, $values);
if (WRITE_SQL) file_put_contents("migration.out", $sql ."\n",FILE_APPEND | LOCK_EX );
}
}
}// Concursos
}
$omegaup->CompleteTrans();
//$omegaup->FailTrans();
echo "ok\n";

Está súper prángana que no se puedan dejar comentarios por línea :(

L19 y el UTF-8 apá? de hecho como que parece que por ahí hubo un UTF-8->latin1->UTF-8->latin1, porque todos los caracteres acentuados están dobles.
L98 no se recomienda usar uniqid para esto, además que corres riesgos de colisiones si de repente la máquina se vuelve ultrarrápida. qué te parece mejor bin2hex(openssl_random_pseudo_bytes(16)); ?
L123 mejor avienta una excepción a la mexicana :P
L146 y el sql injection apá?
L231-234 estos deberían ser JE porque son temporales todos (excepto NO_SALIDA que debería ser WA).

L585 ponle tu userid, no? para que tú seas el owner de esos problemas en vez de que anden por ahí volando.

Owner

alanboy commented Jul 1, 2014

revision #3.

L19 OK
L98 OK
L123 regrese null.. ahora si atrapo todos los lenguajes raros/inexistentes
L146 OK
L231-234 OK

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment