/** * Creates a valid clarification */ public function testCreateValidClarification() { // Get a problem $problemData = ProblemsFactory::createProblem(); // Get a contest $contestData = ContestsFactory::createContest(); // Add the problem to the contest ContestsFactory::addProblemToContest($problemData, $contestData); // Create our contestant who will submit the clarification $contestant = UserFactory::createUser(); // Call the API $this->detourBroadcasterCalls(); $clarificationData = ClarificationsFactory::createClarification($problemData, $contestData, $contestant); // Assert status of new contest $this->assertArrayHasKey("clarification_id", $clarificationData['response']); // Verify that clarification was inserted in the database $clarification = ClarificationsDAO::getByPK($clarificationData['response']['clarification_id']); // Verify our retreived clarificatoin $this->assertNotNull($clarification); $this->assertEquals($clarificationData['request']['message'], $clarification->getMessage()); // We need to verify that the contest and problem IDs where properly saved // Extractiing the contest and problem from DB to check IDs $problem = ProblemsDAO::getByAlias($problemData["request"]["alias"]); $contest = ContestsDAO::getByAlias($contestData["request"]["alias"]); $this->assertEquals($contest->getContestId(), $clarification->getContestId()); $this->assertEquals($problem->getProblemId(), $clarification->getProblemId()); }
/** * Check in DB for problem added to contest * * @param array $problemData * @param array $contestData * @param Request $r */ public static function assertProblemAddedToContest($problemData, $contestData, $r) { // Get problem and contest from DB $problem = ProblemsDAO::getByAlias($problemData["request"]["alias"]); $contest = ContestsDAO::getByAlias($contestData["request"]["alias"]); // Get problem-contest and verify it $contest_problems = ContestProblemsDAO::getByPK($contest->getContestId(), $problem->getProblemId()); self::assertNotNull($contest_problems); self::assertEquals($r["points"], $contest_problems->getPoints()); self::assertEquals($r["order_in_contest"], $contest_problems->getOrder()); }
/** * */ public function testViewProblemInAContestDetailsValid() { // Get a contest $contestData = ContestsFactory::createContest(); // Get a user to be the author $author = UserFactory::createUser(); // Get a problem $problemData = ProblemsFactory::createProblem(null, null, 1, $author); // Add the problem to the contest ContestsFactory::addProblemToContest($problemData, $contestData); // Get a user for our scenario $contestant = UserFactory::createUser(); // Prepare our request $r = new Request(); $r["contest_alias"] = $contestData["request"]["alias"]; $r["problem_alias"] = $problemData["request"]["alias"]; // Log in the user $r["auth_token"] = $this->login($contestant); // Explicitly join contest ContestController::apiOpen($r); // Call api $response = ProblemController::apiDetails($r); // Get problem and contest from DB to check it $problemDAO = ProblemsDAO::getByAlias($problemData["request"]["alias"]); $contestDAO = ContestsDAO::getByAlias($contestData["request"]["alias"]); $contestantsDAO = UsersDAO::search(new Users(array("username" => $contestant->getUsername()))); $contestantDAO = $contestantsDAO[0]; // Assert data $this->assertEquals($response["title"], $problemDAO->getTitle()); $this->assertEquals($response["alias"], $problemDAO->getAlias()); $this->assertEquals($response["validator"], $problemDAO->getValidator()); $this->assertEquals($response["time_limit"], $problemDAO->getTimeLimit()); $this->assertEquals($response["memory_limit"], $problemDAO->getMemoryLimit()); $this->assertEquals($response["problemsetter"]['username'], $author->username); $this->assertEquals($response["problemsetter"]['name'], $author->name); $this->assertEquals($response["source"], $problemDAO->getSource()); $this->assertContains("<h1>Entrada</h1>", $response["problem_statement"]); $this->assertEquals($response["order"], $problemDAO->getOrder()); $this->assertEquals($response["score"], 0); // Default data $this->assertEquals(0, $problemDAO->getVisits()); $this->assertEquals(0, $problemDAO->getSubmissions()); $this->assertEquals(0, $problemDAO->getAccepted()); $this->assertEquals(0, $problemDAO->getDifficulty()); // Verify that we have an empty array of runs $this->assertEquals(0, count($response["runs"])); // Verify that problem was marked as Opened $problem_opened = ContestProblemOpenedDAO::getByPK($contestDAO->getContestId(), $problemDAO->getProblemId(), $contestantDAO->getUserId()); $this->assertNotNull($problem_opened); // Verify open time $this->assertEquals(Utils::GetPhpUnixTimestamp(), Utils::GetPhpUnixTimestamp($problem_opened->getOpenTime())); }
static function DeleteAllContests() { try { $contests = ContestsDAO::getAll(); foreach ($contests as $c) { ContestsDAO::delete($c); } } catch (ApiException $e) { // Propagate exception var_dump($e->getArrayMessage()); throw $e; } }
public static function CanEditClarification($user_id, Clarifications $clarification) { if (is_null($clarification) || !is_a($clarification, 'Clarifications')) { return false; } try { $contest = ContestsDAO::getByPK($clarification->getContestId()); $problem = ProblemsDAO::getByPK($clarification->getProblemId()); } catch (Exception $e) { throw new InvalidDatabaseOperationException($e); } if (is_null($contest) || is_null($problem)) { return false; } return $problem->getAuthorId() === $user_id || Authorization::IsContestAdmin($user_id, $contest); }
/** * Tests remove admins */ public function testRemoveAdmin() { // Get a contest $contestData = ContestsFactory::createContest(); // Get users $user = UserFactory::createUser(); $user2 = UserFactory::createUser(); ContestsFactory::addAdminUser($contestData, $user); ContestsFactory::addAdminUser($contestData, $user2); // Prepare request for remove one admin $r = new Request(); $r['auth_token'] = $this->login($contestData['director']); $r['usernameOrEmail'] = $user->getUsername(); $r['contest_alias'] = $contestData['request']['alias']; // Call api ContestController::apiRemoveAdmin($r); $contest = ContestsDAO::getByAlias($contestData['request']['alias']); $this->AssertFalse(Authorization::IsContestAdmin($user->getUserId(), $contest)); $this->AssertTrue(Authorization::IsContestAdmin($user2->getUserId(), $contest)); }
/** * Assert that contest in the request actually exists in the DB * * @param Request $r */ public function assertContest(Request $r) { // Validate that data was written to DB by getting the contest by title $contest = new Contests(); $contest->setTitle($r['title']); $contests = ContestsDAO::search($contest); $contest = $contests[0]; // Assert that we found our contest $this->assertNotNull($contest); $this->assertNotNull($contest->getContestId()); // Assert data was correctly saved $this->assertEquals($r['description'], $contest->getDescription()); $this->assertGreaterThanOrEqual($r['start_time'] - 1, Utils::GetPhpUnixTimestamp($contest->getStartTime())); $this->assertGreaterThanOrEqual($r['start_time'], Utils::GetPhpUnixTimestamp($contest->getStartTime()) + 1); $this->assertGreaterThanOrEqual($r['finish_time'] - 1, Utils::GetPhpUnixTimestamp($contest->getFinishTime())); $this->assertGreaterThanOrEqual($r['finish_time'], Utils::GetPhpUnixTimestamp($contest->getFinishTime()) + 1); $this->assertEquals($r['window_length'], $contest->getWindowLength()); $this->assertEquals($r['public'], $contest->getPublic()); $this->assertEquals($r['alias'], $contest->getAlias()); $this->assertEquals($r['points_decay_factor'], $contest->getPointsDecayFactor()); $this->assertEquals($r['partial_score'], $contest->getPartialScore()); $this->assertEquals($r['submissions_gap'], $contest->getSubmissionsGap()); $this->assertEquals($r['feedback'], $contest->getFeedback()); $this->assertEquals($r['penalty'], $contest->getPenalty()); $this->assertEquals($r['scoreboard'], $contest->getScoreboard()); $this->assertEquals($r['penalty_type'], $contest->penalty_type); $this->assertEquals($r['penalty_calc_policy'], $contest->getPenaltyCalcPolicy()); $this->assertEquals($r['recommended'], $contest->getRecommended()); }
/** * Validates that request contains contest_alias and the api is contest-admin only * * @param Request $r * @throws InvalidDatabaseOperationException * @throws ForbiddenAccessException */ private static function validateStats(Request $r) { Validators::isStringNonEmpty($r["contest_alias"], "contest_alias"); try { $r["contest"] = ContestsDAO::getByAlias($r["contest_alias"]); } catch (Exception $e) { // Operation failed in the data layer throw new InvalidDatabaseOperationException($e); } // This API is Contest Admin only if (is_null($r["contest"]) || !Authorization::IsContestAdmin($r["current_user_id"], $r["contest"])) { throw new ForbiddenAccessException("userNotAllowed"); } }
/** * Entry point for Problem Details API * * @param Request $r * @throws InvalidFilesystemOperationException * @throws InvalidDatabaseOperationException */ public static function apiDetails(Request $r) { // Get user. // Allow unauthenticated requests if we are not openning a problem // inside a contest. try { self::authenticateRequest($r); } catch (ForbiddenAccessException $e) { if (!is_null($r["contest_alias"])) { throw $e; } } // Validate request self::validateDetails($r); $response = array(); // Create array of relevant columns $relevant_columns = array("title", "author_id", "alias", "validator", "time_limit", "validator_time_limit", "overall_wall_time_limit", "extra_wall_time", "memory_limit", "output_limit", "visits", "submissions", "accepted", "difficulty", "creation_date", "source", "order", "points", "public", "languages", "slow", "stack_limit", "email_clarifications"); // Read the file that contains the source if (!ProblemController::isLanguageSupportedForProblem($r)) { // If there is no language file for the problem, return the spanish version. $r['lang'] = 'es'; } $statement_type = ProblemController::getStatementType($r); Cache::getFromCacheOrSet(Cache::PROBLEM_STATEMENT, $r["problem"]->getAlias() . "-" . $r["lang"] . "-" . $statement_type, $r, 'ProblemController::getProblemStatement', $file_content, APC_USER_CACHE_PROBLEM_STATEMENT_TIMEOUT); // Add problem statement to source $response["problem_statement"] = $file_content; $response["problem_statement_language"] = $r['lang']; // Add the example input. $sample_input = null; Cache::getFromCacheOrSet(Cache::PROBLEM_SAMPLE, $r["problem"]->getAlias() . "-sample.in", $r, 'ProblemController::getSampleInput', $sample_input, APC_USER_CACHE_PROBLEM_STATEMENT_TIMEOUT); if (!empty($sample_input)) { $response['sample_input'] = $sample_input; } // Add the problem the response $response = array_merge($response, $r["problem"]->asFilteredArray($relevant_columns)); if (!is_null($r['current_user_id'])) { // Create array of relevant columns for list of runs $relevant_columns = array("guid", "language", "status", "verdict", "runtime", "penalty", "memory", "score", "contest_score", "time", "submit_delay"); // Search the relevant runs from the DB $contest = ContestsDAO::getByAlias($r["contest_alias"]); $keyrun = new Runs(array("user_id" => $r["current_user_id"], "problem_id" => $r["problem"]->getProblemId(), "contest_id" => is_null($r["contest"]) ? null : $r["contest"]->getContestId())); // Get all the available runs done by the current_user try { $runs_array = RunsDAO::search($keyrun); } catch (Exception $e) { // Operation failed in the data layer throw new InvalidDatabaseOperationException($e); } // Add each filtered run to an array if (count($runs_array) >= 0) { $runs_filtered_array = array(); foreach ($runs_array as $run) { $filtered = $run->asFilteredArray($relevant_columns); $filtered['time'] = strtotime($filtered['time']); array_push($runs_filtered_array, $filtered); } } $response["runs"] = $runs_filtered_array; } if (!is_null($r["contest"])) { // At this point, contestant_user relationship should be established. try { $contest_user = ContestsUsersDAO::CheckAndSaveFirstTimeAccess($r["current_user_id"], $r["contest"]->getContestId()); } catch (Exception $e) { // Operation failed in the data layer throw new InvalidDatabaseOperationException($e); } // As last step, register the problem as opened if (!ContestProblemOpenedDAO::getByPK($r["contest"]->getContestId(), $r["problem"]->getProblemId(), $r["current_user_id"])) { //Create temp object $keyContestProblemOpened = new ContestProblemOpened(array("contest_id" => $r["contest"]->getContestId(), "problem_id" => $r["problem"]->getProblemId(), "user_id" => $r["current_user_id"])); try { // Save object in the DB ContestProblemOpenedDAO::save($keyContestProblemOpened); } catch (Exception $e) { // Operation failed in the data layer throw new InvalidDatabaseOperationException($e); } } } else { if (isset($r['show_solvers']) && $r['show_solvers']) { $response['solvers'] = RunsDAO::GetBestSolvingRunsForProblem($r['problem']->problem_id); } } if (!is_null($r['current_user_id'])) { ProblemViewedDAO::MarkProblemViewed($r['current_user_id'], $r['problem']->problem_id); } $response["score"] = self::bestScore($r); $response["status"] = "ok"; return $response; }
/** * Entry point for Problem Details API * * @param Request $r * @throws InvalidFilesystemOperationException * @throws InvalidDatabaseOperationException */ public static function apiDetails(Request $r) { // Get user. // Allow unauthenticated requests if we are not openning a problem // inside a contest. try { self::authenticateRequest($r); } catch (UnauthorizedException $e) { if (!is_null($r['contest_alias'])) { throw $e; } } // Validate request self::validateDetails($r); $response = array(); // Create array of relevant columns $relevant_columns = array('title', 'alias', 'validator', 'time_limit', 'validator_time_limit', 'overall_wall_time_limit', 'extra_wall_time', 'memory_limit', 'output_limit', 'visits', 'submissions', 'accepted', 'difficulty', 'creation_date', 'source', 'order', 'points', 'public', 'languages', 'slow', 'stack_limit', 'email_clarifications'); // Read the file that contains the source if (!ProblemController::isLanguageSupportedForProblem($r)) { // If there is no language file for the problem, return the spanish version. $r['lang'] = 'es'; } $statement_type = ProblemController::getStatementType($r); Cache::getFromCacheOrSet(Cache::PROBLEM_STATEMENT, $r['problem']->getAlias() . '-' . $r['lang'] . '-' . $statement_type, $r, 'ProblemController::getProblemStatement', $file_content, APC_USER_CACHE_PROBLEM_STATEMENT_TIMEOUT); // Add problem statement to source $response['problem_statement'] = $file_content; $response['problem_statement_language'] = $r['lang']; // Add the example input. $sample_input = null; Cache::getFromCacheOrSet(Cache::PROBLEM_SAMPLE, $r['problem']->getAlias() . '-sample.in', $r, 'ProblemController::getSampleInput', $sample_input, APC_USER_CACHE_PROBLEM_STATEMENT_TIMEOUT); if (!empty($sample_input)) { $response['sample_input'] = $sample_input; } // Add the problem the response $response = array_merge($response, $r['problem']->asFilteredArray($relevant_columns)); // If the problem is public or if the user has admin privileges, show the // problem source and alias of owner. if ($r['problem']->public || Authorization::IsProblemAdmin($r['current_user_id'], $r['problem'])) { $problemsetter = UsersDAO::getByPK($r['problem']->author_id); if (!is_null($problemsetter)) { $response['problemsetter'] = array('username' => $problemsetter->username, 'name' => is_null($problemsetter->name) ? $problemsetter->username : $problemsetter->name); } } else { unset($response['source']); } if (!is_null($r['current_user_id'])) { // Create array of relevant columns for list of runs $relevant_columns = array('guid', 'language', 'status', 'verdict', 'runtime', 'penalty', 'memory', 'score', 'contest_score', 'time', 'submit_delay'); // Search the relevant runs from the DB $contest = ContestsDAO::getByAlias($r['contest_alias']); $keyrun = new Runs(array('user_id' => $r['current_user_id'], 'problem_id' => $r['problem']->getProblemId(), 'contest_id' => is_null($r['contest']) ? null : $r['contest']->getContestId())); // Get all the available runs done by the current_user try { $runs_array = RunsDAO::search($keyrun); } catch (Exception $e) { // Operation failed in the data layer throw new InvalidDatabaseOperationException($e); } // Add each filtered run to an array if (count($runs_array) >= 0) { $runs_filtered_array = array(); foreach ($runs_array as $run) { $filtered = $run->asFilteredArray($relevant_columns); $filtered['alias'] = $r['problem']->alias; $filtered['username'] = $r['current_user']->username; $filtered['time'] = strtotime($filtered['time']); array_push($runs_filtered_array, $filtered); } } $response['runs'] = $runs_filtered_array; } if (!is_null($r['contest'])) { // At this point, contestant_user relationship should be established. try { ContestsUsersDAO::CheckAndSaveFirstTimeAccess($r['current_user_id'], $r['contest']->contest_id); } catch (ApiException $e) { throw $e; } catch (Exception $e) { // Operation failed in the data layer throw new InvalidDatabaseOperationException($e); } // As last step, register the problem as opened if (!ContestProblemOpenedDAO::getByPK($r['contest']->getContestId(), $r['problem']->getProblemId(), $r['current_user_id'])) { //Create temp object $keyContestProblemOpened = new ContestProblemOpened(array('contest_id' => $r['contest']->getContestId(), 'problem_id' => $r['problem']->getProblemId(), 'user_id' => $r['current_user_id'])); try { // Save object in the DB ContestProblemOpenedDAO::save($keyContestProblemOpened); } catch (Exception $e) { // Operation failed in the data layer throw new InvalidDatabaseOperationException($e); } } } elseif (isset($r['show_solvers']) && $r['show_solvers']) { $response['solvers'] = RunsDAO::GetBestSolvingRunsForProblem($r['problem']->problem_id); } if (!is_null($r['current_user_id'])) { ProblemViewedDAO::MarkProblemViewed($r['current_user_id'], $r['problem']->problem_id); } $response['score'] = self::bestScore($r); $response['status'] = 'ok'; return $response; }
private static function getScoreboardTimeLimitUnixTimestamp(Contests $contest, $showAllRuns = false) { if ($showAllRuns || ContestsDAO::hasFinished($contest) && $contest->getShowScoreboardAfter()) { // Show full scoreboard to admin users // or if the contest finished and the creator wants to show it at the end return null; } $start = strtotime($contest->getStartTime()); $finish = strtotime($contest->getFinishTime()); $percentage = (double) $contest->scoreboard / 100.0; $limit = $start + (int) (($finish - $start) * $percentage); return $limit; }
/** * Details of a scoreboard. Returns a list with all contests that belong to * the given scoreboard_alias * * @param Request $r */ public static function apiDetails(Request $r) { self::validateGroupScoreboard($r); $response = array(); // Fill contests $response["contests"] = array(); $response["ranking"] = array(); try { $groupScoreboardContestKey = new GroupsScoreboardsContests(array("group_scoreboard_id" => $r["scoreboard"]->group_scoreboard_id)); $r["gscs"] = GroupsScoreboardsContestsDAO::search($groupScoreboardContestKey); $i = 0; $contest_params = array(); foreach ($r["gscs"] as $gsc) { $contest = ContestsDAO::getByPK($gsc->contest_id); $response["contests"][$i] = $contest->asArray(); $response["contests"][$i]["only_ac"] = $gsc->only_ac; $response["contests"][$i]["weight"] = $gsc->weight; // Fill contest params to pass to scoreboardMerge $contest_params[$contest->alias] = array("only_ac" => $gsc->only_ac == 0 ? false : true, "weight" => $gsc->weight); $i++; } } catch (ApiException $ex) { throw $ex; } catch (Exception $ex) { throw new InvalidDatabaseOperationException($ex); } $r["contest_params"] = $contest_params; // Fill details of this scoreboard $response["scoreboard"] = $r["scoreboard"]->asArray(); // If we have contests, calculate merged&filtered scoreboard if (count($response["contests"]) > 0) { // Get merged scoreboard $r["contest_aliases"] = ""; foreach ($response["contests"] as $contest) { $r["contest_aliases"] .= $contest["alias"] . ","; } $r["contest_aliases"] = rtrim($r["contest_aliases"], ","); try { $groupUsers = GroupsUsersDAO::search(new GroupsUsers(array("group_id" => $r["scoreboard"]->group_id))); $r["usernames_filter"] = ""; foreach ($groupUsers as $groupUser) { $user = UsersDAO::getByPK($groupUser->user_id); $r["usernames_filter"] .= $user->username . ","; } $r["usernames_filter"] = rtrim($r["usernames_filter"], ","); } catch (Exception $ex) { throw new InvalidDatabaseOperationException($ex); } $mergedScoreboardResponse = ContestController::apiScoreboardMerge($r); $response["ranking"] = $mergedScoreboardResponse["ranking"]; } $response["status"] = "ok"; return $response; }
public static function getCurrentSession(Request $r) { $authToken = $r['auth_token']; if (is_null($authToken)) { return array('valid' => false, 'id' => null, 'name' => null, 'username' => null, 'email' => null, 'email_md5' => null, 'auth_token' => null, 'is_admin' => false, 'login_url' => '/login/'); } $vo_CurrentUser = AuthTokensDAO::getUserByToken($authToken); if (is_null($vo_CurrentUser)) { // Means user has auth token, but at // does not exist in DB return array('valid' => false, 'id' => null, 'name' => null, 'username' => null, 'email' => null, 'email_md5' => null, 'auth_token' => null, 'is_admin' => false, 'login_url' => '/login/'); } // Get email via his id $vo_Email = EmailsDAO::getByPK($vo_CurrentUser->getMainEmailId()); $_SESSION['omegaup_user'] = array('name' => $vo_CurrentUser->getUsername(), 'email' => !is_null($vo_Email) ? $vo_Email->getEmail() : ''); return array('valid' => true, 'id' => $vo_CurrentUser->getUserId(), 'name' => $vo_CurrentUser->getName(), 'email' => !is_null($vo_Email) ? $vo_Email->getEmail() : '', 'email_md5' => !is_null($vo_Email) ? md5($vo_Email->getEmail()) : '', 'user' => $vo_CurrentUser, 'username' => $vo_CurrentUser->getUsername(), 'auth_token' => $authToken, 'is_email_verified' => $vo_CurrentUser->getVerified(), 'is_admin' => Authorization::IsSystemAdmin($vo_CurrentUser->getUserId()), 'private_contests_count' => ContestsDAO::getPrivateContestsCount($vo_CurrentUser), 'private_problems_count' => ProblemsDAO::getPrivateCount($vo_CurrentUser), 'needs_basic_info' => $vo_CurrentUser->getPassword() == null); }
/** * Try to view a contest before it has started * * @expectedException PreconditionFailedException */ public function testContestNotStartedYet() { // Get a contest $contestData = ContestsFactory::createContest(); // Get a user for our scenario $contestant = UserFactory::createUser(); // Set contest to not started yet $contest = ContestsDAO::getByAlias($contestData['request']['alias']); $contest->setStartTime(Utils::GetTimeFromUnixTimestamp(Utils::GetPhpUnixTimestamp() + 30)); ContestsDAO::save($contest); // Prepare our request $r = new Request(); $r['contest_alias'] = $contestData['request']['alias']; // Log in the user $r['auth_token'] = $this->login($contestant); // Call api $response = ContestController::apiDetails($r); }
/** * Details of a scoreboard. Returns a list with all contests that belong to * the given scoreboard_alias * * @param Request $r */ public static function apiDetails(Request $r) { self::validateGroupScoreboard($r); $response = array(); // Fill contests $response['contests'] = array(); $response['ranking'] = array(); try { $groupScoreboardContestKey = new GroupsScoreboardsContests(array('group_scoreboard_id' => $r['scoreboard']->group_scoreboard_id)); $r['gscs'] = GroupsScoreboardsContestsDAO::search($groupScoreboardContestKey); $i = 0; $contest_params = array(); foreach ($r['gscs'] as $gsc) { $contest = ContestsDAO::getByPK($gsc->contest_id); $response['contests'][$i] = $contest->asArray(); $response['contests'][$i]['only_ac'] = $gsc->only_ac; $response['contests'][$i]['weight'] = $gsc->weight; // Fill contest params to pass to scoreboardMerge $contest_params[$contest->alias] = array('only_ac' => $gsc->only_ac == 0 ? false : true, 'weight' => $gsc->weight); $i++; } } catch (ApiException $ex) { throw $ex; } catch (Exception $ex) { throw new InvalidDatabaseOperationException($ex); } $r['contest_params'] = $contest_params; // Fill details of this scoreboard $response['scoreboard'] = $r['scoreboard']->asArray(); // If we have contests, calculate merged&filtered scoreboard if (count($response['contests']) > 0) { // Get merged scoreboard $r['contest_aliases'] = ''; foreach ($response['contests'] as $contest) { $r['contest_aliases'] .= $contest['alias'] . ','; } $r['contest_aliases'] = rtrim($r['contest_aliases'], ','); try { $groupUsers = GroupsUsersDAO::search(new GroupsUsers(array('group_id' => $r['scoreboard']->group_id))); $r['usernames_filter'] = ''; foreach ($groupUsers as $groupUser) { $user = UsersDAO::getByPK($groupUser->user_id); $r['usernames_filter'] .= $user->username . ','; } $r['usernames_filter'] = rtrim($r['usernames_filter'], ','); } catch (Exception $ex) { throw new InvalidDatabaseOperationException($ex); } $mergedScoreboardResponse = ContestController::apiScoreboardMerge($r); $response['ranking'] = $mergedScoreboardResponse['ranking']; } $response['status'] = 'ok'; return $response; }
if (property_exists($c->meta, "syscall-count")) { $page->addComponent("<td>" . $c->meta->{'syscall-count'} . " </td>"); } else { $page->addComponent("<td> - </td>"); } $page->addComponent("<td><strong>" . $c->meta->status . "</strong></td>"); $page->addComponent("</tr>"); $page->addComponent("</table>"); $page->addComponent("</td></tr>"); } } $page->addComponent("</td>"); $page->addComponent("</tr>"); } $page->addComponent("</table>"); $aV = ContestsDAO::getByAlias($_GET["alias"]); $eContest = new DAOFormComponent($aV); $eContest->setEditable(false); $page->addComponent($eContest); $page->nextTab("Envios"); $page->nextTab("Chavos"); $page->addComponent("Enviar correos, bannear, nuevos weyes, etc"); $page->nextTab("Stats"); $page->addComponent("GAnalitics u otras cosas, mostrar los auth tokens de los weyes que entraron al concurso con los diferentes ip's"); $page->nextTab("Editar"); $page->addComponent("<script>\n\t\tfunction doEditar(){\n\t\t\t\t var toSend = {};\n\t\t\t\t //upadateContes\n\t\t\t\t \$(\"table input\").each( function (n, el ){ \n\t\t\t\t \t\tif(el.value.length == 0 ) return;\n\t\t\t\t\t\ttoSend[ el.name ] = el.value;\n\t\t\t\t });\n\t\t\t\t\n\n\t\t\t\t\$.ajax({\n url: \"../api/contest/\" + toSend.alias + \"/update/\",\n dataType: \"json\",\n type:\"POST\",\n data: toSend,\n beforeSend: function( xhr ) {\n //\$(\"#submit\").hide();\n },\n success: function(a,b,c){\n \$(\"<p title='OmegaUp'>Success !</p>\").dialog({\n\t\t\t\t\t\t\t\tmodal: true,\n\t\t\t\t\t\t\t\tbuttons: {\n\t\t\t\t\t\t\t\t\tOk: function() {\n\t\t\t\t\t\t\t\t\t\t\$( this ).dialog( \"close\" );\n\t\t\t\t\t\t\t\t\t\twindow.location = \"contest.php?alias=\" + \$(\"#_alias\").val();\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n },\n error:function(a,b,c){\n r = \$.parseJSON(a.responseText);\n \$(\"<p title='OmegaUp'>\"+r.error+\"</p>\").dialog({\n\t\t\t\t\t\t\t\tmodal: true,\n\t\t\t\t\t\t\t\tbuttons: {\n\t\t\t\t\t\t\t\t\tOk: function() {\n\t\t\t\t\t\t\t\t\t\t\$( this ).dialog( \"close\" );\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n }\n \n });\n\t\t\t\tconsole.log(toSend);\n\n\t\t}</script>"); $eContest = new DAOFormComponent($aV); $eContest->setEditable(true); $eContest->hideField("contest_id"); $eContest->addOnClick("Editar concurso", "doEditar()"); $page->addComponent($eContest);
/** * Contest director is god, should be able to submit whenever he wants * for testing purposes */ public function testInvalidRunInsideSubmissionsGapForContestDirector() { // Set the context for the first contest $r = $this->setValidRequest(); $this->detourGraderCalls($this->exactly(2)); // Log as contest director $r["auth_token"] = $this->login($this->contestData["director"]); // Set submissions gap of 20 seconds $contest = ContestsDAO::getByAlias($r["contest_alias"]); $contest->setSubmissionsGap(20); ContestsDAO::save($contest); // Call API $response = RunController::apiCreate($r); // Validate the run $this->assertRun($r, $response); // Send a second run. This one should not fail $response = RunController::apiCreate($r); // Validate the run $this->assertRun($r, $response); }
/** * Invalidates relevant caches on run rejudge * * @param RunsDAO $run */ public static function invalidateCacheOnRejudge(Runs $run) { try { // Expire details of the run Cache::deleteFromCache(Cache::RUN_ADMIN_DETAILS, $run->getRunId()); $contest = ContestsDAO::getByPK($run->getContestId()); // Now we need to invalidate problem stats $problem = ProblemsDAO::getByPK($run->getProblemId()); if (!is_null($problem)) { // Invalidar cache stats Cache::deleteFromCache(Cache::PROBLEM_STATS, $problem->getAlias()); } } catch (Exception $e) { // We did our best effort to invalidate the cache... self::$log->warn('Failed to invalidate cache on Rejudge, skipping: '); self::$log->warn($e); } }
private static function clarificationUpdated(Request $r, $time) { try { if (is_null($r['problem'])) { $r['problem'] = ProblemsDAO::GetByPK($r['clarification']->problem_id); } if (is_null($r['contest']) && !is_null($r['clarification']->contest_id)) { $r['contest'] = ContestsDAO::GetByPK($r['clarification']->contest_id); } if (is_null($r['user'])) { $r['user'] = UsersDAO::GetByPK($r['clarification']->author_id); } } catch (Exception $e) { self::$log->error("Failed to broadcast clarification: " . $e); return; } self::$broadcaster->broadcastClarification($r, $time); }
/** * Get Contests which a certain user has participated in * * @param Request $r * @return Contests array * @throws InvalidDatabaseOperationException */ public static function apiContestStats(Request $r) { self::authenticateOrAllowUnauthenticatedRequest($r); $response = array(); $response['contests'] = array(); $user = self::resolveTargetUser($r); // Get contests where user had at least 1 run try { $contestsParticipated = ContestsDAO::getContestsParticipated($user->getUserId()); } catch (Exception $e) { throw new InvalidDatabaseOperationException($e); } $contests = array(); foreach ($contestsParticipated as $contest) { // Get user ranking $scoreboardR = new Request(array('auth_token' => $r['auth_token'], 'contest_alias' => $contest->getAlias(), 'token' => $contest->getScoreboardUrlAdmin())); $scoreboardResponse = ContestController::apiScoreboard($scoreboardR); // Grab the place of the current user in the given contest $contests[$contest->getAlias()]['place'] = null; foreach ($scoreboardResponse['ranking'] as $userData) { if ($userData['username'] == $user->getUsername()) { $contests[$contest->getAlias()]['place'] = $userData['place']; break; } } $contest->toUnixTime(); $contests[$contest->getAlias()]['data'] = $contest->asArray(); } $response['contests'] = $contests; $response['status'] = 'ok'; return $response; }
/** * Given a contest_alias, sets the recommended flag on/off. * Only omegaUp admins can call this API. * * @param Request $r * @return array */ public static function apiSetRecommended(Request $r) { self::authenticateRequest($r); if (!Authorization::IsSystemAdmin($r['current_user_id'])) { throw new ForbiddenAccessException('userNotAllowed'); } // Validate & get contest_alias try { $r['contest'] = ContestsDAO::getByAlias($r['contest_alias']); } catch (Exception $e) { throw new InvalidDatabaseOperationException($e); } if (is_null($r['contest'])) { throw new NotFoundException('contestNotFound'); } // Validate value param Validators::isInEnum($r['value'], 'value', array('0', '1')); $r['contest']->recommended = $r['value']; try { ContestsDAO::save($r['contest']); } catch (Exception $e) { throw new InvalidDatabaseOperationException($e); } return array('status' => 'ok'); }
public static function setScoreboardPercentage($contestData, $percentage) { $contest = ContestsDAO::getByAlias($contestData['request']['alias']); $contest->setScoreboard($percentage); ContestsDAO::save($contest); }
/** * Get Contests which a certain user has participated in * * @param Request $r * @return Contests array * @throws InvalidDatabaseOperationException */ public static function apiContestStats(Request $r) { self::authenticateOrAllowUnauthenticatedRequest($r); $response = array(); $response["contests"] = array(); $user = self::resolveTargetUser($r); $contest_user_key = new ContestsUsers(); $contest_user_key->setUserId($user->getUserId()); // Get contests where user had at least 1 run try { $contestsParticipated = ContestsDAO::getContestsParticipated($user->getUserId()); } catch (Exception $e) { throw new InvalidDatabaseOperationException($e); } $contests = array(); foreach ($contestsParticipated as $contest) { // Get user ranking $scoreboardR = new Request(array("auth_token" => $r["auth_token"], "contest_alias" => $contest->getAlias(), "token" => $contest->getScoreboardUrlAdmin())); $scoreboardResponse = ContestController::apiScoreboard($scoreboardR); // Grab the place of the current user in the given contest $contests[$contest->getAlias()]["place"] = null; foreach ($scoreboardResponse["ranking"] as $userData) { if ($userData["username"] == $user->getUsername()) { $contests[$contest->getAlias()]["place"] = $userData["place"]; break; } } $contest->toUnixTime(); $contests[$contest->getAlias()]["data"] = $contest->asArray(); } $response["contests"] = $contests; $response["status"] = "ok"; return $response; }
function toDate($unix_time) { if (strlen($unix_time) == 0) { return ''; } return FormatTime($unix_time); return $unix_time; return date('F jS h:i:s a', $unix_time); } function toBold($f, $row) { return "<h3 style='margin:0px; padding:0px'>" . $row['title'] . '</h3>'; } $table->addColRender('start_time', 'toDate'); $table->addColRender('finish_time', 'toDate'); $table->addColRender('alias', 'toBold'); $table->addOnClick('alias', "(function(alias){window.location ='contest.php?alias='+alias;})"); $page->addComponent($table); $page->nextTab('Nuevo'); $page->addComponent(new NewContestFormComponent()); $a = new Contests(array('finish_time' => '1970-01-01 00:00:00')); $b = new Contests(array('finish_time' => date('c'))); $rows = ContestsDAO::byRange($a, $b); $table = new TableComponent($header, $rows); $page->nextTab('Pasados'); $table->addColRender('start_time', 'toDate'); $table->addColRender('finish_time', 'toDate'); $table->addColRender('alias', 'toBold'); $table->addOnClick('alias', "(function(alias){window.location ='contest.php?alias='+alias;})"); $page->addComponent($table); $page->render();
/** * Assert that contest in the request actually exists in the DB * * @param Request $r */ public function assertContest(Request $r) { // Validate that data was written to DB by getting the contest by title $contest = new Contests(); $contest->setTitle($r["title"]); $contests = ContestsDAO::search($contest); $contest = $contests[0]; // Assert that we found our contest $this->assertNotNull($contest); $this->assertNotNull($contest->getContestId()); // Assert data was correctly saved $this->assertEquals($r["description"], $contest->getDescription()); $this->assertGreaterThanOrEqual($r["start_time"] - 1, Utils::GetPhpUnixTimestamp($contest->getStartTime())); $this->assertGreaterThanOrEqual($r["start_time"], Utils::GetPhpUnixTimestamp($contest->getStartTime()) + 1); $this->assertGreaterThanOrEqual($r["finish_time"] - 1, Utils::GetPhpUnixTimestamp($contest->getFinishTime())); $this->assertGreaterThanOrEqual($r["finish_time"], Utils::GetPhpUnixTimestamp($contest->getFinishTime()) + 1); $this->assertEquals($r["window_length"], $contest->getWindowLength()); $this->assertEquals($r["public"], $contest->getPublic()); $this->assertEquals($r["alias"], $contest->getAlias()); $this->assertEquals($r["points_decay_factor"], $contest->getPointsDecayFactor()); $this->assertEquals($r["partial_score"], $contest->getPartialScore()); $this->assertEquals($r["submissions_gap"], $contest->getSubmissionsGap()); $this->assertEquals($r["feedback"], $contest->getFeedback()); $this->assertEquals($r["penalty"], $contest->getPenalty()); $this->assertEquals($r["scoreboard"], $contest->getScoreboard()); $this->assertEquals($r["penalty_type"], $contest->penalty_type); $this->assertEquals($r["penalty_calc_policy"], $contest->getPenaltyCalcPolicy()); }
public static final function IsRunInsideSubmissionGap($contest_id, $problem_id, $user_id) { // Get last run $lastrun = self::GetLastRun($contest_id, $problem_id, $user_id); if (is_null($lastrun)) { return true; } $submission_gap = 0; if ($contest_id != null) { // Get submissions gap $contest = ContestsDAO::getByPK($contest_id); $submission_gap = (int) $contest->getSubmissionsGap(); } $submission_gap = max($submission_gap, RunController::$defaultSubmissionGap); return time() >= strtotime($lastrun->getTime()) + $submission_gap; }
/** * Returns a list of contests * * @param Request $r * @return array * @throws InvalidDatabaseOperationException */ public static function apiRefresh(Request $r) { // This is not supposed to be called by end-users, but by the // Grader service. Regular sessions cannot be used since they // expire, so use a pre-shared secret to authenticate that // grants admin-level privileges just for this call. if ($r['token'] !== OMEGAUP_GRADER_SECRET) { throw new ForbiddenAccessException(); } $contest = ContestsDAO::getByAlias($r['alias']); if ($contest === null) { throw new NotFoundException(); } $id = $contest->getContestId(); Scoreboard::RefreshScoreboardCache($id); return array('status' => 'ok'); }