Example #1
0
 protected function sendClarificationEmail(Request $r, $time)
 {
     if (!OMEGAUP_EMAIL_SEND_EMAILS || !is_null($r['clarification']->answer) || !$r['problem']->email_clarifications) {
         return;
     }
     try {
         $emails = ProblemsDAO::getExplicitAdminEmails($r['problem']);
         $mail = new PHPMailer();
         $mail->IsSMTP();
         $mail->Host = OMEGAUP_EMAIL_SMTP_HOST;
         $mail->SMTPAuth = true;
         $mail->Password = OMEGAUP_EMAIL_SMTP_PASSWORD;
         $mail->From = OMEGAUP_EMAIL_SMTP_FROM;
         $mail->Port = 465;
         $mail->SMTPSecure = 'ssl';
         $mail->Username = OMEGAUP_EMAIL_SMTP_FROM;
         $mail->FromName = OMEGAUP_EMAIL_SMTP_FROM;
         foreach ($emails as $email) {
             $mail->AddAddress($email);
         }
         $mail->isHTML(true);
         global $smarty;
         $email_params = array('clarification_id' => $r['clarification']->clarification_id, 'clarification_body' => htmlspecialchars($r['clarification']->message), 'problem_alias' => $r['problem']->alias, 'problem_name' => htmlspecialchars($r['problem']->title), 'url' => is_null($r['contest']) ? 'https://omegaup.com/arena/problem/' . $r['problem']->alias . '#clarifications' : 'https://omegaup.com/arena/' . $r['contest']->alias . '#clarifications', 'user_name' => $r['user']->username);
         $mail->Subject = ApiUtils::FormatString($smarty->getConfigVars('clarificationEmailSubject'), $email_params);
         $mail->Body = ApiUtils::FormatString($smarty->getConfigVars('clarificationEmailBody'), $email_params);
         if (!$mail->Send()) {
             $this->log->error('Failed to send mail: ' . $mail->ErrorInfo);
         }
     } catch (Exception $e) {
         $this->log->error('Failed to send clarification email ' . $e->getMessage());
     }
 }
Example #2
0
 public function testEditProblem()
 {
     // Login
     $author = $this->createUserAndLogin();
     // Create a problem
     $problemData = ProblemsFactory::createProblem(null, null, 1, $author);
     // Open problem create
     $this->open('/problemedit.php');
     sleep(1);
     $this->type('name=edit-problem-list', $problemData["request"]["alias"]);
     $this->waitForValue('name=title', $problemData["request"]["title"]);
     $problemNewData = ProblemsFactory::getRequest();
     $this->type('name=title', $problemNewData["request"]["title"]);
     $this->type('source', $problemNewData["request"]["source"]);
     $this->type('time_limit', '666');
     $this->type('memory_limit', '1234');
     $this->type('validator', 'token-caseless');
     $this->type('public', '1');
     // Click inicia sesion
     $this->clickAndWait("//input[@value='Actualizar problema']");
     $this->assertElementContainsText('//*[@id="content"]/div[2]/div', "Problem updated succesfully!");
     // Verify data in DB
     $problem_mask = new Problems();
     $problem_mask->setTitle($problemNewData["request"]["title"]);
     $problems = ProblemsDAO::search($problem_mask);
     // Check that we only retreived 1 element
     $this->assertEquals(1, count($problems));
     $this->assertEquals($problemNewData["request"]["source"], $problems[0]->getSource());
     $this->assertEquals(666, $problems[0]->getTimeLimit());
     $this->assertEquals(1234, $problems[0]->getMemoryLimit());
     $this->assertEquals('token-caseless', $problems[0]->getValidator());
     $this->assertEquals('1', $problems[0]->getPublic());
 }
 /**
  * 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());
 }
Example #5
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()));
 }
 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);
 }
 /**
  * Checks the contest details response
  *
  * @param type $contestData
  * @param type $problems
  * @param type $response
  */
 private function assertContestDetails($contestData, $problems, $response)
 {
     // To validate, grab the contest object directly from the DB
     $contest = ContestsDAO::getByAlias($contestData['request']['alias']);
     // Assert we are getting correct data
     $this->assertEquals($contest->getDescription(), $response['description']);
     $this->assertEquals(Utils::GetPhpUnixTimestamp($contest->getStartTime()), $response['start_time']);
     $this->assertEquals(Utils::GetPhpUnixTimestamp($contest->getFinishTime()), $response['finish_time']);
     $this->assertEquals($contest->getWindowLength(), $response['window_length']);
     $this->assertEquals($contest->getAlias(), $response['alias']);
     $this->assertEquals($contest->getPointsDecayFactor(), $response['points_decay_factor']);
     $this->assertEquals($contest->getPartialScore(), $response['partial_score']);
     $this->assertEquals($contest->getSubmissionsGap(), $response['submissions_gap']);
     $this->assertEquals($contest->getFeedback(), $response['feedback']);
     $this->assertEquals($contest->getPenalty(), $response['penalty']);
     $this->assertEquals($contest->getScoreboard(), $response['scoreboard']);
     $this->assertEquals($contest->penalty_type, $response['penalty_type']);
     $this->assertEquals($contest->getPenaltyCalcPolicy(), $response['penalty_calc_policy']);
     // Assert we have our problems
     $numOfProblems = count($problems);
     $this->assertEquals($numOfProblems, count($response['problems']));
     // Assert problem data
     $i = 0;
     foreach ($response['problems'] as $problem_array) {
         // Get problem from DB
         $problem = ProblemsDAO::getByAlias($problems[$i]['request']['alias']);
         // Assert data in DB
         $this->assertEquals($problem->getTitle(), $problem_array['title']);
         $this->assertEquals($problem->getAlias(), $problem_array['alias']);
         $this->assertEquals($problem->getValidator(), $problem_array['validator']);
         $this->assertEquals($problem->getTimeLimit(), $problem_array['time_limit']);
         $this->assertEquals($problem->getMemoryLimit(), $problem_array['memory_limit']);
         $this->assertEquals($problem->getVisits(), $problem_array['visits']);
         $this->assertEquals($problem->getSubmissions(), $problem_array['submissions']);
         $this->assertEquals($problem->getAccepted(), $problem_array['accepted']);
         $this->assertEquals($problem->getOrder(), $problem_array['order']);
         // Get points of problem from Contest-Problem relationship
         $problemInContest = ContestProblemsDAO::getByPK($contest->getContestId(), $problem->getProblemId());
         $this->assertEquals($problemInContest->getPoints(), $problem_array['points']);
         $i++;
     }
 }
 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);
 }
