Code modules

Code modules

Here we collect code modules to form a library for LIONESS users to draw from.

We welcome any contributions to this library. Please send your code to lucas.molleman@nottingham.ac.uk and add ONE LINE to describe what the code aims to do. Please do provide extensive in-line annotation with your code to make its functioning as clear as possible.

Many of the script modules below make use of SQLlibrary.sql[add link], which is based on a library developed by Joep Sonnemans (CREED, University of Amsterdam). This library provides some functions facilitating reading from and writing to the database.

 

1. Preventing participants from navigating back

<head>
<script>
window.history.forward();
function noBack() { window.history.forward(); }
</script>
</head>
<body onload="secondPassed(); noBack();" onpageshow="if (event.persisted) noBack();">

2. Sending a ‘heartbeat’ to the server to signal that the client is still connected

function clientConnected()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
// write the time to the database (to make sure the client is still connected)
xmlhttp.open("POST","clientConnected.php?ppnr="+<?php echo $ppnr;?>,true);
xmlhttp.send();
}
</script>

3a. Log the participant’s IP address

<?php

$ipaddress = getenv('HTTP_CLIENT_IP')?:
getenv('HTTP_X_FORWARDED_FOR')?:
getenv('HTTP_X_FORWARDED')?:
getenv('HTTP_FORWARDED_FOR')?:
getenv('HTTP_FORWARDED')?:
getenv('REMOTE_ADDR');

?>

3b. Redirect participant when his/her device is already logged in to the server

<?php

// check if this IP has already present logged in (preventing double log-ins)
$table_name="ppnumbers";
$connection = @mysql_connect(HOST,ADMIN, WWOORD) or die(mysql_error());
$db = @mysql_select_db(DBNAME,$connection)or die(mysql_error());
$sql="SELECT * FROM $table_name";
$result=@mysql_query($sql,$connection) or die("Couldn't execute query ".$sql);
$IParray = [];
while($row = mysql_fetch_array($result))
{
$IParray[]=$row['ipaddress'];
}

if (in_array($ipaddress, $IParray))
{
header("Location: devicePresent.html");
exit();
}

?>

4. Remove clients that attempt to watch a page without having logged in


<?php

if (!$_COOKIE['clientcookie'])
{
header("Location: notloggedin.html");
exit();
}

 

?>

5. Manually remove participants

Define a variable in the ‘subjects’ table called expTerminated. Include the following code into each page of the experiment:


<?php

$expTerminated=lookUp("ppnumbers","ppnr='$ppnr'","expTerminated");
if ($expTerminated == '1')
{
header("Location: experimentTerminated.php");
exit();
}

?>

If you want to remove clients from the experiment (and send them to an exit page ‘experimentTerminated.php’, you can manually set the variable expTerminated to 1. You can do this via adminer.php, but it is even easier using a client termination page that you can access via the control panel.

 

6. Prevent participants from overwriting their decisions

 

Before writing a record into the database, it is often helpful to check whether this participant has already submitted a decision in this period.

$playerNr=readcookie("clientcookie")[0];
$check=lookUp("decisions","period='$period' and playerNr='$playerNr'","contribution");
if ($check=="")
{
// write entry to server
insertRecord();
}


7a Moving on to the next page once an entry has been submitted to the server

if (isset($_REQUEST['OK']))
{

header("Location: nextPage.php");
exit();

}


7b. Conditional moving on to the next page


if (isset($_REQUEST['OK']))
{
$treatment = lookUp("subjects", "playerNr='$playerNr',"treatment");
if ($treatment==1)
{
header("Location: nextPageTreatment1.php");
exit();
}

if ($treatment==2)
{
header("Location: nextPageTreatment2php");
exit();
}

}


8. Use jQuery to display an alert box that does not block execution of scripts


//load jQuery

<link rel="stylesheet" href="//code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script src="//code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">

// define warning message

<div id="dialog-message" title="Invalid entry" style="display: none;">
<p> Invalid entry!</p>
</div>

// show the message when necessary (JavaScript)

function confirm_entry()
{
var val=document.forms["form1"].contribution.value;
if (val==null || val=="" || isNaN(val) || val<0 || val>20)
{
// window.location.assign('wrong_entry.php');
$(function() {
$( "#dialog-message" ).dialog({
modal: true,
buttons: {
Ok: function() {
$( this ).dialog( "close" );
}
}
});
});
return false;

<html>

<form align=center name="form1" method="post" onsubmit='return confirm_entry(this);' >

 

Your contribution to the group project:

<input name="contribution">
<button type="submit">OK</button>

</form>


9. A timer (that turns red when only 10 seconds are left)

// script for countdown timer
var seconds = <?php echo $timerStart - time() + $timeoutDecision; ?>;
function secondPassed()
{
clientConnected();
var remainingSeconds = seconds;
document.getElementById('countdown').innerHTML = "Remaining time: " + remainingSeconds;
if (seconds == 0)
{
clearInterval(countdownTimer);
// document.getElementById('countdown').innerHTML = "<b><font color='red' size='5'>Please make your decision now!</b>";
window.onbeforeunload=null;
window.location="experimentTimedOut.php";
}
else
{
seconds--;
}
if (seconds < 10)
{
document.getElementById('countdown').setAttribute("style", "color: red; font-size:22; font-family:serif font-size : 22; border:2px solid #a1a1a1; border-radius:10px; width:250px; height:60px; padding:5px; ");
}
}
var countdownTimer = setInterval('secondPassed()', 1000);


10. Retrieve all entries in a group with PHP (using an SQL query)

// read from the database how many others from this group are ready
$qry = "SELECT decisionOK FROM decisions WHERE groupNr=" . $groupNr . " AND period=" . $period;
$result = mysql_query($qry);
$decOK=[];
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$decOK[] = $row['decisionOK'];
}
//we look up whether the partners have made a decision in this period
$sumDone = array_sum($decOK);


11. Proceed to the next screen when all group members have submitted their decisions


$numberPlayersInGroup=readParameter('groupSize');

// read from the database how many others from this group are ready
$qry = "SELECT decisionOK FROM decisions WHERE groupNr=" . $groupNr . " AND period=" . $period;
$result = mysql_query($qry);
$decOK=[];
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$decOK[] = $row['decisionOK'];
}
//we look up whether the partners have made a decision in this period
$sumDone = array_sum($decOK);

// if all players in the group have made their decision in this period, we go on to the results screen
if ($sumDone == $numberPlayersInGroup)
{
header("Location: results.php");
exit();
}


12. Generate an HTML table with JavaScript