Exemplo n.º 1
0
 /**
  *
  */
 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()));
 }
Exemplo n.º 2
0
 /**
  * Create a new run
  *
  * @param Request $r
  * @return array
  * @throws Exception
  * @throws InvalidDatabaseOperationException
  * @throws InvalidFilesystemOperationException
  */
 public static function apiCreate(Request $r)
 {
     // Init
     self::initializeGrader();
     // Authenticate user
     self::authenticateRequest($r);
     // Validate request
     self::validateCreateRequest($r);
     self::$log->info('New run being submitted!!');
     $response = array();
     if (self::$practice) {
         if (OMEGAUP_LOCKDOWN) {
             throw new ForbiddenAccessException('lockdown');
         }
         $submit_delay = 0;
         $contest_id = null;
         $test = 0;
     } else {
         //check the kind of penalty_type for this contest
         $penalty_type = $r['contest']->penalty_type;
         switch ($penalty_type) {
             case 'contest_start':
                 // submit_delay is calculated from the start
                 // of the contest
                 $start = $r['contest']->getStartTime();
                 break;
             case 'problem_open':
                 // submit delay is calculated from the
                 // time the user opened the problem
                 $opened = ContestProblemOpenedDAO::getByPK($r['contest']->getContestId(), $r['problem']->getProblemId(), $r['current_user_id']);
                 if (is_null($opened)) {
                     //holy moly, he is submitting a run
                     //and he hasnt even opened the problem
                     //what should be done here?
                     throw new NotAllowedToSubmitException('runEvenOpened');
                 }
                 $start = $opened->getOpenTime();
                 break;
             case 'none':
             case 'runtime':
                 //we dont care
                 $start = null;
                 break;
             default:
                 self::$log->error('penalty_type for this contests is not a valid option, asuming `none`.');
                 $start = null;
         }
         if (!is_null($start)) {
             //ok, what time is it now?
             $c_time = time();
             $start = strtotime($start);
             //asuming submit_delay is in minutes
             $submit_delay = (int) (($c_time - $start) / 60);
         } else {
             $submit_delay = 0;
         }
         $contest_id = $r['contest']->getContestId();
         $test = Authorization::IsContestAdmin($r['current_user_id'], $r['contest']) ? 1 : 0;
     }
     // Populate new run object
     $run = new Runs(array('user_id' => $r['current_user_id'], 'problem_id' => $r['problem']->getProblemId(), 'contest_id' => $contest_id, 'language' => $r['language'], 'source' => $r['source'], 'status' => 'new', 'runtime' => 0, 'penalty' => $submit_delay, 'memory' => 0, 'score' => 0, 'contest_score' => $contest_id != null ? 0 : null, 'submit_delay' => $submit_delay, 'guid' => md5(uniqid(rand(), true)), 'verdict' => 'JE', 'test' => $test));
     try {
         // Push run into DB
         RunsDAO::save($run);
         SubmissionLogDAO::save(new SubmissionLog(array('user_id' => $run->user_id, 'run_id' => $run->run_id, 'contest_id' => $run->contest_id, 'ip' => ip2long($_SERVER['REMOTE_ADDR']))));
         // Update submissions counter++
         $r['problem']->setSubmissions($r['problem']->getSubmissions() + 1);
         ProblemsDAO::save($r['problem']);
     } catch (Exception $e) {
         // Operation failed in the data layer
         throw new InvalidDatabaseOperationException($e);
     }
     try {
         // Create file for the run
         $filepath = RunController::getSubmissionPath($run);
         FileHandler::CreateFile($filepath, $r['source']);
     } catch (Exception $e) {
         throw new InvalidFilesystemOperationException($e);
     }
     // Call Grader
     try {
         self::$grader->Grade([$run->guid], false, false);
     } catch (Exception $e) {
         self::$log->error('Call to Grader::grade() failed:');
         self::$log->error($e);
     }
     if (self::$practice) {
         $response['submission_deadline'] = 0;
     } else {
         // Add remaining time to the response
         try {
             $contest_user = ContestsUsersDAO::getByPK($r['current_user_id'], $r['contest']->getContestId());
             if ($r['contest']->getWindowLength() === null) {
                 $response['submission_deadline'] = strtotime($r['contest']->getFinishTime());
             } else {
                 $response['submission_deadline'] = min(strtotime($r['contest']->getFinishTime()), strtotime($contest_user->getAccessTime()) + $r['contest']->getWindowLength() * 60);
             }
         } catch (Exception $e) {
             // Operation failed in the data layer
             throw new InvalidDatabaseOperationException($e);
         }
     }
     // Happy ending
     $response['guid'] = $run->getGuid();
     $response['status'] = 'ok';
     // Expire rank cache
     UserController::deleteProblemsSolvedRankCacheList();
     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;
 }
Exemplo n.º 4
0
 /**
  * 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;
 }