Skip to content

Instantly share code, notes, and snippets.

@macroxela
Created October 8, 2015 00:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save macroxela/701ab9b7a8e62260ac5e to your computer and use it in GitHub Desktop.
Save macroxela/701ab9b7a8e62260ac5e to your computer and use it in GitHub Desktop.
A Javascript code editor with teacher version and student version. Allows user to write Javascript code to solve a certain problem which the site then runs and states whether it is the correct solution or not. Developed in team of 2.
<?
require_once( "db.php" );
require_once( "User.php" );
$username = $_GET['username'];
if( $username )
{
if( User::duplicate_username( $username, $dbh ) ) {
print 1;
exit();
}
}
print 0;
?>
<?php
require_once( "db.php" );
require_once( "session.php" );
// if logged in, get out of here
if( $user ) {
header( "Location: home.php" );
exit();
}
$newuser = new User();
if( $_POST && $_POST['enroll'] )
{
$newuser->load_from_post( $_POST );
if( $newuser->validate( $dbh ) ) {
$newuser->save( $dbh );
}
}
?>
<html>
<head>
<title>Enroll</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<? include( "header.php" ); ?>
<div class="floatbox">
<? if( $newuser->dirty ) { ?>
<h2>Create a New Account</h2>
<form method="POST" action="enroll.php">
<table border="0">
<tr><td>Username:</td><td><input type="text" name="username" value="<?=$newuser->user?>">
<? if( $newuser->hasUsernameError() ) { ?>
<div class="error"><?=$newuser->usernameError?></div>
<? } ?>
</td></tr>
<tr><td>Password:</td><td><input type="password" name="password"></td></tr>
<tr><td>Re-type password:</td><td><input type="password" name="password2">
<? if( $newuser->hasPasswordError() ) { ?>
<div class="error"><?=$newuser->passwordError?></div>
<? } ?>
</td></tr>
<tr><td></td><td><hr></td></tr>
<tr><td>First Name:</td><td><input type="text" name="first_name" value="<?=$newuser->fname?>"></td></tr>
<tr><td>Last Name:</td><td><input type="text" name="last_name" value="<?=$newuser->lname?>"></td></tr>
<tr><td>Email Address:</td><td><input type="text" name="email" value="<?=$newuser->email?>">
<? if( $newuser->hasEmailError() ) { ?>
<div class="error"><?=$newuser->emailError?></div>
<? } ?>
</td></tr>
<tr><td></td><td><input type="submit" value="Create Account" name="enroll"></td></tr>
</table>
</form>
<? } else { ?>
<h2>Account created!</h2>
<div>Please log in</div>
<? } ?>
</div>
</body>
</html>
<? require_once( "User.php" ); ?>
<div class="header">
<?
if( $user ) {
// either already logged in or just did
?>
<div>Welcome, <?=$user->user?>!</div>
<div><a href="logout.php">Logout</a></div>
<?
} else {
// either just got here or failed to log in
?>
<form method="POST">
<div class="login">
<div>
Username: <input type="text" name="username" value="<?=$login->user?>">
Password: <input type="password" name="password">
<input type="submit" value="Login" name="login">
</div>
<div>
<span class="error"><?=$login->loginError?></span>
&nbsp;&nbsp;&nbsp;&nbsp;
<span>No account? <a href="enroll.php">Enroll</a> now!</span>
</div>
</div>
</form>
<? } ?>
</div>
<?
require_once( "db.php" );
require_once( "session.php" );
?>
<html>
<head>
<title>Home</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<? include( "header.php" ); ?>
<h1>Home Page</h1>
<? if( $user ) { ?>
<?if($user->user == "account")
{?>
<div><a href="teacherindex.php">A link for the teacher</a></div>
<?}?>
<a href = "index.php">Problem Sets</a>
<? } ?>
</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Assignments</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script src="run.js"></script>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<h1>Assignments</h1>
<p>Solve the following problem using <span>Javascript.</span>
Once you have solved the problem, type it in the given
box and the code will be executed. It will be tested with different
inputs to make sure it runs correctly. If your code is not
correct you can modify it and try again.</p>
<hr />
<span id="number" >Problem #1: </span>
<p id="problem">Write the solution to find
the factorial of any given number.</p>
<p id="warning">Please type solution, then click submit</p>
<hr />
<p>function f(x) {</p>
<textarea class="text" id="solution" name="solution" ></textarea>
<button id="submit" type="button" >Submit</button>
<p>}</p>
<hr />
<p id="test1"></p>
<p id="test2"></p>
<p id="test3"></p>
<p id="test4"></p>
<br/><br/><br/><br/>
</body>
</html>
<?
require_once( "db.php" );
require_once( "session.php" );
$stmt = $dbh->prepare("select * from questions");
$stmt ->execute();
/*
if($_POST)
{*/
$tst = $dbh->prepare("SELECT id FROM users WHERE username = :us");
$tst->bindParam(":us",$user->user);
$tst->execute();
$val = $tst->fetch();
$qry = $dbh->prepare("SELECT distinct(quest_id) FROM results WHERE u_id = :k");
$qry->bindParam(":k",$val['id']);
$qry->execute();
//}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Assignments</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script src="run.js"></script>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<? include( "header.php" ); ?>
<? if( $user ) { ?>
<div><a href="admin.php">A link for logged in people</a></div>
<? } ?>
<h1>Assignments</h1>
<p>Solve the following problem using <span>Javascript.</span>
Once you have solved the problem, type it in the given
box and the code will be executed. It will be tested with different
inputs to make sure it runs correctly. If your code is not
correct you can modify it and try again.</p>
<hr />
<select id="q_id" class="problem" >
<?while( $row = $stmt->fetch() ) { ?>
<option value = "<?=$row['ID']?>" > <span id="number" >Problem #<?=$row['ID']?>: </span> <?=$row['text']?></option>
<?}?>
</select>
<p id="warning">Please type solution, then click submit</p>
<hr />
<p>function f(x) {</p>
<textarea class="text" id="solution" name="solution" ></textarea>
<form> <input type = "hidden" value="<?=$user->user?>" id = "user" /> </form>
<button id="submit" type="button" >Submit</button>
<p>}</p>
<hr />
<p id="test1"></p>
<p id="test2"></p>
<p id="test3"></p>
<p id="test4"></p>
<hr />
Attempted Questions:<br>
<?
while($try = $qry->fetch())
{
print "Question ".$try['quest_id']."<br>";
}
?>
<br/><br/><br/><br/>
</body>
</html>
<?
require_once("db.php");
//http://red1.cs.panam.edu/3342/amarroquin1/blob/login.php?username=test&pass=test_pass
try
{
if($_GET)
{
$us = trim($_GET["username"]);
$p = trim($_GET["pass"]);
$stmt2 = $dbh->prepare("SELECT u_Id as id FROM users WHERE username LIKE :lts AND password LIKE :ps");
$stmt2->bindParam( ':lts', $us );
$stmt2->bindParam( ':ps', $p );
$stmt2->execute();
/*header( "Content-type: text/xml" );
print "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
print "<data>";*/
if($rows = $stmt2->fetch())
{
print $rows["id"]."<br>";
}
else
{
print 0;
}
}
}
catch(PDOException $e)
{
print $e->getMessage();
die();
}
?>
<?php
session_start();
session_destroy();
header( "Location: home.php" );
?>
<?php
#
# Portable PHP password hashing framework.
#
# Version 0.3 / genuine.
#
# Written by Solar Designer <solar at openwall.com> in 2004-2006 and placed in
# the public domain. Revised in subsequent years, still public domain.
#
# There's absolutely no warranty.
#
# The homepage URL for this framework is:
#
# http://www.openwall.com/phpass/
#
# Please be sure to update the Version line if you edit this file in any way.
# It is suggested that you leave the main version number intact, but indicate
# your project name (after the slash) and add your own revision information.
#
# Please do not change the "private" password hashing method implemented in
# here, thereby making your hashes incompatible. However, if you must, please
# change the hash type identifier (the "$P$") to something different.
#
# Obviously, since this code is in the public domain, the above are not
# requirements (there can be none), but merely suggestions.
#
class PasswordHash {
var $itoa64;
var $iteration_count_log2;
var $portable_hashes;
var $random_state;
function PasswordHash($iteration_count_log2, $portable_hashes)
{
$this->itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
if ($iteration_count_log2 < 4 || $iteration_count_log2 > 31)
$iteration_count_log2 = 8;
$this->iteration_count_log2 = $iteration_count_log2;
$this->portable_hashes = $portable_hashes;
$this->random_state = microtime();
if (function_exists('getmypid'))
$this->random_state .= getmypid();
}
function get_random_bytes($count)
{
$output = '';
if (is_readable('/dev/urandom') &&
($fh = @fopen('/dev/urandom', 'rb'))) {
$output = fread($fh, $count);
fclose($fh);
}
if (strlen($output) < $count) {
$output = '';
for ($i = 0; $i < $count; $i += 16) {
$this->random_state =
md5(microtime() . $this->random_state);
$output .=
pack('H*', md5($this->random_state));
}
$output = substr($output, 0, $count);
}
return $output;
}
function encode64($input, $count)
{
$output = '';
$i = 0;
do {
$value = ord($input[$i++]);
$output .= $this->itoa64[$value & 0x3f];
if ($i < $count)
$value |= ord($input[$i]) << 8;
$output .= $this->itoa64[($value >> 6) & 0x3f];
if ($i++ >= $count)
break;
if ($i < $count)
$value |= ord($input[$i]) << 16;
$output .= $this->itoa64[($value >> 12) & 0x3f];
if ($i++ >= $count)
break;
$output .= $this->itoa64[($value >> 18) & 0x3f];
} while ($i < $count);
return $output;
}
function gensalt_private($input)
{
$output = '$P$';
$output .= $this->itoa64[min($this->iteration_count_log2 +
((PHP_VERSION >= '5') ? 5 : 3), 30)];
$output .= $this->encode64($input, 6);
return $output;
}
function crypt_private($password, $setting)
{
$output = '*0';
if (substr($setting, 0, 2) == $output)
$output = '*1';
$id = substr($setting, 0, 3);
# We use "$P$", phpBB3 uses "$H$" for the same thing
if ($id != '$P$' && $id != '$H$')
return $output;
$count_log2 = strpos($this->itoa64, $setting[3]);
if ($count_log2 < 7 || $count_log2 > 30)
return $output;
$count = 1 << $count_log2;
$salt = substr($setting, 4, 8);
if (strlen($salt) != 8)
return $output;
# We're kind of forced to use MD5 here since it's the only
# cryptographic primitive available in all versions of PHP
# currently in use. To implement our own low-level crypto
# in PHP would result in much worse performance and
# consequently in lower iteration counts and hashes that are
# quicker to crack (by non-PHP code).
if (PHP_VERSION >= '5') {
$hash = md5($salt . $password, TRUE);
do {
$hash = md5($hash . $password, TRUE);
} while (--$count);
} else {
$hash = pack('H*', md5($salt . $password));
do {
$hash = pack('H*', md5($hash . $password));
} while (--$count);
}
$output = substr($setting, 0, 12);
$output .= $this->encode64($hash, 16);
return $output;
}
function gensalt_extended($input)
{
$count_log2 = min($this->iteration_count_log2 + 8, 24);
# This should be odd to not reveal weak DES keys, and the
# maximum valid value is (2**24 - 1) which is odd anyway.
$count = (1 << $count_log2) - 1;
$output = '_';
$output .= $this->itoa64[$count & 0x3f];
$output .= $this->itoa64[($count >> 6) & 0x3f];
$output .= $this->itoa64[($count >> 12) & 0x3f];
$output .= $this->itoa64[($count >> 18) & 0x3f];
$output .= $this->encode64($input, 3);
return $output;
}
function gensalt_blowfish($input)
{
# This one needs to use a different order of characters and a
# different encoding scheme from the one in encode64() above.
# We care because the last character in our encoded string will
# only represent 2 bits. While two known implementations of
# bcrypt will happily accept and correct a salt string which
# has the 4 unused bits set to non-zero, we do not want to take
# chances and we also do not want to waste an additional byte
# of entropy.
$itoa64 = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$output = '$2a$';
$output .= chr(ord('0') + $this->iteration_count_log2 / 10);
$output .= chr(ord('0') + $this->iteration_count_log2 % 10);
$output .= '$';
$i = 0;
do {
$c1 = ord($input[$i++]);
$output .= $itoa64[$c1 >> 2];
$c1 = ($c1 & 0x03) << 4;
if ($i >= 16) {
$output .= $itoa64[$c1];
break;
}
$c2 = ord($input[$i++]);
$c1 |= $c2 >> 4;
$output .= $itoa64[$c1];
$c1 = ($c2 & 0x0f) << 2;
$c2 = ord($input[$i++]);
$c1 |= $c2 >> 6;
$output .= $itoa64[$c1];
$output .= $itoa64[$c2 & 0x3f];
} while (1);
return $output;
}
function HashPassword($password)
{
$random = '';
if (CRYPT_BLOWFISH == 1 && !$this->portable_hashes) {
$random = $this->get_random_bytes(16);
$hash =
crypt($password, $this->gensalt_blowfish($random));
if (strlen($hash) == 60)
return $hash;
}
if (CRYPT_EXT_DES == 1 && !$this->portable_hashes) {
if (strlen($random) < 3)
$random = $this->get_random_bytes(3);
$hash =
crypt($password, $this->gensalt_extended($random));
if (strlen($hash) == 20)
return $hash;
}
if (strlen($random) < 6)
$random = $this->get_random_bytes(6);
$hash =
$this->crypt_private($password,
$this->gensalt_private($random));
if (strlen($hash) == 34)
return $hash;
# Returning '*' on error is safe here, but would _not_ be safe
# in a crypt(3)-like function used _both_ for generating new
# hashes and for validating passwords against existing hashes.
return '*';
}
function CheckPassword($password, $stored_hash)
{
$hash = $this->crypt_private($password, $stored_hash);
if ($hash[0] == '*')
$hash = crypt($password, $stored_hash);
return $hash == $stored_hash;
}
}
?>
<?
require_once( "User.php" );
session_start();
$user = $_SESSION['user'];
// handle login post
$login = new User();
if( $_POST && $_POST['login'] ) {
if( $login->login( $_POST['username'], $_POST['password'], $dbh ) ) {
// logged in! set $user var and store in session
$user = $login;
$_SESSION['user'] = $user;
}
}
?>
@charset "utf-8";
/* CSS Document */
body
{background-color:#C2C2D6;}
h1
{color:#007A29;}
h3
{color:blue;}
p
{
width:600px;
font-family:"Serif";
font-size:18px;
}
p#problem
{
font-size:22px;
}
span
{
font-size:22px;
color:#7A0000;
text-decoration:underline;
}
p#warning
{
display:none;
color:red;
font-size:14px;
}
p.func
{
width:150px;
font-family:"Serif";
font-size:18px;
color:blue;
}
textarea.text
{
width: 500px;
height: 250px;
}
textarea#solution
{
position:relative;
left:20px;
}
#submit
{
width:100px;
height:25px;
position:relative;
top:20px;
left:20px;
}
p#tested
{
background-color:#D8D8E6;
display:none;
position:relative;
left:20px;
top:30px;
}
.floatbox
{
border-style: solid;
border-width: 1px;
margin-top: 100px;
margin-left: 100px;
padding: 10px;
display: inline-block;
}
.error
{
color: red;
font-style: italic;
}
.header
{
font-size: 10pt;
background-color: darkgrey;
margin: 0px;
padding: 5px;
color: white;
text-align: right;
border-style: solid;
border-color: black;
border-width: 1px;
}
.login
{
text-align: right;
}
in, go back home
if( !$user ) {
header( "Location: home.php" );
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Assignments</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script src="teacher.js"></script>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<h3>View students' answers</h3>
<form>
<p id="warning" >Type students' user name or question id or both.</p>
<p>Students' user name</p>
<input type="text" id="username" ></text>
<p>Question's number</p>
<input type="text" id="question" ></text>
</form>
<button>Submit</button>
<hr />
<p id="list" ></p>
</body>
</html>
$(document).ready( function() {
// hook ajax request
$("#username").blur( start );
$("#question").blur( start );
} );
function start() {
$("#list").empty();
$("#warning").hide();
var user = $.trim( $("#username").val() );
var quest = $.trim( $("#question").val() );
if( user == "" && quest == "" ) {
$("#warning").show();
} else {
$.ajax( { url : "teacher.php",
datatype: 'xml',
data : "name=" + user + "&" + "question=" + quest,
success : response
} );
}
}
function response( data ) {
$("#list").hide();
//$("#list").text("First list " + $(data).find('questions').find('question').text());
$(data).find('questions').find('question').each(function(){
var st = "Question # " + $(this).find('q_id').text() + ", userID: " + $(this).find('u_id').text()
+ ", student's code: " + $(this).find('u_script').text() + ", correct:" + $(this).find('correct').text() + "<br>";
var qid = $(this).find('q_id').text();
var uid = $(this).find('u_id').text();
var scr = $(this).find('u_script').text();
var asw = $(this).find('correct').text();
/*$("#list").append("Question # " + qid + ", userID: " + uid + ", student's code: " +
scr + ", correct:" + asw);*/
$("#list").append(st);
$("#list").show();
});
}
<?php
require_once ("db.php");
$qid = $_GET['question'];
$name = $_GET['name'];
if($name != "" && $qid == "")
{
$qry = $dbh -> prepare("select id from users where username = :u");
$qry -> bindParam(':u', $name);
$qry ->execute();
$row = $qry->fetch();
$uid = $row['id'];
$stmt = $dbh -> prepare("select * from results where u_id = :u");
$stmt->bindParam(':u', $uid);
$stmt->execute();
}
else if($name == "" && $qid != "")
{
$stmt = $dbh -> prepare("select * from results where quest_id = :q");
$stmt->bindParam(':q', $qid);
$stmt->execute();
}
else if($name != "" && $qid != "")
{
$qry = $dbh -> prepare("select id from users where username = :u");
$qry -> bindParam(':u', $name);
$qry ->execute();
$row = $qry->fetch();
$uid = $row['id'];
$stmt = $dbh -> prepare("select * from results where u_id = :u and quest_id = :q");
$stmt->bindParam(':u', $uid);
$stmt->bindParam(':q', $qid);
$stmt->execute();
}
//$stmt = $dbh->prepare(" select * from results where quest_id = :qID";
header( "Content-type: text/xml" );
print "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>
<questions>
<?while($rows = $stmt->fetch()){?>
<question>
<q_id><?=$rows['quest_id']?></q_id>
<u_id><?=$rows['u_id']?></u_id>
<u_script><?=$rows['script']?></u_script>
<correct><?=$rows['correct']?></correct>
</question>
<?}?>
</questions>
<?
require_once( "db.php" );
require_once( "session.php" );
// if not logged in, go back home
if( !$user ) {
header( "Location: home.php" );
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Assignments</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script src="teacher.js"></script>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<? include( "header.php" ); ?>
<? if( $user ) { ?>
<div><a href="admin.php">A link for logged in people</a></div>
<? } ?>
<h3>View students' answers</h3>
<form>
<p id="warning" >Type students' user name or question id or both.</p>
<p>Students' user name</p>
<input type="text" id="username" ></text>
<p>Question's number</p>
<input type="text" id="question" ></text>
</form>
<button>Submit</button>
<hr />
<p id="list" ></p>
</body>
</html>
var x1 = 2;
var output1 = 2;
var x2 = 3;
var output2 = 6;
var x3 = 4;
var output3 = 24;
var x4 = 5;
var output4 = 120;
var code = "return 2;";
$(document).ready(function() {
var out1 = f(x1);
var ans1,ans2, ans3, ans4;
var out2 = f(x2);
var out3 = f(x3);
var out4 = f(x4);
var check = true;
if(out1 == output1)
{ ans1 = "correct"; }
else
{ ans1 = "wrong";
check = false; }
if(out2 == output2)
{ ans2 = "correct"; }
else
{ ans2 = "wrong";
check = false; }
if(out3 == output3)
{ ans3 = "correct"; }
else
{ ans3 = "wrong";
check = false; }
if(out4 == output4)
{ ans4 = "correct"; }
else
{ ans4 = "wrong";
check = false; }
$("#test1").html("Your code is " + ans1 + " with input1" );
$("#test1").show();
$("#test2").html("Your code is " + ans2 + " with input2" );
$("#test2").show();
$("#test3").html("Your code is " + ans3 + " with input3" );
$("#test3").show();
$("#test4").html("Your code is " + ans4 + " with input4" );
$("#test4").show();
var userid= 5;
var ques_id = 1;
alert("script=" + code + "&userid=" +userid +"&ques_id=" + ques_id +"&correct=" + check);
$.ajax( {
//type: 'POST',
url: "saving.php",
data: "script=" + code +"&userid=" +userid +"&ques_id=" + ques_id+ "&correct=" + check,
success: saveAnswer
});
});
function saveAnswer()
{
alert ("Saving" ) ;
}
function f(x) {
return 2;}
<?php
require_once("db.php");
$comd = $_GET['command'];
$name = $_GET['username'];
$id = $_GET['q_id'];
$qry = $dbh -> prepare("select id from users where username = :u");
$qry -> bindParam(':u', $name);
$qry ->execute();
$r = $qry ->fetch();
$uid = $r['id'];
$quest_query = $dbh->prepare("select * from questions where id = :id");
$quest_query->bindParam(':id', $id);
$quest_query->execute();
$row=$quest_query->fetch();
$output1 = $row['output1'];
$output2 = $row['output2'];
$output3 = $row['output3'];
$output4 = $row['output4'];
$input1 = $row['input1'];
$input2 = $row['input2'];
$input3 = $row['input3'];
$input4 = $row['input4'];
//$text = $row['text'];
$myFile = "testFile.js";
$file = fopen($myFile, 'w') or die("Can't open file");
$comds = "
var x1 = " .(string)$input1. ";
var output1 = ".(string)$output1.";
var x2 = " .(string)$input2. ";
var output2 = ".(string)$output2.";
var x3 = " .(string)$input3. ";
var output3 = ".(string)$output3.";
var x4 = " .(string)$input4. ";
var output4 = ".(string)$output4.";
var code = \"".$comd."\";
$(document).ready(function() {
var out1 = f(x1);
var ans1,ans2, ans3, ans4;
var out2 = f(x2);
var out3 = f(x3);
var out4 = f(x4);
var check = true;
if(out1 == output1)
{ ans1 = \"correct\"; }
else
{ ans1 = \"wrong\";
check = false; }
if(out2 == output2)
{ ans2 = \"correct\"; }
else
{ ans2 = \"wrong\";
check = false; }
if(out3 == output3)
{ ans3 = \"correct\"; }
else
{ ans3 = \"wrong\";
check = false; }
if(out4 == output4)
{ ans4 = \"correct\"; }
else
{ ans4 = \"wrong\";
check = false; }
$(\"#test1\").html(\"Your code is \" + ans1 + \" with input1\" );
$(\"#test1\").show();
$(\"#test2\").html(\"Your code is \" + ans2 + \" with input2\" );
$(\"#test2\").show();
$(\"#test3\").html(\"Your code is \" + ans3 + \" with input3\" );
$(\"#test3\").show();
$(\"#test4\").html(\"Your code is \" + ans4 + \" with input4\" );
$(\"#test4\").show();
var userid= ".$uid.";
var ques_id = ".(string)$id.";
$.ajax( {
type: 'GET',
url: \"saving.php\",
data: \"script=\" + code +\"&userid=\" +userid +\"&ques_id=\" + ques_id+ \"&correct=\" + check,
success: saveAnswer
});
});
function saveAnswer()
{
alert (\"Saving\" ) ;
}
function f(x) {
".$comd.
"}";
fwrite($file, $comds);
fclose($file);
?>
<?=$comds?>
<?
require_once( "PasswordHash.php" );
// a class
class User
{
// class data
public $id, $user, $pass, $pass2, $fname, $lname, $email;
public $usernameError, $passwordError, $emailError;
public $loginError;
public $dirty;
public function __construct()
{
$this->dirty = true;
}
static public function duplicate_username( $username, $dbh )
{
$sql = "SELECT id FROM users WHERE username = :username";
$stmt = $dbh->prepare( $sql );
$stmt->bindParam( ':username', $username );
$stmt->execute();
if( $stmt->rowCount() > 0 ) {
return true;
}
return false;
}
public function load_from_post( $post ) {
$this->user = $post['username'];
$this->pass = $post['password'];
$this->pass2 = $post['password2'];
$this->fname = $post['first_name'];
$this->lname = $post['last_name'];
$this->email = $post['email'];
}
public function inflate_by_id( $id, $dbh ) {
$stmt = $dbh->prepare( "SELECT * FROM users WHERE id = :id" );
$stmt->bindParam( ':id', $id );
$stmt->execute();
if( $stmt->rowCount() == 0 ) {
throw new Exception( "Failed to inflate user with id $id" );
}
$row = $stmt->fetch();
$this->id = $row['id'];
$this->user = $row['username'];
$this->pass = $row['password'];
$this->fname = $row['first_name'];
$this->lname = $row['last_name'];
$this->email = $row['email'];
$this->dirty = false;
}
public function validate( $dbh ) {
if( !$this->user ) {
$this->usernameError = "Username cannot be blank";
} else if( strlen( $this->user ) < 6 ) {
$this->usernameError = "Username must be at least 6 characters";
} else if( User::duplicate_username( $this->user, $dbh ) ) {
$this->usernameError = "$this->user is already taken";
}
// passwords match and are at least 6 chars
if( !$this->pass ) {
$this->passwordError = "Password cannot be blank";
} else if( $this->pass != $this->pass2 ) {
$this->passwordError = "Passwords do not match";
} else if( strlen( $this->pass ) < 6 ) {
$this->passwordError = "Password must be at least 6 characters";
}
// first/last name aren't blank
if( !$this->email ) {
$this->emailError = "Email address cannot be blank";
}
return !$this->hasErrors();
}
public function hasUsernameError() { return $this->usernameError != ''; }
public function hasPasswordError() { return $this->passwordError != ''; }
public function hasEmailError() { return $this->emailError != ''; }
public function hasErrors() {
return $this->usernameError || $this->passwordError || $this->emailError;
}
public function save( $dbh ) {
// hash password
$hasher = new PasswordHash( 8, false );
$pwhash = $hasher->HashPassword( $this->pass );
$stmt = $dbh->prepare( "
INSERT INTO users
(username, password, first_name, last_name, email)
VALUES (:username, :password, :first_name, :last_name, :email);"
);
$stmt->bindParam( ':username', $this->user );
$stmt->bindParam( ':password', $pwhash );
$stmt->bindParam( ':first_name', $this->fname );
$stmt->bindParam( ':last_name', $this->lname );
$stmt->bindParam( ':email', $this->email );
$stmt->execute();
// get id
$this->id = $dbh->lastInsertId();
$this->dirty = false;
}
public function login( $user, $pass, $dbh )
{
// store username for repopulating forms
$this->user = $user;
// get the stored hash
$stmt = $dbh->prepare( "SELECT id, password FROM users WHERE username = :username" );
$stmt->bindParam( ':username', $user );
$stmt->execute();
if( $stmt->rowCount() == 0 ) {
$this->loginError = "Invalid username or password";
return false;
//throw new Exception( "No such user $user" );
}
$row = $stmt->fetch();
$stored_hash = $row['password'];
// compare with submitted password hash
$hasher = new PasswordHash( 8, false );
if( $hasher->CheckPassword( $pass, $stored_hash ) ) {
// login success!
$this->inflate_by_id( $row['id'], $dbh );
return true;
}
$this->loginError = "Invalid username or password";
return false;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment