--- loncom/homework/bridgetask.pm	2005/03/28 21:49:31	1.5
+++ loncom/homework/bridgetask.pm	2005/05/10 20:58:38	1.23
@@ -1,7 +1,7 @@
 # The LearningOnline Network with CAPA 
 # definition of tags that give a structure to a document
 #
-# $Id: bridgetask.pm,v 1.5 2005/03/28 21:49:31 albertel Exp $
+# $Id: bridgetask.pm,v 1.23 2005/05/10 20:58:38 albertel Exp $
 #
 # Copyright Michigan State University Board of Trustees
 #
@@ -37,23 +37,45 @@ use Apache::lonmenu;
 use Apache::lonlocal;
 use Apache::lonxml;
 use Time::HiRes qw( gettimeofday tv_interval );
+
 BEGIN {
     &Apache::lonxml::register('Apache::bridgetask',('Task','IntroParagraph','Dimension','Instance','InstanceText','Criteria','ClosingParagraph'));
 }
 
+sub initialize_bridgetask {
+    # id of current Dimension, 0 means that no dimension is current 
+    # (inside <Task> only)
+    $Apache::bridgetask::dimension='';
+    # list of all Dimension ids seen
+    @Apache::bridgetask::dimensionlist=();
+    # mandatory attribute of all Dimensions seen
+    %Apache::bridgetask::dimensionmandatory=();
+    # list of all current Instance ids
+    @Apache::bridgetask::instance=();
+    # list of all Instance ids seen in this problem
+    @Apache::bridgetask::instancelist=();
+    # key of queud user data that we are currently grading
+    $Apache::bridgetask::queue_key='';
+}
+
 sub proctor_check_auth {
-    my ($slot)=@_;
-    my $user=$ENV{'form.proctorname'};
-    my $domain=$ENV{'form.proctordomain'};
+    my ($slot_name,$slot)=@_;
+    my $user=$env{'form.proctorname'};
+    my $domain=$env{'form.proctordomain'};
     
     my @allowed=split(",",$slot->{'proctor'});
     foreach my $possible (@allowed) {
 	my ($puser,$pdom)=(split('@',$possible));
 	if ($puser eq $user && $pdom eq $domain) {
-	    my $authhost=&Apache::lonnet::authenticate($puser,$ENV{'form.proctorpassword'},$pdom);
+	    my $authhost=&Apache::lonnet::authenticate($puser,$env{'form.proctorpassword'},$pdom);
 	    if ($authhost ne 'no_host') {
-		$Apache::lonhomework::results{'resource.checkedin'}=
+		my $version=
+		    $Apache::lonhomework::results{'resource.version'}=
+		    $Apache::lonhomework::history{'resource.version'}++;
+		$Apache::lonhomework::results{"resource.$version.checkedin"}=
 		    $user.'@'.$domain;
+		$Apache::lonhomework::results{"resource.$version.checkedin.slot"}=
+		    $slot_name;
 		return 1;
 	    }
 	}
@@ -61,25 +83,57 @@ sub proctor_check_auth {
     return 0;
 }
 
+sub add_previous_version_button {
+    my $result;
+    $result.=&mt(' Show a previously done version: [_1]','<select name="previousversion">
+<option>Pick one</option>
+</select>');
+    return $result;
+}
+
+sub add_grading_button {
+    my $result;
+    $result.=' <input type="submit" name="gradeasubmission" value="'.
+	&mt("Get a submission to grade").'" />';
+    $result.='<input type="hidden" name="grade_target" value="webgrade" />';
+    return $result;
+}
+
+sub add_request_another_attempt_button {
+    
+}
+
 sub start_Task {
     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
 
-    &Apache::structuretags::initialize_storage();
-    &Apache::lonhomework::showhash(%Apache::lonhomework::history);
-
     my ($status,$accessmsg,$slot);
+    if ($target ne 'webgrade') {
+	&Apache::structuretags::initialize_storage();
+	&Apache::lonhomework::showhash(%Apache::lonhomework::history);
+    } 
+
     $Apache::lonhomework::parsing_a_task=1;
     #should get back a <html> or the neccesary stuff to start XML/MathML
     my ($result,$head_tag_start,$body_tag_start,$form_tag_start)=
 	&Apache::structuretags::page_start($target,$token,$tagstack,$parstack,$parser,$safeeval);
-
-    if ($target eq 'web' || $target eq 'grade' || $target eq 'answer' ||
+    
+    if ($target eq 'web') {
+	$body_tag_start.=&add_previous_version_button();
+	if ($Apache::lonhomework::modifygrades) {
+	    $body_tag_start.='<form name="gradesubmission" method="POST" action="';
+	    my $uri=$env{'request.uri'};
+	    if ($env{'request.enc'}) { $uri=&Apache::lonenc::encrypted($uri); }
+	    $body_tag_start.=$uri.'">'.&add_grading_button()."</form>";
+	}
+    }
+    if ($target eq 'web' || ($target eq 'grade' && !$env{'form.webgrade'}) || $target eq 'answer' ||
 	$target eq 'tex') {
-	($status,$accessmsg,$slot) = 
+	($status,$accessmsg,my $slot_name,$slot) = 
 	    &Apache::lonhomework::check_task_access('0');
-	push (@Apache::inputtags::status,$status);
+	push(@Apache::inputtags::status,$status);
+	$Apache::inputtags::slot_name=$slot_name;
 	my $expression='$external::datestatus="'.$status.'";';
-	$expression.='$external::gradestatus="'.$Apache::lonhomework::history{"resource.0.solved"}.'";';
+	$expression.='$external::gradestatus="'.$Apache::lonhomework::history{"resource.$version.solved"}.'";';
 	&Apache::run::run($expression,$safeeval);
 	&Apache::lonxml::debug("Got $status");
 	if (( $status eq 'CLOSED' ) ||
@@ -87,6 +141,7 @@ sub start_Task {
 	    ( $status eq 'UNAVAILABLE') ||
 	    ( $status eq 'NOT_IN_A_SLOT') ||
 	    ( $status eq 'NEEDS_CHECKIN') ||
+	    ( $status eq 'WAITING_FOR_GRADE') ||
 	    ( $status eq 'INVALID_ACCESS')) {
 	    my $bodytext=&Apache::lonxml::get_all_text("/task",$parser);
 	    if ( $target eq "web" ) {
@@ -99,6 +154,8 @@ sub start_Task {
 		} elsif ($status eq 'NEEDS_CHECKIN') {
 		    $msg.='<h1>'.&mt('You need the Proctor to validate you.').
 			'</h1>'.&proctor_validation_screen($slot);
+		} elsif ($status eq 'WAITING_FOR_GRADE') {
+		    $msg.='<h1>'.&mt('Your submission is in the grading queue.').'</h1>';
 		} elsif ($status ne 'NOT_YET_VIEWED') {
 		    $msg.='<h1>'.&mt('Not open to be viewed').'</h1>';
 		}
@@ -113,12 +170,15 @@ sub start_Task {
 		} else {
 		    $result.=&mt('Problem is not open to be viewed. It')." $accessmsg \\vskip 0 mm ";
 		}
-	    } elsif ($target eq 'grade') {
+	    } elsif ($target eq 'grade' && !$env{'form.webgrade'}) {
 		if ($status eq 'NEEDS_CHECKIN') {
-		    if (&proctor_check_auth($slot)) {
+		    if (&proctor_check_auth($slot_name,$slot)) {
 			#FIXME immeadiatly add this to the grading queue
                         #      with slot->{'endtime'} for when grading can 
                         #      begin on this resource
+			# FIXME I think the above is done by default,
+                        #        need to check that
+                        #        failure doesn't do this.
  		    }
 		}
 	    }
@@ -128,12 +188,45 @@ sub start_Task {
               $body_tag_start \n $form_tag_start".	
 	      '<input type="hidden" name="submitted" value="yes" />';
 	    # if we are viewing someone else preserve that info
-	    if (defined $ENV{'form.grade_symb'}) {
+	    if (defined $env{'form.grade_symb'}) {
 		foreach my $field ('symb','courseid','domain','username') {
 		    $result .= '<input type="hidden" name="grade_'.$field.
-			'" value="'.$ENV{"form.grade_$field"}.'" />'."\n";
+			'" value="'.$env{"form.grade_$field"}.'" />'."\n";
 		}
 	    }
+	    if ($Apache::lonhomework::history{'resource.status'} eq 'fail') {
+		$result.='<h1><font color="red">'.&mt('Did not pass').'</font></h1>';
+		$result.=&request_another_attempt_button();
+	    }
+	    if ($Apache::lonhomework::history{'resource.status'} eq 'pass') {
+		$result.='<h1><font color="green">'.&mt('Passed').'</font></h1>';
+	    }
+	}
+    } elsif ( ($target eq 'grade' && $env{'form.webgrade'}) ||
+	      $target eq 'webgrade') {
+	if ($target eq 'webgrade') {
+	    $result.=$head_tag_start.$body_tag_start.$form_tag_start;
+	    $result.='<input type="hidden" name="webgrade" value="yes" />';
+	    $result.=&show_queue();
+	}
+	my $todo=&get_from_queue();
+	if ($todo) {
+	    &setup_env_for_other_user($todo,$safeeval);
+	    my ($symb,$uname,$udom)=&decode_queue_key($todo);
+	    $result.="\n".'<table><tr><td>Found '.
+		&Apache::lonnet::gettitle($symb).' for '.$uname.' at '.$udom.'</td></tr></table>';
+	    $result.='<input type="hidden" name="gradingkey" value="'.
+		&Apache::lonnet::escape($todo).'" />';
+	    $Apache::bridgetask::queue_key=$todo;
+	    &Apache::structuretags::initialize_storage();
+	    &Apache::lonhomework::showhash(%Apache::lonhomework::history);
+	    $result.="\n".'<table width="100%" style="width:100%" border="1">';
+	} else {
+	    if ($target eq 'webgrade') {
+		$result.="\n".
+		    '<table><tr><td>No user to be graded.</td></tr></table>';
+	    }
+	    my $bodytext=&Apache::lonxml::get_all_text("/task",$parser);
 	}
     } else {
 	# page_start returned a starting result, delete it if we don't need it
@@ -146,20 +239,101 @@ sub end_Task {
     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
     my $result='';
     my $status=$Apache::inputtags::status['-1'];
+    my $version=$Apache::lonhomework::history{'resource.version'};
     if ($target eq 'grade' || $target eq 'web' || $target eq 'answer' ||
 	$target eq 'tex') {
 	if (
-	    (($target eq 'web') && ($ENV{'request.state'} ne 'construct')) ||
+	    (($target eq 'web') && ($env{'request.state'} ne 'construct')) ||
 	    ($target eq 'answer') || ($target eq 'tex')
 	   ) {
 	    if ($target eq 'web') {
+		if ($status eq 'CAN_ANSWER') {
+		    $result.="\n".'<table border="1">'.
+			&Apache::inputtags::file_selector($version,
+							  "bridgetask","*",
+							  'portfolioonly').
+							  "</table>";
+		    $result.=&Apache::inputtags::gradestatus('0');
+		}
+	    } 
+	    if ($target eq 'web' || $target eq 'webgrade') {
 		$result.=&Apache::lonxml::xmlend().'</html>';
 	    }
 	}
-	if ($target eq 'grade') {
+	if ($target eq 'grade' && !$env{'form.webgrade'}) {
+	    my $award='SUBMITTED';
+	    &Apache::essayresponse::file_submission('0','bridgetask',
+						    'portfiles',\$award);
+	    if ($award eq 'SUBMITTED' &&
+		$Apache::lonhomework::results{"resource.$version.bridgetask.portfiles"}) {
+		$Apache::lonhomework::results{"resource.$version.tries"}=
+		    1+$Apache::lonhomework::history{"resource.$version.tries"};
+	    }
+	    $Apache::lonhomework::results{"resource.$version.award"}=$award;
+	    &Apache::lonhomework::showhash(%Apache::lonhomework::results);
+	    &Apache::structuretags::finalize_storage();
+	    if ($award eq 'SUBMITTED') {
+		&add_to_queue();
+	    }
+	}
+	if ($target eq 'grade' && $env{'form.webgrade'}) {
+	    my $optional_required=
+		&Apache::lonxml::get_param('OptionalRequired',$parstack,
+					   $safeeval);
+	    my $optional_passed=0;
+	    my $mandatory_failed=0;
+	    my $ungraded=0;
+	    my $review=0;   
 	    &Apache::lonhomework::showhash(%Apache::lonhomework::results);
+	    foreach my $dim_id (@Apache::bridgetask::dimensionlist) {
+		my $status=
+		    $Apache::lonhomework::results{"resource.$dim_id.status"};
+		my $mandatory=
+		    ($Apache::bridgetask::dimensionmandatory{$dim_id} ne 'N');
+		if ($status eq 'pass') {
+		    if (!$mandatory) { $optional_passed++; }
+		} elsif ($status eq 'fail') {
+		    if ($mandatory) { $mandatory_failed++; }
+		} elsif ($status eq 'ungraded') {
+		    $ungraded++;
+		} elsif ($status eq 'review') {
+		    $review++;
+		}	
+	    }
+	    if ($optional_passed < $optional_required) {
+		$mandatory_failed++;
+	    }
+	    &Apache::lonxml::debug("all dim ".join(':',@Apache::bridgetask::dimensionlist)."results -> m_f $mandatory_failed o_p $optional_passed u $ungraded r $review");
+	    $Apache::lonhomework::results{'resource.grader'}=
+		$env{'user.name'}.'@'.$env{'user.domain'};
+	    if ($review) {
+		$Apache::lonhomework::results{'resource.status'}='review';
+		&move_to_review_queue();
+	    } elsif ($ungraded) {
+		$Apache::lonhomework::results{'resource.status'}='ungraded';
+		&check_queue_unlock();
+	    } elsif ($mandatory_failed) {
+		$Apache::lonhomework::results{'resource.status'}='fail';
+		$Apache::lonhomework::results{"resource.$version.award"}='EXACT_ANS';
+		&remove_from_queue();
+	    } else {
+		$Apache::lonhomework::results{'resource.status'}='pass';
+		$Apache::lonhomework::results{"resource.$version.award"}='INCORRECT';
+		&remove_from_queue();
+	    }
 	    &Apache::structuretags::finalize_storage();
 	}
+    } elsif ($target eq 'webgrade') {
+	$result.="</table>\n<hr />";
+	#$result.='<input type="submit" name="next" value="'.
+	#    &mt('Save &amp; Next').'" /> ';
+	#$result.='<input type="submit" name="end" value="'.
+	#    &mt('Save &amp; Stop Grading').'" /> ';
+	#$result.='<input type="submit" name="throwaway" value="'.
+	#    &mt('Throw Away &amp; Stop Grading').'" /> ';
+	#$result.='<input type="submit" name="save" value="'.
+	#    &mt('Save Partial Grade and Continue Grading').'" /> ';
+	$result.='</form>'.&Apache::loncommon::endbodytag().'</html>';
     } elsif ($target eq 'meta') {
 	$result.='<parameter part="0" package="Task"></parameter>'."\n";
 	#$result.=&Apache::response::meta_part_order();
@@ -169,11 +343,212 @@ sub end_Task {
     return $result;
 }
 
+sub move_to_review_queue {
+    &Apache::lonxml::debug("Want to move");
+}
+
+sub check_queue_unlock {
+    &Apache::lonxml::debug("Want to unlock?");
+}
+
+sub remove_from_queue {
+    &Apache::lonxml::debug("Want to remove. Done?");
+}
+
+sub setup_env_for_other_user {
+    my ($queue_key,$safeeval)=@_;
+    my ($symb,$uname,$udom)=&decode_queue_key($queue_key);
+    $env{'form.grade_symb'}=$symb;
+    $env{'form.grade_domain'}=$udom;
+    $env{'form.grade_username'}=$uname;
+    $env{'form.grade_courseid'}=$env{'request.course.id'};
+    &Apache::lonxml::initialize_rndseed($safeeval);
+}
+
+sub add_to_queue {
+    my ($symb,$cid,$udom,$uname)=&Apache::lonxml::whichuser();
+    my $cnum=$env{'course.'.$cid.'.num'};
+    my $cdom=$env{'course.'.$cid.'.domain'};
+    my %data;
+    $data{"$symb\0queue\0$uname\@$udom"}=[$Apache::inputtags::slot_name];
+    &Apache::lonnet::put('gradingqueue',\%data,$cdom,$cnum);
+}
+
+sub show_queue {
+    my $result;
+    my ($symb,$cid,$udom,$uname)=&Apache::lonxml::whichuser();
+    my $cnum=$env{'course.'.$cid.'.num'};
+    my $cdom=$env{'course.'.$cid.'.domain'};
+    my $regexp="^$symb\0";
+    my %queue=&Apache::lonnet::dump('gradingqueue',$cdom,$cnum,$regexp);
+    $result.="\n<h3>Current Queue</h3><table><tr><th>resource</th>".
+	"<th>user</th><th>type</th><th>data</th></tr>";
+    foreach my $key (sort(keys(%queue))) {
+	if ($key=~/locked$/) {
+	    my ($symb,$uname,$udom) = &decode_queue_key($key);
+	    my $title=&Apache::lonnet::gettitle($symb);
+	    $result.="<tr><td>$title</td><td>$uname</td><td>";
+	    $result.='<td>lock</td><td>'.$queue{$key}.'</td></tr>';
+	} elsif ($key=~/timestamp$/) {
+	    my ($symb,undef) = split("\0",$key);
+	    my $title=&Apache::lonnet::gettitle($symb);
+	    $result.="<tr><td>$title</td><td></td><td>";
+	    $result.='<td>last queue modification time</td><td>'.
+		&Apache::lonlocal::locallocaltime($queue{$key})."</td></tr>";
+	} else {
+	    my ($symb,$uname,$udom) = &decode_queue_key($key);
+	    my $title=&Apache::lonnet::gettitle($symb);
+	    $result.="<tr><td>$title</td><td>$uname</td><td>";
+	    my $slot=$queue{$key}->[0];
+	    my %slot_data=&Apache::lonnet::get_slot($slot);
+	    $result.='<td>queue entry</td><td>End time: '.
+		&Apache::lonlocal::locallocaltime($slot_data{'endtime'}).
+		"</td></tr>";
+	}
+    }
+    $result.="</table><hr />\n";
+    return $result;
+}
+
+sub decode_queue_key {
+    my ($key)=@_;
+    my ($symb,undef,$user) = split("\0",$key);
+    my ($uname,$udom) = split('@',$user);
+    return ($symb,$uname,$udom);
+}
+
+sub queue_key_locked {
+    my ($key,$cdom,$cnum)=@_;
+    my ($key_locked,$value)=
+	&Apache::lonnet::get('gradingqueue',["$key\0locked"],$cdom,$cnum);
+    if ($key_locked eq "$key\0locked") {
+	return $value;
+    }
+    return undef;
+}
+
+sub pick_from_queue_data {
+    my ($check_section,$queue,$cdom,$cnum)=@_;
+    foreach my $key (keys(%$queue)) {
+	my ($symb,$uname,$udom)=&decode_queue_key($key);
+	if ($check_section) {
+	    my $section=&Apache::lonnet::getsection($uname,$udom);
+	    if ($section eq $check_section) {
+		&Apache::lonnet::logthis("my sec");
+		next;
+	    }
+	}
+	my $slot=$queue->{$key}[0];
+	my %slot_data=&Apache::lonnet::get_slot($slot);
+	if ($slot_data{'endtime'} > time) { 
+	    &Apache::lonnet::logthis("not time");
+	    next;
+	}
+	if (&queue_key_locked($key,$cdom,$cnum)) {
+	    &Apache::lonnet::logthis("someone already has um.");
+	    next;
+	}
+	return $key;
+    }
+    return undef;
+}
+
+sub find_mid_grade {
+    my ($symb,$cdom,$cnum)=@_;
+    my $todo=&Apache::lonnet::unescape($env{'form.gradingkey'});
+    my $me=$env{'user.name'}.'@'.$env{'user.domain'};
+    if ($todo) {
+	my $who=&queue_key_locked($todo,$cdom,$cnum);
+	if ($who eq $me) { return $todo; }
+    }
+    my $regexp="^$symb\0.*\0locked\$";
+    my %locks=&Apache::lonnet::dump('gradingqueue',$cdom,$cnum,$regexp);
+    foreach my $key (keys(%locks)) {
+	my $who=$locks{$key};
+	if ($who eq $me) {
+	    $todo=$key;
+	    $todo=~s/\0locked$//;
+	    return $todo;
+	}
+    }
+    return undef;
+}
+
+sub get_from_queue {
+    my $result;
+    my ($symb,$cid,$udom,$uname)=&Apache::lonxml::whichuser();
+    my $cnum=$env{'course.'.$cid.'.num'};
+    my $cdom=$env{'course.'.$cid.'.domain'};
+    my $todo;
+    # FIXME need to find if I am 'mid grading'
+    $todo=&find_mid_grade($symb,$cdom,$cnum);
+    &Apache::lonnet::logthis("found ".join(':',&decode_queue_key($todo)));
+    if ($todo) { return $todo; }
+    while (1) {
+	my $starttime=time;
+	&Apache::lonnet::put('gradingqueue',{"$symb\0timestamp"=>$starttime},
+			     $cdom,$cnum);
+	&Apache::lonnet::logthis("$starttime");
+	my $regexp="^$symb\0queue\0";
+	my %queue=&Apache::lonnet::dump('gradingqueue',$cdom,$cnum,$regexp);
+	#make a pass looking for a user in my section
+	if ($env{'request.course.sec'}) {
+	    &Apache::lonnet::logthis("sce");
+	    $todo=&pick_from_queue_data($env{'request.course.sec'},\%queue,
+					$cdom,$cnum);
+	    &Apache::lonnet::logthis("sce $todo");
+	}
+	# no one in our section so look for any user that is ready for grading
+	if (!$todo) {
+	    &Apache::lonnet::logthis("no sce");
+	    $todo=&pick_from_queue_data($env{'request.course.sec'},\%queue,
+					$cdom,$cnum);
+	    &Apache::lonnet::logthis("no sce $todo");
+	}
+	# no user to grade 
+	if (!$todo) { last; }
+	&Apache::lonnet::logthis("got $todo");
+	# otherwise found someone so lets try to lock them
+	my $success=&Apache::lonnet::newput('gradingqueue',
+					    {"$todo\0locked"=>
+						 $env{'user.name'}.'@'.$env{'user.domain'}},
+					   $cdom,$cnum);
+	# someone else already picked them
+	&Apache::lonnet::logthis("success $todo");
+	if ($success ne 'ok') { next; }
+	my (undef,$endtime)=
+	    &Apache::lonnet::get('gradingqueue',["$symb\0timestamp"],
+				 $cdom,$cnum);
+	&Apache::lonnet::logthis("emd  $endtime");
+	# someone else already modified the queue, 
+	# perhaps our picked user wass already fully graded between
+	# when we picked him and when we locked his record? so lets
+	# double check.
+	if ($endtime != $starttime) {
+	    my ($key,$value)=
+		&Apache::lonnet::get('gradingqueue',["$todo"],
+				     $cdom,$cnum);
+	    &Apache::lonnet::logthis("check  $key .. $value");
+	    if ($key eq $todo && ref($value)) {
+	    } else {
+		&Apache::lonnet::del('gradingqueue',["$todo\0locked"],
+				     $cdom,$cnum);
+		&Apache::lonnet::logthis("del");
+		next;
+	    }
+	}
+	&Apache::lonnet::logthis("last $todo");
+	last;
+    }
+    return $todo;
+}
+
 sub start_ClosingParagraph {
     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
     my $result;
     if ($target eq 'web') {
-	$result='<table border="1"><tr><td>Closing</td></tr><tr><td>';
+    } elsif ($target eq 'webgrade') {
+	&Apache::lonxml::startredirection();
     }
     return $result;
 }
@@ -182,49 +557,158 @@ sub end_ClosingParagraph {
     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
     my $result;
     if ($target eq 'web') {
-	$result='</td></tr></table>';
+    } elsif ($target eq 'webgrade') {
+	&Apache::lonxml::endredirection();
     }
     return $result;
 }
 
+sub get_id {
+    my ($parstack,$safeeval)=@_;
+    my $id=&Apache::lonxml::get_param('id',$parstack,$safeeval);
+    if (!$id) { $id=$Apache::lonxml::curdepth; }
+    return $id;
+}
+
 my %dimension;
-my $dim_id;
 sub start_Dimension {
     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
     undef(%dimension);
-    $dim_id=$Apache::lonxml::curdepth;
+    my $dim_id=&get_id($parstack,$safeeval);
+    $Apache::bridgetask::dimension=$dim_id;
+    push(@Apache::bridgetask::dimensionlist,$dim_id);
+    undef(@Apache::bridgetask::instance);
+    $Apache::bridgetask::dimensionmandatory{$dim_id}=
+	&Apache::lonxml::get_param('Mandatory',$parstack,$safeeval);
     return '';
 }
 
-sub end_Dimension {
-    my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
-    my $result;
-    if ($target eq 'web') {
-	#FIXME just grabbing the first one for now, need
-	#to randomly pick one until all have been seen
-	#then start repicking
-	my $instance=$dimension{'instances'}->[0];
-	$result=$dimension{'intro'}.
-	    $dimension{$instance.'.text'}.
-	    '<table border="1"><tr><td>Criteria</td></tr><tr><td>';
-	foreach my $id (@{$dimension{$instance.'.criterias'}}) {
-	    $result.=$dimension{$instance.'.criteria.'.$id}.
-		'</td></tr><tr><td>';
+sub get_instance {
+    #FIXME just grabbing the first one for now, need
+    #to randomly pick one until all have been seen
+    #then start repicking
+    &Apache::response::pushrandomnumber();
+    my @order=&Math::Random::random_permutation(@{$dimension{'instances'}});
+    return $order[0];
+}
+
+{
+    my $last_link;
+    sub end_Dimension {
+	my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
+	my $result;
+	my $dim_id=&get_id($parstack,$safeeval);
+	my $instance=&get_instance();
+	if ($target eq 'web') {
+	    $result=$dimension{'intro'}.$dimension{$instance.'.text'};
+	    if ($Apache::lonhomework::history{'resource.status'} eq 'pass' ||
+		$Apache::lonhomework::history{'resource.status'} eq 'fail') {
+		foreach my $id (@{$dimension{$instance.'.criterias'}}) {
+		    my $status=$Apache::lonhomework::history{"resource.$dim_id.$instance.$id.status"};
+		    my $comment=$Apache::lonhomework::history{"resource.$dim_id.$instance.$id.comment"};
+		    $result.='<table border="1"><tr><td>';
+		    if ($status eq 'fail') {
+			$result.='<font color="red">'.&mt('Did not pass').'</font>';
+		    } elsif ($status eq 'pass') {
+			$result.='<font color="green">'.&mt('Passed').'</font>';
+		    } else {
+			&Apache::lonxml::error("Student viewing a graded bridgetask was show a status of $status");
+		    }
+		    $result.='</td></tr><tr><td>';
+		    if ($Apache::lonhomework::history{"resource.$dim_id.$instance.$id.comment"}) {
+			$result.=&mt('Comment from grader: ').$Apache::lonhomework::history{"resource.$dim_id.$instance.$id.comment"}.'</td></tr><tr><td>';
+		    }
+		    $result.=$dimension{$instance.'.criteria.'.$id}.
+			'</td></tr></table>';
+		}
+	    }
+	} elsif ($target eq 'webgrade') {
+	    foreach my $id (@{$dimension{$instance.'.criterias'}}) {
+		my $link='criteria_'.$instance.'_'.$id;
+		my $status=$Apache::lonhomework::history{"resource.$dim_id.$instance.$id.status"};
+		$result.='<tr><td width="100%" valign="top">'.
+		    '<a name="'.$link.'" />'.
+		    '<a name="next_'.$last_link.'" />'.
+		    '<br /><textarea enabled="false" style="width:100%" rows="8" width="25" wrap="hard">'.$dimension{$instance.'.criteria.'.$id}.'</textarea>'.
+		    #$dimension{$instance.'.criteria.'.$id}.
+		    '</td>'.
+		    '<td><nobr>Additional Comment for Student</nobr> <br />'.
+		    '<textarea style="width:100%" rows="8" width="25" wrap="hard" name="HWVAL_comment_'.$link.'">'.&HTML::Entities::encode($Apache::lonhomework::history{"resource.$dim_id.$instance.$id.comment"}).'</textarea>'.
+		    '</td>'.
+		    '<td>'.
+		    '<nobr><label><input type="radio" name="HWVAL_'.$link.'" value="ungraded" '.($status eq 'ungraded' || !$status ? 'checked="checked"':'').'/>Ungraded</label></nobr><br />'.
+		    '<label><input type="radio" name="HWVAL_'.$link.'" value="pass" '.($status eq 'pass' ? 'checked="checked"':'').' />Pass</label><br />'.
+		    '<label><input type="radio" name="HWVAL_'.$link.'" value="fail" '.($status eq 'fail' ? 'checked="checked"':'').' />Fail</label><br />'.
+		    '<label><input type="radio" name="HWVAL_'.$link.'" value="review" '.($status eq 'review' ? 'checked="checked"':'').' />Review</label><br />'.
+		    '</td>'.
+		    '<td>'.
+		    '<a href="#'.$last_link.'">Prev</a><br />'.
+		    '<a href="#next_'.$link.'">Next</a><br /><br /><br />'.
+		    '<input type="submit" name="next" value="'.
+		    &mt('Done').'" /> '.
+		    '</td></tr>';
+		$result.='<tr><td colspan="4">';
+		my (undef,undef,$udom,$uname) = &Apache::lonxml::whichuser();
+		my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
+		foreach my $partial_file (split(',',$Apache::lonhomework::history{"resource.$version.bridgetask.portfiles"})) {
+		    my $file=$file_url.$partial_file;
+		    &Apache::lonnet::allowuploaded('/adm/bridgetask',$file);
+		    $result.='<a href="'.$file.'" target="lonGRDs"><img src="'.
+			&Apache::loncommon::icon($file).'" border=0"> '.$file.
+			'</a>';
+		}
+		$result.='</td></tr>';
+		$last_link=$link;
+	    }
+	} elsif ($target eq 'grade' && $env{'form.webgrade'}) {
+	    my $optional_passed=0;
+	    my $mandatory_failed=0;
+	    my $ungraded=0;
+	    my $review=0;
+	    foreach my $id (@{$dimension{$instance.'.criterias'}}) {
+		my $status=$Apache::lonhomework::results{"resource.$dim_id.$instance.$id.status"}=$env{'form.HWVAL_criteria_'.$instance.'_'.$id};
+		$Apache::lonhomework::results{"resource.$dim_id.$instance.$id.comment"}=$env{'form.HWVAL_comment_criteria_'.$instance.'_'.$id};
+		my $mandatory=($dimension{$instance.'.criteria.'.$id.'.mandatory'} ne 'N');
+		if ($status eq 'pass') {
+		    if (!$mandatory) { $optional_passed++; }
+		} elsif ($status eq 'fail') {
+		    if ($mandatory) { $mandatory_failed++; }
+		} elsif ($status eq 'review') {
+		    $review++;
+		} elsif ($status eq 'ungraded') {
+		    $ungraded++;
+		} else {
+		    &Apache::lonxml::error("got weird status --$status--");
+		}
+	    }
+	    if ($optional_passed < $dimension{$instance.'.optionalrequired'}) {
+		$mandatory_failed++;
+	    }
+	    &Apache::lonxml::debug("all instance ".join(':',@{$dimension{$instance.'.criterias'}})." results -> m_f $mandatory_failed o_p $optional_passed u $ungraded r $review");
+	    if ($review) {
+		$Apache::lonhomework::results{"resource.$dim_id.status"}=
+		    'review';
+	    } elsif ($ungraded) {
+		$Apache::lonhomework::results{"resource.$dim_id.status"}=
+		    'ungraded';
+	    } elsif ($mandatory_failed) {
+		$Apache::lonhomework::results{"resource.$dim_id.status"}=
+		    'fail';
+	    } else {
+		$Apache::lonhomework::results{"resource.$dim_id.status"}=
+		    'pass';
+	    }
 	}
-	$result=~s/<tr><td>$//;
-	$result.='</table>';
+	return $result;
     }
-    return $result;
 }
 
 sub start_IntroParagraph {
     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
     my $result;
-    if ($target eq 'web') {
-	if ($tagstack->[-2] eq 'Dimension') {
+    if ($target eq 'web' || $target eq 'webgrade') {
+	if ($tagstack->[-2] eq 'Dimension' || $target eq 'webgrade') {
 	    &Apache::lonxml::startredirection();
-	} else {
-	    $result='<table border="1"><tr><td>Intro</td></tr><tr><td>';
 	}
     }
     return $result;
@@ -233,21 +717,22 @@ sub start_IntroParagraph {
 sub end_IntroParagraph {
     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
     my $result;
-    if ($target eq 'web') {
-	if ($tagstack->[-2] eq 'Dimension') {
+    if ($target eq 'web' || $target eq 'webgrade') {
+	if ($tagstack->[-2] eq 'Dimension' || $target eq 'webgrade') {
 	    $dimension{'intro'}=&Apache::lonxml::endredirection();
-	} else {
-	    $result='</td></tr></table>';
 	}
     }
     return $result;
 }
 
-my $instance_id;
 sub start_Instance {
     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
-    push(@{$dimension{'instances'}},$Apache::lonxml::curdepth);
-    $instance_id=$Apache::lonxml::curdepth;
+    my $id=&get_id($parstack,$safeeval);
+    push(@{$dimension{'instances'}},$id);
+    push(@Apache::bridgetask::instance,$id);
+    push(@Apache::bridgetask::instancelist,$id);
+    $dimension{$id.'.optionalrequired'}=
+	&Apache::lonxml::get_param('OptionalRequired',$parstack,$safeeval);
     return '';
 }
 
@@ -258,7 +743,7 @@ sub end_Instance {
 
 sub start_InstanceText {
     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
-    if ($target eq 'web') {
+    if ($target eq 'web' || $target eq 'webgrade') {
 	&Apache::lonxml::startredirection();
     }
     return '';
@@ -266,7 +751,8 @@ sub start_InstanceText {
 
 sub end_InstanceText {
     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
-    if ($target eq 'web') {
+    my $instance_id=$Apache::bridgetask::instance[-1];
+    if ($target eq 'web' || $target eq 'webgrade') {
 	$dimension{$instance_id.'.text'}=&Apache::lonxml::endredirection();
     }
     return '';
@@ -274,7 +760,7 @@ sub end_InstanceText {
 
 sub start_Criteria {
     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
-    if ($target eq 'web') {
+    if ($target eq 'web' || $target eq 'webgrade' || $target eq 'grade') {
 	&Apache::lonxml::startredirection();
     }
     return '';
@@ -282,10 +768,13 @@ sub start_Criteria {
 
 sub end_Criteria {
     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
-    if ($target eq 'web') {
+    my $instance_id=$Apache::bridgetask::instance[-1];
+    if ($target eq 'web' || $target eq 'webgrade' || $target eq 'grade') {
 	my $criteria=&Apache::lonxml::endredirection();
-	my $id=$Apache::lonxml::curdepth;
+	my $id=&get_id($parstack,$safeeval);
 	$dimension{$instance_id.'.criteria.'.$id}=$criteria;
+	$dimension{$instance_id.'.criteria.'.$id.'.mandatory'}=
+	    &Apache::lonxml::get_param('Mandatory',$parstack,$safeeval);
 	push(@{$dimension{$instance_id.'.criterias'}},$id);
     }
     return '';
@@ -295,11 +784,10 @@ sub proctor_validation_screen {
     my ($slot) = @_;
     my (undef,undef,$domain,$user) = &Apache::lonxml::whichuser();
     my $url=&Apache::lonnet::studentphoto($domain,$user,'jpg');
-    my $dom=(&Apache::lonxml::whichuser())[2];
-    my $user=$ENV{'form.proctorname'};
-    if ($ENV{'form.proctordomain'}) { $dom=$ENV{'form.proctordomain'}; }
+    $user=$env{'form.proctorname'};
+    if ($env{'form.proctordomain'}) { $domain=$env{'form.proctordomain'}; }
     my $msg;
-    if ($ENV{'form.proctorpassword'}) {
+    if ($env{'form.proctorpassword'}) {
 	$msg='<p><font color="red">'.&mt("Failed to authenticate the proctor.")
 	    .'</font></p>';
     }
@@ -307,13 +795,13 @@ sub proctor_validation_screen {
 <h2>Proctor Validation</h2>
     <p>Your room's proctor needs to validate your access to this resource.</p>
     $msg
-<form name="checkout" method="POST" action="$ENV{'request.uri'}">
+<form name="checkout" method="POST" action="$env{'request.uri'}">
 <input type="hidden" name="validate" value="yes" />
 <input type="hidden" name="submitted" value="yes" />
 <table>
   <tr><td>Proctor's Username:</td><td><input type="string" name="proctorname" value="$user" /></td></tr>
   <tr><td>Password:</td><td><input type="password" name="proctorpassword" value="" /></td></tr>
-  <tr><td>Proctor's Domain:</td><td><input type="string" name="proctordomain" value="$dom" /></td></tr>
+  <tr><td>Proctor's Domain:</td><td><input type="string" name="proctordomain" value="$domain" /></td></tr>
 </table>
 <input type="submit" name="checkoutbutton" value="Validate"  /><br />
 Student who should be logged in is:<br />