Skip to content

Commit

Permalink
Add support for custom errorMsg in Action::setError + minor changes
Browse files Browse the repository at this point in the history
- Adding support in Action to set a custom error info message.
  Also moving array creation from getError to setError.

- More mysql_queryf to Database class converting

- Remove "signup" specific error code "account-already-exists",
  using "invalid-input" instead with a custom error message

- Remove 'password' column from the SELECT query in the "duplicate username"
  check of SignupAction, is not needed or used.

- Resolve issue #118
  Remove normalization calls in LoginAction and other places.
  Implement pattern requirement in SignupAction.

- Using $db->getRow instead of $row assignment inside `if` statements.

- Replace `/>` with `>` in HTML
  Replace ` >` with `>` in HTML

- Fix bug in actions/wiperun.php where it redirects to job/"" $jobID isn't always
  set.

- JobPage: Remove bogus $request->getSessionData
PHP Notice: Undefined property: WebRequest::$getSessionData in /Users/krinkle/Sites/github/jquery-testswarm/inc/pages/JobPage.php on line 65

- UserPage: Put username in subtitle and set title to "User"

- RunresultsPage: Add additional if statement to termine that the query returned a row,
  and provide a fallback. Else it would output the gzip header without echoing gezipped
  content resulting in a browser failure:

    Error 330 (net::ERR_CONTENT_DECODING_FAILED): Unknown error.

  Also moved override down to Page::execute instead of Page::output so that the
  try catch is still preserved so that a nice 500 page can be generated if things go wrong
  also added a basic title and html output in case row doesn't exist (anymore).

- ScoresPage: Branch logic off into ScoresAction
  • Loading branch information
Krinkle committed Mar 31, 2012
1 parent 1b976a8 commit d16fd64
Show file tree
Hide file tree
Showing 14 changed files with 296 additions and 217 deletions.
16 changes: 7 additions & 9 deletions inc/Action.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ abstract class Action {
"invalid-input" => "One or more input fields were invalid.",
"missing-parameters" => "One ore more required fields were not submitted.",
"requires-post" => "This action requires a POST request.",
"account-already-exists" => "Account already exists. Please login instead."
);

/**
Expand All @@ -44,19 +43,18 @@ abstract class Action {
*/
abstract public function doAction();