Example #9
0
 /**
  * Validator for List API
  * 
  * @param Request $r
  * @throws ForbiddenAccessException
  * @throws InvalidDatabaseOperationException
  * @throws NotFoundException
  */
 private static function validateList(Request $r)
 {
     // Defaults for offset and rowcount
     if (!isset($r["offset"])) {
         $r["offset"] = 0;
     }
     if (!isset($r["rowcount"])) {
         $r["rowcount"] = 100;
     }
     if (!Authorization::IsSystemAdmin($r["current_user_id"])) {
         throw new ForbiddenAccessException("userNotAllowed");
     }
     Validators::isNumber($r["offset"], "offset", false);
     Validators::isNumber($r["rowcount"], "rowcount", false);
     Validators::isInEnum($r["status"], "status", array('new', 'waiting', 'compiling', 'running', 'ready'), false);
     Validators::isInEnum($r["verdict"], "verdict", array("AC", "PA", "WA", "TLE", "MLE", "OLE", "RTE", "RFE", "CE", "JE", "NO-AC"), false);
     // Check filter by problem, is optional
     if (!is_null($r["problem_alias"])) {
         Validators::isStringNonEmpty($r["problem_alias"], "problem");
         try {
             $r["problem"] = ProblemsDAO::getByAlias($r["problem_alias"]);
         } catch (Exception $e) {
             // Operation failed in the data layer
             throw new InvalidDatabaseOperationException($e);
         }
         if (is_null($r["problem"])) {
             throw new NotFoundException("problemNotFound");
         }
     }
     Validators::isInEnum($r["language"], "language", array('c', 'cpp', 'cpp11', 'java', 'py', 'rb', 'pl', 'cs', 'pas', 'kp', 'kj', 'cat', 'hs'), false);
     // Get user if we have something in username
     if (!is_null($r["username"])) {
         try {
             $r["user"] = UserController::resolveUser($r["username"]);
         } catch (NotFoundException $e) {
             // If not found, simply ignore it
             $r["username"] = null;
             $r["user"] = null;
         }
     }
 }
Example #10
0
<?php

