Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

Implement TestSwarmContext (issue #127) #131

Merged
merged 5 commits into from

2 participants

@Krinkle
Collaborator

Implement TestSwarmContext (issue #127)

Krinkle added some commits
@Krinkle Krinkle Database class update
- Call close() at the beginning of open()
  close() checks if it is open and closes if it is and is an
  innocent no-op otherwise.

- Call open() from Database::__construct

- Add function documentation
b9de29d
@Krinkle Krinkle [TestSwarm OOP] Implement TestSwarmContext
- This reduces the number of global variables to basically 2 (config and context).
  There are still some code paths relying on very generic globals from one file to
  another (such as "$username", "$user_id" etc. from init-usersession.php).
  and the existing uses of mysql_queryf and $swarmBrowser/$swarmRequest.

- Context makes dependency resolving a lot easier, no longer depending on order of
  php includes. Instead things are created on-demand (context->getBD() will create
  the Database object when needed).

- Might also speed up some JSON responses since objects that aren't needed, won't be
  created.

- Adapting existing classes to get their info from the context instead.
  I did this without keeping backwards compatibility. These classes were developed
  only a few days ago, so changed them as if they were created like this from the
  beginning.
 * BrowserInfo:
   - Removed caching from BrowserInfo, became to complicated and not really needed.
   so far it is only used once for the current user agent, and in the event we do
   create it for other user agents, the gain in caching them in case we come across
   the exact same user agent twice within the same request and slim. If that does
   become an issue we can optimize for that when we actually do that.
   - Removed redundant findSwarmUAFromBI method
a9e49fa
@Krinkle Krinkle Update uses of deprecated globals with TestSwarmContext
- All instances of $swarmBrowser replaced, global removed.
- All instances of $swarmConfig replaced, global removed.
- All instances of $swarmDB replaced, global removed.
- All instances of $swarmRequest replaced, global removed.
1aaa420
@Krinkle Krinkle Merge branch 'master' of github.com:Krinkle/testswarm 60f7e23
@Krinkle Krinkle parseUserAgnet >parseUserAgent 8e263b1
@Krinkle Krinkle merged commit 8e263b1 into jquery:master
@staabm staabm commented on the diff
inc/TestSwarm.php
((47 lines not shown))
+ * @return Database
+ */
+ public function getDB() {
+ if ( $this->db === null ) {
+ $this->db = Database::newFromContext( $this );
+ }
+ return $this->db;
+ }
+
+ /**
+ * Get the WebRequest object
+ * @return WebRequest
+ */
+ public function getRequest() {
+ if ( $this->request === null ) {
+ $this->request = new WebRequest( $this );
@staabm
staabm added a note

Maybe also use a static factory method to be consistent... "newFromContext"

@Krinkle Collaborator
Krinkle added a note

Sounds good.

@Krinkle Collaborator
Krinkle added a note
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@staabm staabm commented on the diff
inc/TestSwarm.php
((8 lines not shown))
+ * @since 0.3.0
+ * @package TestSwarm
+ */
+class TestSwarmContext {
+ private $browserInfo, $conf, $db, $request;
+
+ /**
+ * The context is self-initializing. The only thing it
+ * needs to be passed is an array with all setting keys from testswarm.ini
+ * (including ones commented out in the sample file, it has to contain them all)
+ * Population of default values of optional settings happens in init.php
+ * @param $config array
+ */
+ public function __construct( Array $config ) {
+ $conf = new stdClass;
+ foreach ( $config as $key => $val ) {
@staabm
staabm added a note

Does this makes sense? Checking for an array and casting it to an object?

@Krinkle Collaborator
Krinkle added a note

Yes, conf is a 2-level deep object (an object with objects). The variable given is a fresh ini parse, which will be an array of arrays. Casting the main variable to an object will only cast the root level, so I'm looping instead. Although right now all settings are in a subgroup, there may be root settings in the future, hence the check for an array first.

If it's a group, cast the array to an object. Otherwise keep it (a string, number or boolean) as is. See also ./config/testswarm-sample.ini and init.php

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@Krinkle Krinkle referenced this pull request from a commit
@Krinkle Krinkle Use newFromContext style in WebRequest as well
- Addresses comment in PR #131
8644289
@Krinkle Krinkle was assigned
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Mar 21, 2012
  1. @Krinkle

    Database class update

    Krinkle authored
    - Call close() at the beginning of open()
      close() checks if it is open and closes if it is and is an
      innocent no-op otherwise.
    
    - Call open() from Database::__construct
    
    - Add function documentation
  2. @Krinkle

    [TestSwarm OOP] Implement TestSwarmContext

    Krinkle authored
    - This reduces the number of global variables to basically 2 (config and context).
      There are still some code paths relying on very generic globals from one file to
      another (such as "$username", "$user_id" etc. from init-usersession.php).
      and the existing uses of mysql_queryf and $swarmBrowser/$swarmRequest.
    
    - Context makes dependency resolving a lot easier, no longer depending on order of
      php includes. Instead things are created on-demand (context->getBD() will create
      the Database object when needed).
    
    - Might also speed up some JSON responses since objects that aren't needed, won't be
      created.
    
    - Adapting existing classes to get their info from the context instead.
      I did this without keeping backwards compatibility. These classes were developed
      only a few days ago, so changed them as if they were created like this from the
      beginning.
     * BrowserInfo:
       - Removed caching from BrowserInfo, became to complicated and not really needed.
       so far it is only used once for the current user agent, and in the event we do
       create it for other user agents, the gain in caching them in case we come across
       the exact same user agent twice within the same request and slim. If that does
       become an issue we can optimize for that when we actually do that.
       - Removed redundant findSwarmUAFromBI method
Commits on Mar 22, 2012
  1. @Krinkle

    Update uses of deprecated globals with TestSwarmContext

    Krinkle authored
    - All instances of $swarmBrowser replaced, global removed.
    - All instances of $swarmConfig replaced, global removed.
    - All instances of $swarmDB replaced, global removed.
    - All instances of $swarmRequest replaced, global removed.
  2. @Krinkle
  3. @Krinkle

    parseUserAgnet >parseUserAgent

    Krinkle authored
This page is out of date. Refresh to see the latest.
View
19 content/home.php
@@ -61,11 +61,13 @@
/** @return bool: Whether the current user was found in the swarm */
function loadBrowsers($headingTitle, $mobile) {
- global $swarmBrowser, $swarmDB;
+ global $swarmContext;
+ $bi = $swarmContext->getBrowserInfo();
+ $db = $swarmContext->getDB();
$foundSelf = false;
- $rows = $swarmDB->getRows(str_queryf(
+ $rows = $db->getRows(str_queryf(
"SELECT
useragents.engine as engine,
useragents.name as name,
@@ -82,8 +84,8 @@ function loadBrowsers($headingTitle, $mobile) {
AND mobile = %s
ORDER BY engine, name;",
swarmdb_dateformat( strtotime( '1 minute ago' ) ),
- $swarmBrowser->getBrowserCodename(),
- $swarmBrowser->getBrowserVersion(),
+ $bi->getBrowserCodename(),
+ $bi->getBrowserVersion(),
$mobile
));
@@ -116,10 +118,13 @@ function loadBrowsers($headingTitle, $mobile) {
return $foundSelf;
}
+$request = $swarmContext->getRequest();
+$bi = $swarmContext->getBrowserInfo();
+
if ( $found ) { ?>
<div class="join">
<p><strong>TestSwarm Needs Your Help!</strong> You have a browser that we need to test against, you should join the swarm to help us out.</p>
- <?php if ( !$swarmRequest->getSessionData( "username" ) ) { ?>
+ <?php if ( !$request->getSessionData( "username" ) ) { ?>
<form action="" method="get">
<input type="hidden" name="state" value="run"/>
<br/><strong>Username:</strong><br/>
@@ -127,12 +132,12 @@ function loadBrowsers($headingTitle, $mobile) {
<input type="submit" value="Join the Swarm"/>
</form>
<?php } else { ?>
- <br/><p><strong>&raquo; <?php echo $swarmRequest->getSessionData( "username" ); ?></strong> <a href="<?php echo swarmpath("run/{$swarmRequest->getSessionData( "username" )}/" ); ?>">Start Running Tests</a></p>
+ <br/><p><strong>&raquo; <?php echo $request->getSessionData( "username" ); ?></strong> <a href="<?php echo swarmpath("run/{$request->getSessionData( "username" )}/" ); ?>">Start Running Tests</a></p>
<?php } ?>
</div>
<?php } else { ?>
<div class="join">
<p>TestSwarm doesn't need your help at this time. If you wish to help run tests you should load up one of the below browsers.</p>
- <p>If you feel that this may be a mistake, copy the following information (<?php echo $swarmBrowser->getBrowserCodename(); ?> <?php echo $swarmBrowser->getBrowserVersion(); ?> <?php echo $swarmBrowser->getOsCodename(); ?>) and your <a href="http://useragentstring.com/">useragent string</a>, and post it to the <a href="//groups.google.com/group/testswarm">discussion group</a>.</a>
+ <p>If you feel that this may be a mistake, copy the following information (<?php echo $bi->getBrowserCodename(); ?> <?php echo $bi->getBrowserVersion(); ?> <?php echo $bi->getOsCodename(); ?>) and your <a href="http://useragentstring.com/">useragent string</a>, and post it to the <a href="//groups.google.com/group/testswarm">discussion group</a>.</a>
</div>
<?php }
View
7 content/run.php
@@ -1,7 +1,10 @@
+<?php
+$bi = $swarmContext->getBrowserInfo();
+?>
<div class="userinfo">
<div class="browser you">
- <img src="<?php echo swarmpath( "images/{$swarmBrowser->getBrowserCodename()}.sm.png" ); ?>" class="browser-icon <?php echo $swarmBrowser->getBrowserCodename(); ?>" alt="<?php echo $swarmBrowser->getSwarmUserAgentName(); ?>" title="<?php echo $swarmBrowser->getSwarmUserAgentName(); ?>"/>
- <span class="browser-name"><?php echo preg_replace('/\w+ /', "", $swarmBrowser->getSwarmUserAgentName()); ?></span>
+ <img src="<?php echo swarmpath( "images/{$bi->getBrowserCodename()}.sm.png" ); ?>" class="browser-icon <?php echo $bi->getBrowserCodename(); ?>" alt="<?php echo $bi->getSwarmUserAgentName(); ?>" title="<?php echo $bi->getSwarmUserAgentName(); ?>"/>
+ <span class="browser-name"><?php echo preg_replace('/\w+ /', "", $bi->getSwarmUserAgentName()); ?></span>
</div>
<h3><?php echo $username; ?></h3>
View
2  content/tinder.php
@@ -98,7 +98,7 @@ function get_status2($num, $fail, $error, $total){
}
- $job_search = preg_replace( "/[^a-zA-Z ]/", "", $swarmRequest->getVal( "job", "" ) );
+ $job_search = preg_replace( "/[^a-zA-Z ]/", "", $swarmContext->getRequest()->getVal( "job", "" ) );
$job_search .= "%";
$search_result = mysql_queryf(
View
55 inc/BrowserInfo.php
@@ -7,8 +7,7 @@
* @package TestSwarm
*/
class BrowserInfo {
-
- protected static $cache = array();
+ private $context;
protected $userAgent = "";
protected $browserCodename;
@@ -19,38 +18,15 @@ class BrowserInfo {
protected $swarmUserAgentName;
/**
+ * @param $context TestSwarmContext
* @param $userAgent string
* @return BrowserInfo
*/
- public static function newFromUA( $userAgent ) {
- // Cached already?
- if ( isset( self::$cache[$userAgent] ) ) {
- return self::$cache[$userAgent];
- }
-
- $bi = new self( $userAgent );
- return self::$cache[$userAgent] = $bi;
- }
-
- /**
- * Get information from the TestSwarm useragents table.
- * @param $bi BrowserInfo
- * @return array|false Database row or false if no matches.
- */
- public static function findSwarmUAFromBI( BrowserInfo $bi ) {
- global $swarmDB;
-
- return $swarmDB->getRow(str_queryf(
- "SELECT
- id,
- name
- FROM
- useragents
- WHERE engine = %s
- AND %s REGEXP version;",
- $bi->getBrowserCodename(),
- $bi->getBrowserVersion()
- ));
+ public static function newFromContext( TestSwarmContext $context, $userAgent ) {
+ $bi = new self();
+ $bi->context = $context;
+ $bi->parseUserAgent( $userAgent );
+ return $bi;
}
/** @return string */
@@ -94,7 +70,17 @@ public function isKnownInTestSwarm() {
}
public function loadSwarmUserAgentData() {
- $uaRow = self::findSwarmUAFromBI( $this );
+ $uaRow = $this->context->getDB()->getRow(str_queryf(
+ "SELECT
+ id,
+ name
+ FROM
+ useragents
+ WHERE engine = %s
+ AND %s REGEXP version;",
+ $this->getBrowserCodename(),
+ $this->getBrowserVersion()
+ ));
if ( $uaRow ) {
$this->swarmUserAgentID = $uaRow->id ? intval( $uaRow->id ) : null;
$this->swarmUserAgentName = $uaRow->name ? (string)$uaRow->name : null;
@@ -107,7 +93,7 @@ public function loadSwarmUserAgentData() {
* Instances may not be created directly, use the static newFromUA method instead
* @param $userAgent string
*/
- private function __construct( $userAgent ) {
+ private function parseUserAgent( $userAgent ) {
$lcUA = strtolower( $userAgent );
// Version
@@ -202,4 +188,7 @@ private function __construct( $userAgent ) {
return $this;
}
+
+ /** Don't allow direct instantiations of this class, use newFromContext instead */
+ private function __construct() {}
}
View
38 inc/Database.php
@@ -7,24 +7,40 @@
* @package TestSwarm
*/
class Database {
+ private $context;
+
protected $host, $username, $password, $dbname;
protected $conn;
protected $isOpen = false;
- public function __construct( $host, $username, $password, $dbname = false ) {
- $this->checkEnvironment();
+ /**
+ * Creates a Database object, opens the connection and returns the instance.
+ *
+ * @param context TestSwarmContext
+ * @param $connType int: [optional]
+ */
- $this->host = $host;
- $this->username = $username;
- $this->password = $password;
- $this->dbname = $dbname;
- return $this;
+ public static function newFromContext( TestSwarmContext $context, $connType = DBCON_DEFAULT ) {
+ $dbConf = $context->getConf()->database;
+ $db = new self();
+
+ $db->context = $context;
+ $db->host = $dbConf->host;
+ $db->username = $dbConf->username;
+ $db->password = $dbConf->password;
+ $db->dbname = $dbConf->database;
+
+ $db->open( $connType );
+
+ return $db;
}
/**
* @param $connType int: DBCON_DEFAULT or DBCON_PERSISTENT.
*/
public function open( $connType = DBCON_DEFAULT ) {
+ $this->close();
+
switch ( $connType ) {
case DBCON_DEFAULT:
$this->conn = mysql_connect( $this->host, $this->username, $this->password, /*force_new=*/true );
@@ -35,9 +51,11 @@ public function open( $connType = DBCON_DEFAULT ) {
default:
throw new SwarmException( "Invalid connection type." );
}
+
if ( !$this->conn ) {
throw new SwarmException( "Connection to {$this->host} failed.\nMySQL Error " . $this->lastErrNo() . ": " . $this->lastErrMsg() );
}
+
if ( $this->dbname ) {
$isOK = mysql_select_db( $this->dbname, $this->conn );
if ( !$isOK ) {
@@ -46,6 +64,7 @@ public function open( $connType = DBCON_DEFAULT ) {
} else {
$isOK = (bool)$this->conn;
}
+
$this->isOpen = $isOK;
return $this;
}
@@ -91,6 +110,7 @@ public function getNumRows( $res ) {
/**
* Queries other than SELECT, such as DELETE, UPDATE and INSERT.
+ * @return resource|false
*/
public function query( $sql ) {
return $this->doQuery( $sql );
@@ -142,4 +162,8 @@ protected function checkEnvironment() {
throw new SwarmException( "MySQL functions missing." );
}
}
+
+ private function __construct() {
+ $this->checkEnvironment();
+ }
}
View
66 inc/TestSwarm.php
@@ -0,0 +1,66 @@
+<?php
+/**
+ * Wrapper class containing various request-specific objects.
+ * Each of these objects is created only once for the context.
+ * The creation happends on-demand and is put in a private cache.
+ *
+ * @author Timo Tijhof, 2012
+ * @since 0.3.0
+ * @package TestSwarm
+ */
+class TestSwarmContext {
+ private $browserInfo, $conf, $db, $request;
+
+ /**
+ * The context is self-initializing. The only thing it
+ * needs to be passed is an array with all setting keys from testswarm.ini
+ * (including ones commented out in the sample file, it has to contain them all)
+ * Population of default values of optional settings happens in init.php
+ * @param $config array
+ */
+ public function __construct( Array $config ) {
+ $conf = new stdClass;
+ foreach ( $config as $key => $val ) {
@staabm
staabm added a note

Does this makes sense? Checking for an array and casting it to an object?

@Krinkle Collaborator
Krinkle added a note

Yes, conf is a 2-level deep object (an object with objects). The variable given is a fresh ini parse, which will be an array of arrays. Casting the main variable to an object will only cast the root level, so I'm looping instead. Although right now all settings are in a subgroup, there may be root settings in the future, hence the check for an array first.

If it's a group, cast the array to an object. Otherwise keep it (a string, number or boolean) as is. See also ./config/testswarm-sample.ini and init.php

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+ $conf->$key = is_array( $val ) ? (object)$val : $val;
+ }
+ $this->conf = $conf;
+ }
+
+ public function getBrowserInfo() {
+ if ( $this->browserInfo === null ) {
+ $ua = isset( $_SERVER["HTTP_USER_AGENT"] ) ? $_SERVER["HTTP_USER_AGENT"] : "";
+ $this->browserInfo = BrowserInfo::newFromContext( $this, $ua );
+ }
+ return $this->browserInfo;
+ }
+
+ /**
+ * Get the configuration object
+ * @return stdClass
+ */
+ public function getConf() {
+ return $this->conf;
+ }
+
+ /**
+ * Get the Database object
+ * @return Database
+ */
+ public function getDB() {
+ if ( $this->db === null ) {
+ $this->db = Database::newFromContext( $this );
+ }
+ return $this->db;
+ }
+
+ /**
+ * Get the WebRequest object
+ * @return WebRequest
+ */
+ public function getRequest() {
+ if ( $this->request === null ) {
+ $this->request = new WebRequest( $this );
@staabm
staabm added a note

Maybe also use a static factory method to be consistent... "newFromContext"

@Krinkle Collaborator
Krinkle added a note

Sounds good.

@Krinkle Collaborator
Krinkle added a note
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+ }
+ return $this->request;
+ }
+}
View
5 inc/WebRequest.php
@@ -11,10 +11,13 @@
*/
class WebRequest {
+ private $context;
+
protected $raw;
private $ip;
- function __construct() {
+ function __construct( TestSwarmContext $context ) {
+ $this->context = $context;
$this->checkMagicQuotes();
// POST overrides GET data
View
39 inc/init-usersession.php
@@ -2,7 +2,8 @@
/**
* Initialize global variables related to a user,
* for requests that require a username.
- * Sets the following globals:
+ *
+ * @todo Deprecate these globals:
* - $username
* - $user_id
* - $client_id
@@ -10,9 +11,13 @@
* @since 0.1.0
* @package TestSwarm
*/
- global $swarmBrowser, $swarmDB, $swarmRequest;
+ global $swarmContext;
+
+ $bi = $swarmContext->getBrowserInfo();
+ $db = $swarmContext->getDB();
+ $request = $swarmContext->getRequest();
- $username = $swarmRequest->getSessionData( "username", $swarmRequest->getVal( "user" ) );
+ $username = $request->getSessionData( "username", $request->getVal( "user" ) );
if ( !$username ) {
$username = $_REQUEST["user"];
}
@@ -27,13 +32,13 @@
exit( "Username required. ?user=USERNAME." );
}
- $client_id = preg_replace( "/[^0-9]/", "", $swarmRequest->getVal( "client_id" ) );
+ $client_id = preg_replace( "/[^0-9]/", "", $request->getVal( "client_id" ) );
// Client passed
if ( $client_id ) {
// Verify that the client exists,
// And get the user ID.
- $user_id = $swarmDB->getOne(str_queryf(
+ $user_id = $db->getOne(str_queryf(
"SELECT
user_id
FROM
@@ -46,7 +51,7 @@
if ( $user_id ) {
// If the client ID is already provided, update its record so
// that we know that it's still alive
- $swarmDB->query(str_queryf(
+ $db->query(str_queryf(
"UPDATE clients SET updated=%s WHERE id=%u LIMIT 1;",
swarmdb_dateformat( SWARM_NOW ),
$client_id
@@ -62,37 +67,37 @@
} else {
// If the useragent isn't known, abort with an error message
- if ( !$swarmBrowser->isKnownInTestSwarm() ) {
+ if ( !$bi->isKnownInTestSwarm() ) {
echo "Your browser is not supported for testing right now.\n"
- . "Browser: {$swarmBrowser->getBrowserCodename()} Version: {$swarmBrowser->getBrowserVersion()}";
+ . "Browser: {$bi->getBrowserCodename()} Version: {$bi->getBrowserVersion()}";
exit;
}
// Figure out what the user's ID number is
- $user_id = $swarmDB->getOne(str_queryf( "SELECT id FROM users WHERE name=%s;", $username ));
+ $user_id = $db->getOne(str_queryf( "SELECT id FROM users WHERE name=%s;", $username ));
// If the user doesn't have one, create a new user account
if ( !$user_id ) {
- $swarmDB->query(str_queryf(
+ $db->query(str_queryf(
"INSERT INTO users (name, created, updated, seed) VALUES(%s, %s, %s, RAND());",
$username,
swarmdb_dateformat( SWARM_NOW ),
swarmdb_dateformat( SWARM_NOW )
));
- $user_id = $swarmDB->getInsertId();
+ $user_id = $db->getInsertId();
}
// Insert in a new record for the client and get its ID
- $swarmDB->query(str_queryf(
+ $db->query(str_queryf(
"INSERT INTO clients (user_id, useragent_id, useragent, os, ip, created)
VALUES(%u, %u, %s, %s, %s, %s);",
$user_id,
- $swarmBrowser->getSwarmUserAgentID(),
- $swarmBrowser->getRawUA(),
- $swarmBrowser->getOsCodename(),
- $swarmRequest->getIP(),
+ $bi->getSwarmUserAgentID(),
+ $bi->getRawUA(),
+ $bi->getOsCodename(),
+ $request->getIP(),
swarmdb_dateformat( SWARM_NOW )
));
- $client_id = $swarmDB->getInsertId();
+ $client_id = $db->getInsertId();
}
View
39 inc/init.php
@@ -16,14 +16,16 @@
// Defines
define( 'SWARM_NOW', 0 );
-
define( 'DBCON_DEFAULT', 10 );
define( 'DBCON_PERSISTENT', 11 );
-// Global requirements
+// Load classes
require_once "inc/BrowserInfo.php";
require_once "inc/Database.php";
+require_once "inc/TestSwarm.php";
require_once "inc/WebRequest.php";
+
+// Other requirements
require_once "inc/utilities.php";
@@ -87,15 +89,24 @@
/**
+ * Context
+ * @{
+ */
+$swarmContext = new TestSwarmContext( $swarmConfig );
+
+/**@}*/
+
+
+/**
* Debugging
* @{
*/
function swarmExceptionHandler( Exception $e ) {
- global $swarmConfig;
+ global $swarmContext;
$msg = "<h2>TestSwarm internal error</h2>\n\n";
- if ( $swarmConfig["debug"]["show_exception_details"] ) {
+ if ( $swarmContext->getConf()->debug->show_exception_details ) {
$msg .=
'<p>' . nl2br( htmlspecialchars( $e->getMessage() ) ) .
'</p><p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $e->getTraceAsString() ) ) .
@@ -116,7 +127,7 @@ function swarmExceptionHandler( Exception $e ) {
set_exception_handler( "swarmExceptionHandler" );
-if ( $swarmConfig["debug"]["php_error_reporting"] ) {
+if ( $swarmContext->getConf()->debug->php_error_reporting ) {
error_reporting( E_ALL );
ini_set( "display_errors", 1 );
}
@@ -125,21 +136,6 @@ function swarmExceptionHandler( Exception $e ) {
/**
- * Database
- * @{
- */
-$swarmDB = new Database(
- $swarmConfig["database"]["host"],
- $swarmConfig["database"]["username"],
- $swarmConfig["database"]["password"],
- $swarmConfig["database"]["database"]
-);
-$swarmDB->open( DBCON_PERSISTENT );
-
-/**@}*/
-
-
-/**
* Session
* @{
*/
@@ -149,7 +145,4 @@ function swarmExceptionHandler( Exception $e ) {
// Increase the session timeout to two weeks (3600 * 24 * 14)
ini_set( 'session.gc_maxlifetime', '1209600' );
-$swarmRequest = new WebRequest();
-
/**@}*/
-
View
11 inc/utilities.php
@@ -40,10 +40,12 @@ function array_extend( $arr1, $arr2 ) {
* @source php.net/mysql-query#86447
*/
function mysql_queryf(/* $string, $arg, .. */) {
+ global $swarmContext;
+
$args = func_get_args();
$sql_query = call_user_func_array( 'str_queryf', $args );
- $result = mysql_query( $sql_query );
+ $result = $swarmContext->getDB()->query( $sql_query );
if (!$result) {
echo "Invalid query: " . mysql_error();
exit;
@@ -137,14 +139,14 @@ function swarmdb_dateformat( $timestamp = 0 ) {
* @return string Relative path from the domain root to the specified file or directory
*/
function swarmpath( $rel ) {
- global $swarmConfig;
+ global $swarmContext;
// Only normalize the contextpath once
static $contextpath;
if ( is_null( $contextpath ) ) {
// Add trailing slash if it's missing
- $path = $swarmConfig["web"]["contextpath"];
+ $path = $swarmContext->getConf()->web->contextpath;
if ( substr( $path, -1 ) !== '/' ) {
$path = "$path/";
}
@@ -156,7 +158,8 @@ function swarmpath( $rel ) {
$path = "/$path";
}
- $swarmConfig["web"]["contextpath"] = $path;
+ // Update it (just in case it's used elsewhere)
+ $swarmContext->getConf()->web->contextpath = $path;
}
// Just in case, strip the leading slash
View
12 index.php
@@ -12,9 +12,7 @@
require_once "inc/init.php";
-$swarmBrowser = BrowserInfo::newFromUA( isset( $_SERVER["HTTP_USER_AGENT"] ) ? $_SERVER["HTTP_USER_AGENT"] : "" );
-
-$state = preg_replace("/[^a-z]/", "", $swarmRequest->getVal( "state", "" ) );
+$state = preg_replace("/[^a-z]/", "", $swarmContext->getRequest()->getVal( "state", "" ) );
if ( !$state ) {
$state = "home";
@@ -40,15 +38,15 @@
<head>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
- <title><?php echo htmlentities( $swarmConfig['web']['title'] . ': ' . $title ); ?></title>
+ <title><?php echo htmlentities( $swarmContext->getConf()->web->title . ': ' . $title ); ?></title>
<link rel="stylesheet" href="<?php echo swarmpath( "css/site.css" ); ?>"/>
<script>window.SWARM = <?php echo json_encode( array(
- // Derived version of $swarmConfig for the browser
- // (not the entire array since it also contains DB passwords!)
+ // Export a simplified version of the TestSwarm configuration object to the browser
+ // (not the entire object since it also contains DB password and such..).
"web" => array(
"contextpath" => swarmpath( "" ),
),
- "client" => $swarmConfig["client"],
+ "client" => $swarmContext->getConf()->client,
) ); ?>;</script>
<?php
echo isset( $scripts ) ? "\t" . $scripts . "\n" : "";
View
8 logic/addjob.php
@@ -2,12 +2,14 @@
$title = "Add New Job";
- if ( $swarmRequest->getVal( "state" ) !== "addjob" || !$swarmRequest->hasKeys( "user", "auth", "job_name" ) ) {
+ $request = $swarmContext->getRequest();
+
+ if ( $request->getVal( "state" ) !== "addjob" || !$request->hasKeys( "user", "auth", "job_name" ) ) {
return;
}
- $username = $swarmRequest->getVal( "user", "" );
- $auth = $swarmRequest->getVal( "auth", "" );
+ $username = $request->getVal( "user", "" );
+ $auth = $request->getVal( "auth", "" );
$user_id = null;
$result = mysql_queryf("SELECT id FROM users WHERE name=%s AND auth=%s;", $username, $auth);
View
10 logic/getrun.php
@@ -1,7 +1,9 @@
<?php
require "inc/init-usersession.php";
- global $swarmConfig;
+ global $swarmContext;
+
+ $bi = $swarmContext->getBrowserInfo();
$result = mysql_queryf(
"SELECT
@@ -13,7 +15,7 @@
AND NOT EXISTS (SELECT 1 FROM run_client WHERE run_useragent.run_id = run_id AND client_id = %u)
ORDER BY run_id DESC
LIMIT 1;",
- $swarmBrowser->getSwarmUserAgentID(),
+ $bi->getSwarmUserAgentID(),
$client_id
);
@@ -45,7 +47,7 @@
mysql_queryf(
"UPDATE run_useragent SET runs = runs + 1, status = 1 WHERE run_id=%u AND useragent_id=%u LIMIT 1;",
$run_id,
- $swarmBrowser->getSwarmUserAgentID()
+ $bi->getSwarmUserAgentID()
);
# Initialize the client run
@@ -66,7 +68,7 @@
}
echo json_encode( array(
- "swarmUpdate" => array( "client" => $swarmConfig["client"] ),
+ "swarmUpdate" => array( "client" => $swarmContext->getConf()->client ),
"runInfo" => $runInfo,
) );
View
8 logic/login.php
@@ -1,17 +1,19 @@
<?php
$title = "Login";
+ $request = $swarmContext->getRequest();
+
if ( isset( $_SESSION["username"] ) && isset( $_SESSION["auth"] ) && $_SESSION["auth"] == "yes" ) {
$username = $_SESSION["username"];
header("Location: " . swarmpath( "user/$username/" ) );
exit;
}
- $username = preg_replace("/[^a-zA-Z0-9_ -]/", "", $swarmRequest->getVal( "username" ) );
- $password = $swarmRequest->getVal( "password" );
+ $username = preg_replace("/[^a-zA-Z0-9_ -]/", "", $request->getVal( "username" ) );
+ $password = $request->getVal( "password" );
$error = "";
- if ( $swarmRequest->wasPosted() && $username && $password ) {
+ if ( $request->wasPosted() && $username && $password ) {
$result = mysql_queryf(
"SELECT id
View
6 logic/run.php
@@ -1,9 +1,11 @@
<?php
require "inc/init-usersession.php";
- $user = $swarmRequest->getVal( "username", $swarmRequest->getSessionData( "username" ) );
+ $request = $swarmContext->getRequest();
- if ( !$swarmRequest->getVal( "user" ) && $user ) {
+ $user = $request->getVal( "username", $request->getSessionData( "username" ) );
+
+ if ( !$request->getVal( "user" ) && $user ) {
header("Location: " . swarmpath( "run/$user/" ) );
exit;
}
View
23 logic/saverun.php
@@ -1,13 +1,16 @@
<?php
require "inc/init-usersession.php";
- if ( $swarmRequest->wasPosted() ) {
- $run_id = preg_replace( "/[^0-9]/", "", $swarmRequest->getVal( "run_id", "" ) );
- $fail = preg_replace( "/[^0-9-]/", "", $swarmRequest->getVal( "fail", "" ) );
- $error = preg_replace( "/[^0-9-]/", "", $swarmRequest->getVal( "error", "" ) );
- $total = preg_replace( "/[^0-9-]/", "", $swarmRequest->getVal( "total", "" ) );
+ $bi = $swarmContext->getBrowserInfo();
+ $request = $swarmContext->getRequest();
- $results = gzencode( $swarmRequest->getVal( "results", "" ) );
+ if ( $request->wasPosted() ) {
+ $run_id = preg_replace( "/[^0-9]/", "", $request->getVal( "run_id", "" ) );
+ $fail = preg_replace( "/[^0-9-]/", "", $request->getVal( "fail", "" ) );
+ $error = preg_replace( "/[^0-9-]/", "", $request->getVal( "error", "" ) );
+ $total = preg_replace( "/[^0-9-]/", "", $request->getVal( "total", "" ) );
+
+ $results = gzencode( $request->getVal( "results", "" ) );
} else {
$results = false;
}
@@ -49,7 +52,7 @@
AND clients.useragent_id = %u;",
$run_id,
$client_id,
- $swarmBrowser->getSwarmUserAgentID()
+ $bi->getSwarmUserAgentID()
);
while ( $row = mysql_fetch_array($result) ) {
@@ -66,7 +69,7 @@
WHERE useragent_id = %u
AND run_id = %u
LIMIT 1;",
- $swarmBrowser->getSwarmUserAgentID(),
+ $bi->getSwarmUserAgentID(),
$run_id
);
} else {
@@ -84,7 +87,7 @@
AND clients.useragent_id = %u;",
$run_id,
$client_id,
- $swarmBrowser->getSwarmUserAgentID()
+ $bi->getSwarmUserAgentID()
);
while ( $row = mysql_fetch_array($result) ) {
@@ -105,7 +108,7 @@
WHERE useragent_id = %u
AND run_id = %u
LIMIT 1;",
- $swarmBrowser->getSwarmUserAgentID(),
+ $bi->getSwarmUserAgentID(),
$run_id
);
}
View
12 logic/signup.php
@@ -1,15 +1,17 @@
<?php
$title = "Signup";
- if ( !$swarmRequest->wasPosted() ) {
+ $request = $swarmContext->getRequest();
+
+ if ( !$request->wasPosted() ) {
return;
)
- $username = preg_replace("/[^a-zA-Z0-9_ -]/", "", $swarmRequest->getVal( "username", false ) );
- $password = $swarmRequest->getVal( "password", false );
+ $username = preg_replace("/[^a-zA-Z0-9_ -]/", "", $request->getVal( "username", false ) );
+ $password = $request->getVal( "password", false );
- $email = $swarmRequest->getVal( "email" );
- $request = $swarmRequest->getVal( "request" );
+ $email = $request->getVal( "email" );
+ $request = $request->getVal( "request" );
$error = "";
if ( !$username || !$password ) {
View
2  logic/tinder.php
@@ -1,6 +1,6 @@
<?php
- $search_user = preg_replace( "/[^a-zA-Z0-9_ -]/", "", $swarmRequest->getVal( "user" ) );
+ $search_user = preg_replace( "/[^a-zA-Z0-9_ -]/", "", $swarmContext->getRequest()->getVal( "user" ) );
$title = "$search_user";
$scripts =
Something went wrong with that request. Please try again.