final protected function setError( $error ) {
if ( !isset( self::$errorCodes[$error] ) ) {
final protected function setError( $errorCode, $errorMsg = null ) {
if ( !isset( self::$errorCodes[$errorCode] ) ) {
throw new SwarmException( "Unrecognized error code used." );
}
$this->error = $error;
$this->error = array(
"code" => $errorCode,
"info" => $errorMsg === null ? self::$errorCodes[$errorCode] : $errorMsg,
);
}

final public function getError() {
return $this->error
? array(
"code" => $this->error,
"info" => self::$errorCodes[$this->error],
) : false;
return $this->error ? $this->error : false;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion inc/Page.php
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ final public function handleException( Exception $e ) {
$this->setSubTitle( null );

$msg = '<div class="errorbox">An internal error occurred.'
. ' The following error message was caught:<br/><br/><strong>'
. ' The following error message was caught:<br><br><strong>'
. nl2br( htmlspecialchars( $e->getMessage() ) ) . '</strong></div>';

if ( $this->getContext()->getConf()->debug->show_exception_details ) {
Expand Down
5 changes: 5 additions & 0 deletions inc/actions/GetrunAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ public function doAction() {
return;
}

// Create a Client object to verify that the client exists
// throws an exception, caught higher up, if it doesn't exist.
// Also updates the timestamp so that it shows up on HomePage and UserPage
$client = Client::newFromContext( $this->getContext(), $clientID );

$runID = $db->getOne(str_queryf(
"SELECT
run_id
Expand Down
2 changes: 1 addition & 1 deletion inc/actions/LoginAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public function doAction() {
return;
}

$username = preg_replace("/[^a-zA-Z0-9_ -]/", "", $request->getVal( "username" ) );
$username = $request->getVal( "username" );
$password = $request->getVal( "password" );

if ( !$username || !$password ) {
Expand Down
38 changes: 38 additions & 0 deletions inc/actions/ScoresAction.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php
/**
* "Scores" action.
*
* @since 0.1.0
* @package TestSwarm
*/

class ScoresAction extends Action {

public function doAction() {
$db = $this->getContext()->getDB();

$rows = $db->getRows(
"SELECT
users.name as user_name,
SUM(total) as score
FROM
clients, run_client, users
WHERE clients.id = run_client.client_id
AND clients.user_id = users.id
GROUP BY user_id
HAVING score > 0
ORDER by score DESC;"
);

$scores = array();
foreach ( $rows as $pos => $row ) {
$scores[] = array(
"position" => intval( $pos + 1 ), // Array is 0 based
"userName" => $row->user_name,
"score" => intval( $row->score )
);
}

$this->setData( $scores );
}
}
34 changes: 21 additions & 13 deletions inc/actions/SignupAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,11 @@ class SignupAction extends Action {

public function doAction() {

$db = $this->getContext()->getDB();
$request = $this->getContext()->getRequest();

// Already logged in ?
if ( $request->getSessionData( "username" ) && $request->getSessionData( "auth" ) == "yes" ) {
if ( $request->getSessionData( "username" ) && $request->getSessionData( "auth" ) === "yes" ) {
$this->setData( array(
"status" => "logged-in",
"username" => $request->getSessionData( "username" ),
Expand All @@ -26,31 +27,38 @@ public function doAction() {
return;
}

$username = preg_replace("/[^a-zA-Z0-9_ -]/", "", $request->getVal( "username" ) );
$username = $request->getVal( "username" );
$password = $request->getVal( "password" );

if ( !$username || !$password ) {
$this->setError( "missing-parameters" );
return;
}

# Figure out what the user's ID is
$result = mysql_queryf("SELECT id, password FROM users WHERE name = %s;", $username);
// Validate user name (github.com/jquery/testswarm/issues/118)
// Only allow lowercase a-z, 0-9 and dashed, must start with a letter
if ( !preg_match( "/^[a-z][-a-z0-9]*$/", $username ) ) {
$this->setError( "invalid-input", "Username may only contain lowercase a-z, 0-9 and dashes and must start with a letter." );
return;
}

// Check if this user name is already taken
$row = $db->getRow(str_queryf( "SELECT id FROM users WHERE name = %s;", $username ));

if ( $row = mysql_fetch_array($result) ) {
$this->setError( "account-already-exists" );
if ( $row ) {
$this->setError( "invalid-input", "Username \"$username\" is already taken." );
return;
}

# If the user doesn't have one, create a new user account
$result = mysql_queryf(
// Create the user
$db->query(str_queryf(
"INSERT INTO users (name, created, seed) VALUES(%s, %s, RAND());",
$username,
swarmdb_dateformat( SWARM_NOW )
);
$user_id = intval( mysql_insert_id() );
));
$userID = $db->getInsertId();

mysql_queryf(
$db->query(str_queryf(
"UPDATE
users
SET
Expand All @@ -61,8 +69,8 @@ public function doAction() {
LIMIT 1;",
swarmdb_dateformat( SWARM_NOW ),
$password,
$user_id
);
$userID
));

$request->setSessionData( "username", $username );
$request->setSessionData( "auth", "yes" );
Expand Down
110 changes: 65 additions & 45 deletions inc/actions/wiperun.php
Original file line number Diff line number Diff line change
@@ -1,60 +1,80 @@
<?php
$run_id = preg_replace("/[^0-9]/", "", $_POST["run_id"]);
$client_id = preg_replace("/[^0-9]/", "", $_POST["client_id"]);
$request = $swarmContext->getRequest();

$wipedRun = false;
$jobID = false;

if ( $request->wasPosted() ) {

$run_id = $request->getInt( "run_id" );
$client_id = $request->getInt( "client_id" );

if ( $run_id && $client_id && $request->getSessionData( "username" ) && $request->getSessionData( "auth" ) === "yes" ) {

$results = mysql_queryf(
"SELECT
jobs.id as job_id
FROM
users, jobs, runs
WHERE users.name=%s
AND jobs.user_id=users.id
AND runs.id=%u
AND runs.job_id=jobs.id;",
$request->getSessionData( "username" ),
$run_id
);
$row = mysql_fetch_row($results);

if ( $run_id && $client_id && $_SESSION["username"] && $_SESSION["auth"] == "yes" ) {

$results = mysql_queryf(
"SELECT
jobs.id
FROM
users, jobs, runs
WHERE users.name=%s
AND jobs.user_id=users.id
AND runs.id=%u
AND runs.job_id=jobs.id;",
$_SESSION["username"],
$run_id
);

if ( $row = mysql_fetch_row($results) ) {
$job_id = $row[0];

$results = mysql_queryf( "SELECT useragent_id FROM clients WHERE id=%u;", $client_id );

if ( $row = mysql_fetch_row($results) ) {
$useragent_id = $row[0];

mysql_queryf(
"DELETE run_client FROM run_client,clients WHERE run_id=%u AND clients.id=client_id AND clients.useragent_id=%u;",
$run_id,
$useragent_id
);
mysql_queryf(
"UPDATE run_useragent SET status=0, runs=0, completed=0, updated=%s WHERE run_id=%u AND useragent_id=%u;",
swarmdb_dateformat( SWARM_NOW ),
$run_id,
$useragent_id
);
mysql_queryf(
"UPDATE runs SET status=1, updated=%s WHERE id=%u;",
swarmdb_dateformat( SWARM_NOW ),
$run_id
);

$wipedRun = true;
if ( $row ) {
$jobID = $row["job_id"];

$results = mysql_queryf( "SELECT useragent_id FROM clients WHERE id=%u;", $client_id );
$row = mysql_fetch_row( $results );

if ( $row ) {
$useragent_id = $row["useragent_id"];

mysql_queryf(
"DELETE run_client FROM run_client, clients
WHERE run_id = %u
AND clients.id = client_id
AND clients.useragent_id = %u;",
$run_id,
$useragent_id
);
mysql_queryf(
"UPDATE run_useragent
SET status = 0, runs = 0, completed = 0, updated = %s
WHERE run_id = %u
AND useragent_id = %u;",
swarmdb_dateformat( SWARM_NOW ),
$run_id,
$useragent_id
);
mysql_queryf(
"UPDATE runs
SET status = 1, updated = %s
WHERE id = %u;",
swarmdb_dateformat( SWARM_NOW ),
$run_id
);

$wipedRun = true;
}
}
}
}

if ( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] )
&& strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ) == 'xmlhttprequest'
) {
echo json_encode( $wipedRun ? "ok" : "error" );
echo json_encode( $wipedRun && $jobID ? "ok" : "error" );

} elseif ( $wipedRun && $jobID ) {
header("Location: " . swarmpath( "job/{$jobID}" ) );

} else {
header("Location: " . swarmpath( "job/{$job_id}/" ) );
header("Location: " . swarmpath( "" ) );
}

exit;
5 changes: 3 additions & 2 deletions inc/init.php
Original file line number Diff line number Diff line change
Expand Up @@ -112,16 +112,17 @@
"LoginAction" => "inc/actions/LoginAction.php",
"LogoutAction" => "inc/actions/LogoutAction.php",
"SaverunAction" => "inc/actions/SaverunAction.php",
"ScoresAction" => "inc/actions/ScoresAction.php",
"SignupAction" => "inc/actions/SignupAction.php",
# Pages
"GetrunPage" => "inc/pages/GetrunPage.php", // @todo: API
"GetrunPage" => "inc/pages/GetrunPage.php", // @todo: rm Page, add Api
"HomePage" => "inc/pages/HomePage.php",
"JobPage" => "inc/pages/JobPage.php",
"LoginPage" => "inc/pages/LoginPage.php",
"LogoutPage" => "inc/pages/LogoutPage.php",
"RunPage" => "inc/pages/RunPage.php",
"RunresultsPage" => "inc/pages/RunresultsPage.php",
"SaverunPage" => "inc/pages/SaverunPage.php", // @todo: API
"SaverunPage" => "inc/pages/SaverunPage.php", // @todo: rm Page, add Api
"ScoresPage" => "inc/pages/ScoresPage.php",
"SignupPage" => "inc/pages/SignupPage.php",
"UserPage" => "inc/pages/UserPage.php"
Expand Down
Loading

0 comments on commit d16fd64

Please sign in to comment.