require_once '../../server/bootstrap.php';
$r = new Request($_REQUEST);
$session = SessionController::apiCurrentSession($r);
$r['statement_type'] = 'html';
$r['show_solvers'] = true;
try {
    $result = ProblemController::apiDetails($r);
    $problem = ProblemsDAO::GetByAlias($result['alias']);
} catch (ApiException $e) {
    header('HTTP/1.1 404 Not Found');
    die(file_get_contents('../404.html'));
}
$smarty->assign('problem_statement', $result['problem_statement']);
$smarty->assign('problem_statement_language', $result['problem_statement_language']);
$smarty->assign('problem_alias', $result['alias']);
$smarty->assign('public', $result['public']);
$smarty->assign('source', $result['source']);
$smarty->assign('title', $result['title']);
$smarty->assign('points', $result['points']);
$smarty->assign('validator', $result['validator']);
$smarty->assign('time_limit', $result['time_limit'] / 1000 . 's');
$smarty->assign('validator_time_limit', $result['validator_time_limit'] / 1000 . 's');
$smarty->assign('overall_wall_time_limit', $result['overall_wall_time_limit'] / 1000 . 's');
$smarty->assign('memory_limit', $result['memory_limit'] / 1024 . 'MB');
$smarty->assign('solvers', $result['solvers']);
$smarty->assign('karel_problem', count(array_intersect(explode(',', $result['languages']), array('kp', 'kj'))) == 2);
if (isset($result['sample_input'])) {
    $smarty->assign('sample_input', $result['sample_input']);
}
Example #11
0
 public static final function byUserType($user_type, $order, $mode, $offset, $rowcount, $query, $user_id, $tag, &$total)
 {
     global $conn;
     // Just in case.
     if ($mode !== 'asc' && $mode !== 'desc') {
         $mode = 'desc';
     }
     // Use BINARY mode to force case sensitive comparisons when ordering by title.
     $collation = $order === 'title' ? 'COLLATE utf8_bin' : '';
     $select = '';
     $sql = '';
     $args = array();
     if ($user_type === USER_ADMIN) {
         $args = array($user_id);
         $select = '
             SELECT
                 100 / LOG2(GREATEST(accepted, 1) + 1)   AS points,
                 accepted / GREATEST(1, submissions)     AS ratio,
                 ROUND(100 * COALESCE(ps.score, 0))      AS score,
                 p.*';
         $sql = '
             FROM
                 Problems p
             LEFT JOIN (
                 SELECT
                     Problems.problem_id,
                     MAX(Runs.score) AS score
                 FROM
                     Problems
                 INNER JOIN
                     Runs ON Runs.user_id = ? AND Runs.problem_id = Problems.problem_id
                 GROUP BY
                     Problems.problem_id
                 ) ps ON ps.problem_id = p.problem_id';
         $added_where = false;
         if (!is_null($tag)) {
             $sql .= ' INNER JOIN Problems_Tags pt ON pt.problem_id = p.problem_id';
             $sql .= ' INNER JOIN Tags t ON pt.tag_id = t.tag_id';
             $sql .= ' WHERE t.name = ?';
             $args[] = $tag;
             $added_where = true;
         }
         if (!is_null($query)) {
             if (!$added_where) {
                 $sql .= ' WHERE';
             } else {
                 $sql .= ' AND';
             }
             $sql .= " title LIKE CONCAT('%', ?, '%') ";
             $args[] = $query;
         }
     } elseif ($user_type === USER_NORMAL && !is_null($user_id)) {
         $select = '
             SELECT
                 100 / LOG2(GREATEST(p.accepted, 1) + 1) AS points,
                 p.accepted / GREATEST(1, p.submissions)     AS ratio,
                 ROUND(100 * COALESCE(ps.score, 0), 2)   AS score,
                 p.*';
         $sql = '
             FROM
                 Problems p
             LEFT JOIN (
                 SELECT
                     pi.problem_id,
                     MAX(r.score) AS score
                 FROM
                     Problems pi
                 INNER JOIN
                     Runs r ON r.user_id = ? AND r.problem_id = pi.problem_id
                 GROUP BY
                     pi.problem_id
             ) ps ON ps.problem_id = p.problem_id
             LEFT JOIN
                 User_Roles ur ON ur.user_id = ? AND p.problem_id = ur.contest_id
             LEFT JOIN
                 Groups_Users gu ON gu.user_id = ?
             LEFT JOIN
                 Group_Roles gr ON gr.group_id = gu.group_id AND p.problem_id = gr.contest_id';
         $args[] = $user_id;
         $args[] = $user_id;
         $args[] = $user_id;
         if (!is_null($tag)) {
             $sql .= ' INNER JOIN Problems_Tags pt ON pt.problem_id = p.problem_id';
             $sql .= ' INNER JOIN Tags t ON pt.tag_id = t.tag_id';
             $sql .= ' WHERE t.name = ? AND pt.public = 1 AND';
             $args[] = $tag;
         } else {
             $sql .= ' WHERE';
         }
         $sql .= '
             (p.public = 1 OR p.author_id = ? OR ur.role_id = 3 OR gr.role_id = 3) ';
         $args[] = $user_id;
         if (!is_null($query)) {
             $sql .= " AND p.title LIKE CONCAT('%', ?, '%')";
             $args[] = $query;
         }
     } elseif ($user_type === USER_ANONYMOUS) {
         $select = '
                 SELECT
                     0 AS score,
                     100 / LOG2(GREATEST(p.accepted, 1) + 1) AS points,
                     accepted / GREATEST(1, p.submissions)   AS ratio,
                     p.*';
         $sql = '
                 FROM
                     Problems p';
         if (!is_null($tag)) {
             $sql .= ' INNER JOIN Problems_Tags pt ON pt.problem_id = p.problem_id';
             $sql .= ' INNER JOIN Tags t ON pt.tag_id = t.tag_id';
             $sql .= ' WHERE t.name = ? AND pt.public = 1 AND';
             $args[] = $tag;
         } else {
             $sql .= ' WHERE';
         }
         $sql .= ' p.public = 1 ';
         if (!is_null($query)) {
             $sql .= " AND p.title LIKE CONCAT('%', ?, '%') ";
             $args[] = $query;
         }
     }
     $total = $conn->GetOne("SELECT COUNT(*) {$sql}", $args);
     // Reset the offset to 0 if out of bounds.
     if ($offset < 0 || $offset > $total) {
         $offset = 0;
     }
     if ($order == 'problem_id') {
         $sql .= " ORDER BY p.problem_id {$collation} {$mode}";
     } elseif ($order == 'points' && $mode == 'desc') {
         $sql .= ' ORDER BY `points` DESC, `accepted` ASC, `submissions` DESC';
     } else {
         $sql .= " ORDER BY `{$order}` {$collation} {$mode}";
     }
     $sql .= ' LIMIT ?, ?';
     $args[] = $offset;
     $args[] = $rowcount;
     $result = $conn->Execute("{$select} {$sql}", $args);
     // Only these fields (plus score, points and ratio) will be returned.
     $filters = array('title', 'submissions', 'accepted', 'alias', 'public');
     $problems = array();
     if (!is_null($result)) {
         foreach ($result as $row) {
             $temp = new Problems($row);
             $problem = $temp->asFilteredArray($filters);
             // score, points and ratio are not actually fields of a Problems object.
             $problem['score'] = $row['score'];
             $problem['points'] = $row['points'];
             $problem['ratio'] = $row['ratio'];
             $problem['tags'] = ProblemsDAO::getTagsForProblem($temp, true);
             array_push($problems, $problem);
         }
     }
     return $problems;
 }
 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);
 }
 /**
  * Tests removed problem admin can't edit a problem anymore
  *
  * @expectedException ForbiddenAccessException
  */
 public function testUpdateProblemWithRemovedProblemAdmin()
 {
     // Get a problem
     $problemData = ProblemsFactory::createProblem();
     // Create our new admin
     $problemAdmin = UserFactory::createUser();
     // Add admin to the problem
     $response = ProblemController::apiAddAdmin(new Request(array('usernameOrEmail' => $problemAdmin->username, 'problem_alias' => $problemData['request']['alias'], 'auth_token' => $this->login($problemData['author']))));
     $this->assertEquals('ok', $response['status']);
     // Then remove the user
     $response = ProblemController::apiRemoveAdmin(new Request(array('usernameOrEmail' => $problemAdmin->username, 'problem_alias' => $problemData['request']['alias'], 'auth_token' => $this->login($problemData['author']))));
     $this->assertEquals('ok', $response['status']);
     //Call API
     $newTitle = 'new title coadmin';
     $response = ProblemController::apiUpdate(new Request(array('problem_alias' => $problemData['request']['alias'], 'title' => $newTitle, 'message' => 'Non-admin powers', 'auth_token' => $this->login($problemAdmin))));
     // Verify data in DB
     $problem_mask = new Problems();
     $problem_mask->setTitle($newTitle);
     $problems = ProblemsDAO::search($problem_mask);
 }
Example #14
0
 /** 
  * Tests removed problem admin can't edit a problem anymore
  * 
  * @expectedException ForbiddenAccessException
  */
 public function testUpdateProblemWithRemovedProblemAdmin()
 {
     // Get a problem
     $problemData = ProblemsFactory::createProblem();
     // Create our new admin
     $problemAdmin = UserFactory::createUser();
     // Add admin to the problem
     $response = ProblemController::apiAddAdmin(new Request(array("usernameOrEmail" => $problemAdmin->username, "problem_alias" => $problemData["request"]["alias"], "auth_token" => $this->login($problemData["author"]))));
     $this->assertEquals("ok", $response["status"]);
     // Then remove the user
     $response = ProblemController::apiRemoveAdmin(new Request(array("usernameOrEmail" => $problemAdmin->username, "problem_alias" => $problemData["request"]["alias"], "auth_token" => $this->login($problemData["author"]))));
     $this->assertEquals("ok", $response["status"]);
     //Call API
     $newTitle = "new title coadmin";
     $response = ProblemController::apiUpdate(new Request(array("problem_alias" => $problemData["request"]["alias"], "title" => $newTitle, "message" => 'Non-admin powers', "auth_token" => $this->login($problemAdmin))));
     // Verify data in DB
     $problem_mask = new Problems();
     $problem_mask->setTitle($newTitle);
     $problems = ProblemsDAO::search($problem_mask);
 }
Example #15
0
 /**
  * Basic new run test
  */
 public function testNewRunValid()
 {
     $r = $this->setValidRequest();
     $this->detourGraderCalls();
     // Call API
     $response = RunController::apiCreate($r);
     $this->assertRun($r, $response);
     // Check problem submissions (1)
     $problem = ProblemsDAO::getByAlias($r["problem_alias"]);
     $this->assertEquals(1, $problem->getSubmissions());
 }
 /**
  * Validator for List API
  *
  * @param Request $r
  * @throws ForbiddenAccessException
  * @throws InvalidDatabaseOperationException
  * @throws NotFoundException
  */
 private static function validateList(Request $r)
 {
     // Defaults for offset and rowcount
     if (!isset($r['offset'])) {
         $r['offset'] = 0;
     }
     if (!isset($r['rowcount'])) {
         $r['rowcount'] = 100;
     }
     if (!Authorization::IsSystemAdmin($r['current_user_id'])) {
         throw new ForbiddenAccessException('userNotAllowed');
     }
     Validators::isNumber($r['offset'], 'offset', false);
     Validators::isNumber($r['rowcount'], 'rowcount', false);
     Validators::isInEnum($r['status'], 'status', array('new', 'waiting', 'compiling', 'running', 'ready'), false);
     Validators::isInEnum($r['verdict'], 'verdict', array('AC', 'PA', 'WA', 'TLE', 'MLE', 'OLE', 'RTE', 'RFE', 'CE', 'JE', 'NO-AC'), false);
     // Check filter by problem, is optional
     if (!is_null($r['problem_alias'])) {
         Validators::isStringNonEmpty($r['problem_alias'], 'problem');
         try {
             $r['problem'] = ProblemsDAO::getByAlias($r['problem_alias']);
         } catch (Exception $e) {
             // Operation failed in the data layer
             throw new InvalidDatabaseOperationException($e);
         }
         if (is_null($r['problem'])) {
             throw new NotFoundException('problemNotFound');
         }
     }
     Validators::isInEnum($r['language'], 'language', array('c', 'cpp', 'cpp11', 'java', 'py', 'rb', 'pl', 'cs', 'pas', 'kp', 'kj', 'cat', 'hs'), false);
     // Get user if we have something in username
     if (!is_null($r['username'])) {
         try {
             $r['user'] = UserController::resolveUser($r['username']);
         } catch (NotFoundException $e) {
             // If not found, simply ignore it
             $r['username'] = null;
             $r['user'] = null;
         }
     }
 }
Example #17
0
 /**
  * Get Problems solved by user
  *
  * @param Request $r
  * @return Problems array
  * @throws InvalidDatabaseOperationException
  */
 public static function apiProblemsSolved(Request $r)
 {
     self::authenticateOrAllowUnauthenticatedRequest($r);
     $response = array();
     $response['problems'] = array();
     $user = self::resolveTargetUser($r);
     try {
         $db_results = ProblemsDAO::getProblemsSolved($user->getUserId());
     } catch (Exception $e) {
         throw new InvalidDatabaseOperationException($e);
     }
     if (!is_null($db_results)) {
         $relevant_columns = array('title', 'alias', 'submissions', 'accepted');
         foreach ($db_results as $problem) {
             if ($problem->getPublic() == 1) {
                 array_push($response['problems'], $problem->asFilteredArray($relevant_columns));
             }
         }
     }
     $response['status'] = 'ok';
     return $response;
 }
 /**
  *
  * Gets a list of problems where current user is the owner
  *
  * @param Request $r
  */
 public static function apiMyList(Request $r)
 {
     self::authenticateRequest($r);
     self::validateList($r);
     $response = array();
     $response['results'] = array();
     try {
         $problems = null;
         if (Authorization::IsSystemAdmin($r['current_user_id'])) {
             $problems = ProblemsDAO::getAll(null, null, 'problem_id', 'DESC');
         } else {
             $problem_mask = new Problems(array('author_id' => $r['current_user_id']));
             $problems = ProblemsDAO::search($problem_mask, 'problem_id', 'DESC', $r['offset'], $r['rowcount']);
         }
         foreach ($problems as $problem) {
             $problemArray = $problem->asArray();
             $problemArray['tags'] = ProblemsDAO::getTagsForProblem($problem, false);
             array_push($response['results'], $problemArray);
         }
     } catch (Exception $e) {
         throw new InvalidDatabaseOperationException($e);
     }
     $response['status'] = 'ok';
     return $response;
 }
 /**
  * Test that we can produce a valid alias from the title
  */
 public function testConstructAliasFromTitle()
 {
     // Get the problem data
     $problemData = ProblemsFactory::getRequest();
     $r = $problemData['request'];
     $problemAuthor = $problemData['author'];
     // Set a valid "complex" title
     $r['title'] = 'Lá Venganza Del Malvado Dr. Liraaa';
     // Login user
     $r['auth_token'] = $this->login($problemAuthor);
     // Get File Uploader Mock and tell Omegaup API to use it
     FileHandler::SetFileUploader($this->createFileUploaderMock());
     // Call the API
     $response = ProblemController::apiCreate($r);
     // Validate
     // Verify response
     $this->assertEquals('ok', $response['status']);
     $this->assertEquals('testplan', $response['uploaded_files'][10]);
     // Verify data in DB
     $problem_mask = new Problems();
     $problem_mask->setTitle($r['title']);
     $problems = ProblemsDAO::search($problem_mask);
     // Check that we only retreived 1 element
     $this->assertEquals(1, count($problems));
     $problem = $problems[0];
     // Verify contest was found
     $this->assertNotNull($problem);
     $this->assertNotNull($problem->getProblemId());
     // Verify DB data
     $this->assertEquals($r['title'], $problem->getTitle());
     // Verify problem contents were copied
     $targetpath = PROBLEMS_PATH . DIRECTORY_SEPARATOR . $problem->getAlias() . DIRECTORY_SEPARATOR;
     $this->assertFileExists($targetpath . 'testplan');
     $this->assertFileExists($targetpath . 'cases');
     $this->assertFileExists($targetpath . 'statements' . DIRECTORY_SEPARATOR . 'en.html');
 }
Example #20
0
 /**
  *
  * Gets a list of problems where current user is the owner
  *
  * @param Request $r
  */
 public static function apiMyList(Request $r)
 {
     self::authenticateRequest($r);
     self::validateList($r);
     $response = array();
     $response["results"] = array();
     try {
         $problems = NULL;
         if (Authorization::IsSystemAdmin($r["current_user_id"])) {
             $problems = ProblemsDAO::getAll(NULL, NULL, "problem_id", 'DESC');
         } else {
             $problem_mask = new Problems(array("author_id" => $r["current_user_id"]));
             $problems = ProblemsDAO::search($problem_mask, "problem_id", 'DESC', $r["offset"], $r["rowcount"]);
         }
         foreach ($problems as $problem) {
             $problemArray = $problem->asArray();
             $problemArray['tags'] = ProblemsDAO::getTagsForProblem($problem, false);
             array_push($response["results"], $problemArray);
         }
     } catch (Exception $e) {
         throw new InvalidDatabaseOperationException($e);
     }
     $response["status"] = "ok";
     return $response;
 }