Annotation of loncom/homework/grades.pm, revision 1.447

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.447   ! foxr        4: # $Id: grades.pm,v 1.446 2007/10/08 22:29:59 banghart Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: package Apache::grades;
                     30: use strict;
                     31: use Apache::style;
                     32: use Apache::lonxml;
                     33: use Apache::lonnet;
1.3       albertel   34: use Apache::loncommon;
1.112     ng         35: use Apache::lonhtmlcommon;
1.68      ng         36: use Apache::lonnavmaps;
1.1       albertel   37: use Apache::lonhomework;
1.55      matthew    38: use Apache::loncoursedata;
1.362     albertel   39: use Apache::lonmsg();
1.1       albertel   40: use Apache::Constants qw(:common);
1.167     sakharuk   41: use Apache::lonlocal;
1.386     raeburn    42: use Apache::lonenc;
1.170     albertel   43: use String::Similarity;
1.359     www        44: use LONCAPA;
                     45: 
1.315     bowersj2   46: use POSIX qw(floor);
1.87      www        47: 
1.435     foxr       48: 
                     49: my %perm=();
1.447   ! foxr       50: my %bubble_lines_per_response = ();     # no. bubble lines for each response.
1.435     foxr       51:                                    # index is "symb.part_id"
                     52: 
1.447   ! foxr       53: my %first_bubble_line = ();	# First bubble line no. for each bubble.
        !            54: 
        !            55: # Save and restore the bubble lines array to the form env.
        !            56: 
        !            57: 
        !            58: sub save_bubble_lines {
        !            59: 
        !            60:     foreach my $line (keys(%bubble_lines_per_response)) {
        !            61: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
        !            62: 	$env{"form.scantron.first_bubble_line.$line"} =
        !            63: 	    $first_bubble_line{$line};
        !            64:     }
        !            65: }
        !            66: 
        !            67: 
        !            68: sub restore_bubble_lines {
        !            69:     my $line = 0;
        !            70:     %bubble_lines_per_response = ();
        !            71:     while ($env{"form.scantron.bubblelines.$line"}) {
        !            72: 	my $value = $env{"form.scantron.bubblelines.$line"};
        !            73: 	$bubble_lines_per_response{$line} = $value;
        !            74: 	$first_bubble_line{$line}  =
        !            75: 	    $env{"form.scantron.first_bubble_line.$line"};
        !            76: 	$line++;
        !            77:     }
        !            78: 
        !            79: }
        !            80: 
        !            81: #  Given the parsed scanline, get the response for 
        !            82: #  'answer' number n:
        !            83: 
        !            84: sub get_response_bubbles {
        !            85:     my ($parsed_line, $response)  = @_;
        !            86: 
        !            87:     my $bubble_line = $first_bubble_line{$response};
        !            88:     my $bubble_lines= $bubble_linse_per_response{$response};
        !            89:     my $selected = "";
        !            90: 
        !            91:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
        !            92: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"};
        !            93: 	$bubble_line++;
        !            94:     }
        !            95:     return $selected;
        !            96: }
        !            97: 
1.1       albertel   98: 
1.68      ng         99: # ----- These first few routines are general use routines.----
1.447   ! foxr      100: 
        !           101: # Return the number of occurences of a pattern in a string.
        !           102: 
        !           103: sub occurence_count {
        !           104:     my ($string, $pattern) = @_;
        !           105: 
        !           106:     my @matches = ($string =~ /$pattern/g);
        !           107: 
        !           108:     return scalar(@matches);
        !           109: }
        !           110: 
        !           111: 
        !           112: # Take a string known to have digits and convert all the
        !           113: # digits into letters in the range J,A..I.
        !           114: 
        !           115: sub digits_to_letters {
        !           116:     my ($input) = @_;
        !           117: 
        !           118:     my @alphabet = ('J', 'A'..'I');
        !           119: 
        !           120:     my @input    = split(//, $input);
        !           121:     my $output ='';
        !           122:     for (my $i = 0; $i < scalar(@input); $i++) {
        !           123: 	if ($input[$i] =~ /\d/) {
        !           124: 	    $output .= $alphabet[$input[$i]];
        !           125: 	} else {
        !           126: 	    $output .= $input[$i];
        !           127: 	}
        !           128:     }
        !           129:     return $output;
        !           130: }
        !           131: 
1.44      ng        132: #
1.146     albertel  133: # --- Retrieve the parts from the metadata file.---
1.44      ng        134: sub getpartlist {
1.324     albertel  135:     my ($symb) = @_;
1.439     albertel  136: 
                    137:     my $navmap   = Apache::lonnavmaps::navmap->new();
                    138:     my $res      = $navmap->getBySymb($symb);
                    139:     my $partlist = $res->parts();
                    140:     my $url      = $res->src();
                    141:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    142: 
1.146     albertel  143:     my @stores;
1.439     albertel  144:     foreach my $part (@{ $partlist }) {
1.146     albertel  145: 	foreach my $key (@metakeys) {
                    146: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    147: 	}
                    148:     }
                    149:     return @stores;
1.2       albertel  150: }
                    151: 
1.44      ng        152: # --- Get the symbolic name of a problem and the url
1.324     albertel  153: sub get_symb {
1.173     albertel  154:     my ($request,$silent) = @_;
1.257     albertel  155:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                    156:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
1.173     albertel  157:     if ($symb eq '') { 
                    158: 	if (!$silent) {
                    159: 	    $request->print("Unable to handle ambiguous references:$url:.");
                    160: 	    return ();
                    161: 	}
                    162:     }
1.418     albertel  163:     &Apache::lonenc::check_decrypt(\$symb);
1.324     albertel  164:     return ($symb);
1.32      ng        165: }
                    166: 
1.129     ng        167: #--- Format fullname, username:domain if different for display
                    168: #--- Use anywhere where the student names are listed
                    169: sub nameUserString {
                    170:     my ($type,$fullname,$uname,$udom) = @_;
                    171:     if ($type eq 'header') {
1.398     albertel  172: 	return '<b>&nbsp;Fullname&nbsp;</b><span class="LC_internal_info">(Username)</span>';
1.129     ng        173:     } else {
1.398     albertel  174: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    175: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        176:     }
                    177: }
                    178: 
1.44      ng        179: #--- Get the partlist and the response type for a given problem. ---
                    180: #--- Indicate if a response type is coded handgraded or not. ---
1.39      ng        181: sub response_type {
1.324     albertel  182:     my ($symb) = shift;
1.377     albertel  183: 
                    184:     my $navmap = Apache::lonnavmaps::navmap->new();
                    185:     my $res = $navmap->getBySymb($symb);
                    186:     my $partlist = $res->parts();
1.392     albertel  187:     my %vPart = 
                    188: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  189:     my (%response_types,%handgrade);
                    190:     foreach my $part (@{ $partlist }) {
1.392     albertel  191: 	next if (%vPart && !exists($vPart{$part}));
                    192: 
1.377     albertel  193: 	my @types = $res->responseType($part);
                    194: 	my @ids = $res->responseIds($part);
                    195: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    196: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    197: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    198: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    199: 				     '.handgrade',$symb);
1.41      ng        200: 	}
                    201:     }
1.377     albertel  202:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        203: }
                    204: 
1.375     albertel  205: sub flatten_responseType {
                    206:     my ($responseType) = @_;
                    207:     my @part_response_id =
                    208: 	map { 
                    209: 	    my $part = $_;
                    210: 	    map {
                    211: 		[$part,$_]
                    212: 		} sort(keys(%{ $responseType->{$part} }));
                    213: 	} sort(keys(%$responseType));
                    214:     return @part_response_id;
                    215: }
                    216: 
1.207     albertel  217: sub get_display_part {
1.324     albertel  218:     my ($partID,$symb)=@_;
1.207     albertel  219:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    220:     if (defined($display) and $display ne '') {
1.398     albertel  221: 	$display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
1.207     albertel  222:     } else {
                    223: 	$display=$partID;
                    224:     }
                    225:     return $display;
                    226: }
1.269     raeburn   227: 
1.118     ng        228: #--- Show resource title
                    229: #--- and parts and response type
                    230: sub showResourceInfo {
1.324     albertel  231:     my ($symb,$probTitle,$checkboxes) = @_;
1.154     albertel  232:     my $col=3;
                    233:     if ($checkboxes) { $col=4; }
1.398     albertel  234:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
                    235:     $result .='<table border="0">';
1.324     albertel  236:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.126     ng        237:     my %resptype = ();
1.122     ng        238:     my $hdgrade='no';
1.154     albertel  239:     my %partsseen;
1.375     albertel  240:     foreach my $partID (sort keys(%$responseType)) {
                    241: 	foreach my $resID (sort keys(%{ $responseType->{$partID} })) {
                    242: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
                    243: 	    my $responsetype = $responseType->{$partID}->{$resID};
                    244: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
                    245: 	    $result.='<tr>';
                    246: 	    if ($checkboxes) {
                    247: 		if (exists($partsseen{$partID})) {
                    248: 		    $result.="<td>&nbsp;</td>";
                    249: 		} else {
1.401     albertel  250: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
1.375     albertel  251: 		}
                    252: 		$partsseen{$partID}=1;
1.154     albertel  253: 	    }
1.375     albertel  254: 	    my $display_part=&get_display_part($partID,$symb);
1.398     albertel  255: 	    $result.='<td><b>Part: </b>'.$display_part.' <span class="LC_internal_info">'.
                    256: 		$resID.'</span></td>'.
1.375     albertel  257: 		'<td><b>Type: </b>'.$responsetype.'</td></tr>';
                    258: #	    '<td><b>Handgrade: </b>'.$handgrade.'</td></tr>';
1.154     albertel  259: 	}
1.118     ng        260:     }
                    261:     $result.='</table>'."\n";
1.147     albertel  262:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
1.118     ng        263: }
                    264: 
1.434     albertel  265: sub reset_caches {
                    266:     &reset_analyze_cache();
                    267:     &reset_perm();
                    268: }
                    269: 
                    270: {
                    271:     my %analyze_cache;
1.148     albertel  272: 
1.434     albertel  273:     sub reset_analyze_cache {
                    274: 	undef(%analyze_cache);
                    275:     }
                    276: 
                    277:     sub get_analyze {
                    278: 	my ($symb,$uname,$udom)=@_;
                    279: 	my $key = "$symb\0$uname\0$udom";
                    280: 	return $analyze_cache{$key} if (exists($analyze_cache{$key}));
                    281: 
                    282: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    283: 	$url=&Apache::lonnet::clutter($url);
                    284: 	my $subresult=&Apache::lonnet::ssi($url,
                    285: 					   ('grade_target' => 'analyze'),
                    286: 					   ('grade_domain' => $udom),
                    287: 					   ('grade_symb' => $symb),
                    288: 					   ('grade_courseid' => 
                    289: 					    $env{'request.course.id'}),
                    290: 					   ('grade_username' => $uname));
                    291: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    292: 	my %analyze=&Apache::lonnet::str2hash($subresult);
                    293: 	return $analyze_cache{$key} = \%analyze;
                    294:     }
                    295: 
                    296:     sub get_order {
                    297: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    298: 	my $analyze = &get_analyze($symb,$uname,$udom);
                    299: 	return $analyze->{"$partid.$respid.shown"};
                    300:     }
                    301: 
                    302:     sub get_radiobutton_correct_foil {
                    303: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    304: 	my $analyze = &get_analyze($symb,$uname,$udom);
                    305: 	foreach my $foil (@{&get_order($partid,$respid,$symb,$uname,$udom)}) {
                    306: 	    if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    307: 		return $foil;
                    308: 	    }
                    309: 	}
                    310:     }
1.148     albertel  311: }
1.434     albertel  312: 
1.118     ng        313: #--- Clean response type for display
1.335     albertel  314: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    315: #        response types only.
1.118     ng        316: sub cleanRecord {
1.336     albertel  317:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
                    318: 	$uname,$udom) = @_;
1.398     albertel  319:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  320:     if ($response =~ /^(option|rank)$/) {
                    321: 	my %answer=&Apache::lonnet::str2hash($answer);
                    322: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    323: 	my ($toprow,$bottomrow);
                    324: 	foreach my $foil (@$order) {
                    325: 	    if ($grading{$foil} == 1) {
                    326: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    327: 	    } else {
                    328: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    329: 	    }
1.398     albertel  330: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  331: 	}
                    332: 	return '<blockquote><table border="1">'.
                    333: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
1.398     albertel  334: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
1.148     albertel  335: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    336:     } elsif ($response eq 'match') {
                    337: 	my %answer=&Apache::lonnet::str2hash($answer);
                    338: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    339: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    340: 	my ($toprow,$middlerow,$bottomrow);
                    341: 	foreach my $foil (@$order) {
                    342: 	    my $item=shift(@items);
                    343: 	    if ($grading{$foil} == 1) {
                    344: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  345: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  346: 	    } else {
                    347: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  348: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  349: 	    }
1.398     albertel  350: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        351: 	}
1.126     ng        352: 	return '<blockquote><table border="1">'.
1.148     albertel  353: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
1.398     albertel  354: 	    '<tr valign="top"><td>'.$grayFont.'Item ID</span></td>'.
1.148     albertel  355: 	    $middlerow.'</tr>'.
1.398     albertel  356: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
1.148     albertel  357: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    358:     } elsif ($response eq 'radiobutton') {
                    359: 	my %answer=&Apache::lonnet::str2hash($answer);
                    360: 	my ($toprow,$bottomrow);
1.434     albertel  361: 	my $correct = 
                    362: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
                    363: 	foreach my $foil (@$order) {
1.148     albertel  364: 	    if (exists($answer{$foil})) {
1.434     albertel  365: 		if ($foil eq $correct) {
1.148     albertel  366: 		    $toprow.='<td><b>true</b></td>';
                    367: 		} else {
                    368: 		    $toprow.='<td><i>true</i></td>';
                    369: 		}
                    370: 	    } else {
                    371: 		$toprow.='<td>false</td>';
                    372: 	    }
1.398     albertel  373: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  374: 	}
                    375: 	return '<blockquote><table border="1">'.
                    376: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
1.398     albertel  377: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
1.148     albertel  378: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    379:     } elsif ($response eq 'essay') {
1.257     albertel  380: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        381: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  382: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    383: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        384: 
1.257     albertel  385: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    386: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    387: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    388: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    389: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    390: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
1.122     ng        391: 	}
1.166     albertel  392: 	$answer =~ s-\n-<br />-g;
                    393: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  394:     } elsif ( $response eq 'organic') {
                    395: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    396: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    397: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    398: 	return $result;
1.335     albertel  399:     } elsif ( $response eq 'Task') {
                    400: 	if ( $answer eq 'SUBMITTED') {
                    401: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  402: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  403: 	    return $result;
                    404: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    405: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    406: 			       keys(%{$record}));
                    407: 	    return join('<br />',($version,@matches));
                    408: 			       
                    409: 			       
                    410: 	} else {
                    411: 	    my $result =
                    412: 		'<p>'
                    413: 		.&mt('Overall result: [_1]',
                    414: 		     $record->{$version."resource.$respid.$partid.status"})
                    415: 		.'</p>';
                    416: 	    
                    417: 	    $result .= '<ul>';
                    418: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    419: 			     keys(%{$record}));
                    420: 	    foreach my $grade (sort(@grade)) {
                    421: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    422: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    423: 				     $dim, $record->{$grade}).
                    424: 			  '</li>';
                    425: 	    }
                    426: 	    $result.='</ul>';
                    427: 	    return $result;
                    428: 	}
1.440     albertel  429:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    430: 	$answer = 
                    431: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    432: 							      $answer);
1.122     ng        433:     }
1.118     ng        434:     return $answer;
                    435: }
                    436: 
                    437: #-- A couple of common js functions
                    438: sub commonJSfunctions {
                    439:     my $request = shift;
                    440:     $request->print(<<COMMONJSFUNCTIONS);
                    441: <script type="text/javascript" language="javascript">
                    442:     function radioSelection(radioButton) {
                    443: 	var selection=null;
                    444: 	if (radioButton.length > 1) {
                    445: 	    for (var i=0; i<radioButton.length; i++) {
                    446: 		if (radioButton[i].checked) {
                    447: 		    return radioButton[i].value;
                    448: 		}
                    449: 	    }
                    450: 	} else {
                    451: 	    if (radioButton.checked) return radioButton.value;
                    452: 	}
                    453: 	return selection;
                    454:     }
                    455: 
                    456:     function pullDownSelection(selectOne) {
                    457: 	var selection="";
                    458: 	if (selectOne.length > 1) {
                    459: 	    for (var i=0; i<selectOne.length; i++) {
                    460: 		if (selectOne[i].selected) {
                    461: 		    return selectOne[i].value;
                    462: 		}
                    463: 	    }
                    464: 	} else {
1.138     albertel  465:             // only one value it must be the selected one
                    466: 	    return selectOne.value;
1.118     ng        467: 	}
                    468:     }
                    469: </script>
                    470: COMMONJSFUNCTIONS
                    471: }
                    472: 
1.44      ng        473: #--- Dumps the class list with usernames,list of sections,
                    474: #--- section, ids and fullnames for each user.
                    475: sub getclasslist {
1.76      ng        476:     my ($getsec,$filterlist) = @_;
1.291     albertel  477:     my @getsec;
1.442     banghart  478:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  479:     if (!ref($getsec)) {
                    480: 	if ($getsec ne '' && $getsec ne 'all') {
                    481: 	    @getsec=($getsec);
                    482: 	}
                    483:     } else {
                    484: 	@getsec=@{$getsec};
                    485:     }
                    486:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
                    487: 
1.56      matthew   488:     my $classlist=&Apache::loncoursedata::get_classlist();
1.49      albertel  489:     # Bail out if we were unable to get the classlist
1.56      matthew   490:     return if (! defined($classlist));
                    491:     #
                    492:     my %sections;
                    493:     my %fullnames;
1.205     matthew   494:     foreach my $student (keys(%$classlist)) {
                    495:         my $end      = 
                    496:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    497:         my $start    = 
                    498:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    499:         my $id       = 
                    500:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    501:         my $section  = 
                    502:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    503:         my $fullname = 
                    504:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    505:         my $status   = 
                    506:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.76      ng        507: 	# filter students according to status selected
1.442     banghart  508: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    509: 	    if (!($stu_status =~ $status)) {
1.205     matthew   510: 		delete ($classlist->{$student});
1.76      ng        511: 		next;
                    512: 	    }
                    513: 	}
1.205     matthew   514: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  515: 	if (&canview($section)) {
1.291     albertel  516: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  517: 		$sections{$section}++;
1.205     matthew   518: 		$fullnames{$student}=$fullname;
1.103     albertel  519: 	    } else {
1.205     matthew   520: 		delete($classlist->{$student});
1.103     albertel  521: 	    }
                    522: 	} else {
1.205     matthew   523: 	    delete($classlist->{$student});
1.103     albertel  524: 	}
1.44      ng        525:     }
                    526:     my %seen = ();
1.56      matthew   527:     my @sections = sort(keys(%sections));
                    528:     return ($classlist,\@sections,\%fullnames);
1.44      ng        529: }
                    530: 
1.103     albertel  531: sub canmodify {
                    532:     my ($sec)=@_;
                    533:     if ($perm{'mgr'}) {
                    534: 	if (!defined($perm{'mgr_section'})) {
                    535: 	    # can modify whole class
                    536: 	    return 1;
                    537: 	} else {
                    538: 	    if ($sec eq $perm{'mgr_section'}) {
                    539: 		#can modify the requested section
                    540: 		return 1;
                    541: 	    } else {
                    542: 		# can't modify the request section
                    543: 		return 0;
                    544: 	    }
                    545: 	}
                    546:     }
                    547:     #can't modify
                    548:     return 0;
                    549: }
                    550: 
                    551: sub canview {
                    552:     my ($sec)=@_;
                    553:     if ($perm{'vgr'}) {
                    554: 	if (!defined($perm{'vgr_section'})) {
                    555: 	    # can modify whole class
                    556: 	    return 1;
                    557: 	} else {
                    558: 	    if ($sec eq $perm{'vgr_section'}) {
                    559: 		#can modify the requested section
                    560: 		return 1;
                    561: 	    } else {
                    562: 		# can't modify the request section
                    563: 		return 0;
                    564: 	    }
                    565: 	}
                    566:     }
                    567:     #can't modify
                    568:     return 0;
                    569: }
                    570: 
1.44      ng        571: #--- Retrieve the grade status of a student for all the parts
                    572: sub student_gradeStatus {
1.324     albertel  573:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  574:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        575:     my %partstatus = ();
                    576:     foreach (@$partlist) {
1.128     ng        577: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        578: 	$status              = 'nothing' if ($status eq '');
                    579: 	$partstatus{$_}      = $status;
                    580: 	my $subkey           = "resource.$_.submitted_by";
                    581: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    582:     }
                    583:     return %partstatus;
                    584: }
                    585: 
1.45      ng        586: # hidden form and javascript that calls the form
                    587: # Use by verifyscript and viewgrades
                    588: # Shows a student's view of problem and submission
                    589: sub jscriptNform {
1.324     albertel  590:     my ($symb) = @_;
1.442     banghart  591:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.45      ng        592:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
                    593: 	'    function viewOneStudent(user,domain) {'."\n".
                    594: 	'	document.onestudent.student.value = user;'."\n".
                    595: 	'	document.onestudent.userdom.value = domain;'."\n".
                    596: 	'	document.onestudent.submit();'."\n".
                    597: 	'    }'."\n".
                    598: 	'</script>'."\n";
                    599:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  600: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  601: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    602: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1.442     banghart  603: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        604: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    605: 	'<input type="hidden" name="student" value="" />'."\n".
                    606: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    607: 	'</form>'."\n";
                    608:     return $jscript;
                    609: }
1.39      ng        610: 
1.447   ! foxr      611: 
        !           612: 
1.315     bowersj2  613: # Given the score (as a number [0-1] and the weight) what is the final
                    614: # point value? This function will round to the nearest tenth, third,
                    615: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  616: sub compute_points {
1.315     bowersj2  617:     my ($score, $weight) = @_;
                    618:     
                    619:     my $tolerance = .00001;
                    620:     my $points = $score * $weight;
                    621: 
                    622:     # Check for nearness to 1/x.
                    623:     my $check_for_nearness = sub {
                    624:         my ($factor) = @_;
                    625:         my $num = ($points * $factor) + $tolerance;
                    626:         my $floored_num = floor($num);
1.316     albertel  627:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  628:             return $floored_num / $factor;
                    629:         }
                    630:         return $points;
                    631:     };
                    632: 
                    633:     $points = $check_for_nearness->(10);
                    634:     $points = $check_for_nearness->(3);
                    635:     $points = $check_for_nearness->(4);
                    636:     
                    637:     return $points;
                    638: }
                    639: 
1.44      ng        640: #------------------ End of general use routines --------------------
1.87      www       641: 
                    642: #
                    643: # Find most similar essay
                    644: #
                    645: 
                    646: sub most_similar {
1.426     albertel  647:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       648: 
                    649: # ignore spaces and punctuation
                    650: 
                    651:     $uessay=~s/\W+/ /gs;
                    652: 
1.282     www       653: # ignore empty submissions (occuring when only files are sent)
                    654: 
                    655:     unless ($uessay=~/\w+/) { return ''; }
                    656: 
1.87      www       657: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       658:     my $limit=0.6;
1.87      www       659:     my $sname='';
                    660:     my $sdom='';
                    661:     my $scrsid='';
                    662:     my $sessay='';
                    663: # go through all essays ...
1.426     albertel  664:     foreach my $tkey (keys(%$old_essays)) {
                    665: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       666: # ... except the same student
1.426     albertel  667:         next if (($tname eq $uname) && ($tdom eq $udom));
                    668: 	my $tessay=$old_essays->{$tkey};
                    669: 	$tessay=~s/\W+/ /gs;
1.87      www       670: # String similarity gives up if not even limit
1.426     albertel  671: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       672: # Found one
1.426     albertel  673: 	if ($tsimilar>$limit) {
                    674: 	    $limit=$tsimilar;
                    675: 	    $sname=$tname;
                    676: 	    $sdom=$tdom;
                    677: 	    $scrsid=$tcrsid;
                    678: 	    $sessay=$old_essays->{$tkey};
                    679: 	}
1.87      www       680:     }
1.88      www       681:     if ($limit>0.6) {
1.87      www       682:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    683:     } else {
                    684:        return ('','','','',0);
                    685:     }
                    686: }
                    687: 
1.44      ng        688: #-------------------------------------------------------------------
                    689: 
                    690: #------------------------------------ Receipt Verification Routines
1.45      ng        691: #
1.44      ng        692: #--- Check whether a receipt number is valid.---
                    693: sub verifyreceipt {
                    694:     my $request  = shift;
                    695: 
1.257     albertel  696:     my $courseid = $env{'request.course.id'};
1.184     www       697:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  698: 	$env{'form.receipt'};
1.44      ng        699:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  700:     my ($symb)   = &get_symb($request);
1.44      ng        701: 
1.398     albertel  702:     my $title.='<h3><span class="LC_info">Verifying Submission Receipt '.
                    703: 	$receipt.'</h3></span>'."\n".
                    704: 	'<h4><b>Resource: </b>'.$env{'form.probTitle'}.'</h4><br /><br />'."\n";
1.44      ng        705: 
                    706:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   707:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  708:     
                    709:     my $receiptparts=0;
1.390     albertel  710:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    711: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  712:     my $parts=['0'];
1.324     albertel  713:     if ($receiptparts) { ($parts)=&response_type($symb); }
1.294     albertel  714:     foreach (sort 
                    715: 	     {
                    716: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    717: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    718: 		 }
                    719: 		 return $a cmp $b;
                    720: 	     } (keys(%$fullname))) {
1.44      ng        721: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  722: 	foreach my $part (@$parts) {
                    723: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
                    724: 		$contents.='<tr bgcolor="#ffffe6"><td>&nbsp;'."\n".
                    725: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  726: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  727: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    728: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    729: 		if ($receiptparts) {
                    730: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    731: 		}
                    732: 		$contents.='</tr>'."\n";
                    733: 		
                    734: 		$matches++;
                    735: 	    }
1.44      ng        736: 	}
                    737:     }
                    738:     if ($matches == 0) {
                    739: 	$string = $title.'No match found for the above receipt.';
                    740:     } else {
1.324     albertel  741: 	$string = &jscriptNform($symb).$title.
1.44      ng        742: 	    'The above receipt matches the following student'.
                    743: 	    ($matches <= 1 ? '.' : 's.')."\n".
                    744: 	    '<table border="0"><tr><td bgcolor="#777777">'."\n".
                    745: 	    '<table border="0"><tr bgcolor="#e6ffff">'."\n".
                    746: 	    '<td><b>&nbsp;Fullname&nbsp;</b></td>'."\n".
                    747: 	    '<td><b>&nbsp;Username&nbsp;</b></td>'."\n".
1.177     albertel  748: 	    '<td><b>&nbsp;Domain&nbsp;</b></td>';
                    749: 	if ($receiptparts) {
                    750: 	    $string.='<td>&nbsp;Problem Part&nbsp;</td>';
                    751: 	}
                    752: 	$string.='</tr>'."\n".$contents.
1.44      ng        753: 	    '</table></td></tr></table>'."\n";
                    754:     }
1.324     albertel  755:     return $string.&show_grading_menu_form($symb);
1.44      ng        756: }
                    757: 
                    758: #--- This is called by a number of programs.
                    759: #--- Called from the Grading Menu - View/Grade an individual student
                    760: #--- Also called directly when one clicks on the subm button 
                    761: #    on the problem page.
1.30      ng        762: sub listStudents {
1.41      ng        763:     my ($request) = shift;
1.49      albertel  764: 
1.324     albertel  765:     my ($symb) = &get_symb($request);
1.257     albertel  766:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    767:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    768:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                    769:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    770: 
                    771:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
                    772:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    773: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  774: 
1.398     albertel  775:     my $result='<h3><span class="LC_info">&nbsp;'.$viewgrade.
                    776: 	' Submissions for a Student or a Group of Students</span></h3>';
1.118     ng        777: 
1.324     albertel  778:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  779: 
1.45      ng        780:     $request->print(<<LISTJAVASCRIPT);
                    781: <script type="text/javascript" language="javascript">
1.110     ng        782:     function checkSelect(checkBox) {
                    783: 	var ctr=0;
                    784: 	var sense="";
                    785: 	if (checkBox.length > 1) {
                    786: 	    for (var i=0; i<checkBox.length; i++) {
                    787: 		if (checkBox[i].checked) {
                    788: 		    ctr++;
                    789: 		}
                    790: 	    }
                    791: 	    sense = "a student or group of students";
                    792: 	} else {
                    793: 	    if (checkBox.checked) {
                    794: 		ctr = 1;
                    795: 	    }
                    796: 	    sense = "the student";
                    797: 	}
                    798: 	if (ctr == 0) {
1.126     ng        799: 	    alert("Please select "+sense+" before clicking on the Next button.");
1.110     ng        800: 	    return false;
                    801: 	}
                    802: 	document.gradesub.submit();
                    803:     }
                    804: 
                    805:     function reLoadList(formname) {
1.112     ng        806: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        807: 	formname.command.value = 'submission';
                    808: 	formname.submit();
                    809:     }
1.45      ng        810: </script>
                    811: LISTJAVASCRIPT
                    812: 
1.118     ng        813:     &commonJSfunctions($request);
1.41      ng        814:     $request->print($result);
1.39      ng        815: 
1.401     albertel  816:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    817:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  818:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
                    819: 	"\n".$table.
1.401     albertel  820: 	'&nbsp;<b>View Problem Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.267     albertel  821: 	'<label><input type="radio" name="vProb" value="yes" /> one student </label>'."\n".
                    822: 	'<label><input type="radio" name="vProb" value="all" /> all students </label><br />'."\n".
                    823: 	'&nbsp;<b>View Answer: </b><label><input type="radio" name="vAns" value="no"  /> no </label>'."\n".
                    824: 	'<label><input type="radio" name="vAns" value="yes" /> one student </label>'."\n".
1.401     albertel  825: 	'<label><input type="radio" name="vAns" value="all" checked="checked" /> all students </label><br />'."\n".
1.49      albertel  826: 	'&nbsp;<b>Submissions: </b>'."\n";
1.257     albertel  827:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.267     albertel  828: 	$gradeTable.='<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> essay part only </label>'."\n";
1.49      albertel  829:     }
1.442     banghart  830:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    831:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  832:     $env{'form.Status'} = $saveStatus;
1.267     albertel  833:     $gradeTable.='<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> last submission only </label>'."\n".
                    834: 	'<label><input type="radio" name="lastSub" value="last" /> last submission & parts info </label>'."\n".
                    835: 	'<label><input type="radio" name="lastSub" value="datesub" /> by dates and submissions </label>'."\n".
1.348     bowersj2  836: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label><br />'."\n".
                    837:         '&nbsp;<b>Grading Increments:</b> <select name="increment">'.
                    838:         '<option value="1">Whole Points</option>'.
                    839:         '<option value=".5">Half Points</option>'.
1.349     albertel  840:         '<option value=".25">Quarter Points</option>'.
                    841:         '<option value=".1">Tenths of a Point</option>'.
1.348     bowersj2  842:         '</select>'.
1.432     banghart  843:         &build_section_inputs().
1.45      ng        844: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  845: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    846: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    847: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    848: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel  849: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        850: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    851: 
1.257     albertel  852:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.442     banghart  853: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
1.124     ng        854:     } else {
                    855: 	$gradeTable.='<b>Student Status:</b> '.
                    856: 	    &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);').'<br />';
                    857:     }
1.112     ng        858: 
1.126     ng        859:     $gradeTable.='To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
                    860: 	'next to the student\'s name(s). Then click on the Next button.<br />'."\n".
1.110     ng        861: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
1.249     albertel  862: 
                    863: # checkall buttons
                    864:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        865:     $gradeTable.='<input type="button" '."\n".
1.45      ng        866: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1.249     albertel  867: 	'value="Next->" /> <br />'."\n";
                    868:     $gradeTable.=&check_buttons();
1.401     albertel  869:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />Check For Plagiarism</label>';
1.249     albertel  870:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1');
1.45      ng        871:     $gradeTable.='<table border="0"><tr><td bgcolor="#777777">'.
1.110     ng        872: 	'<table border="0"><tr bgcolor="#e6ffff">';
                    873:     my $loop = 0;
                    874:     while ($loop < 2) {
1.126     ng        875: 	$gradeTable.='<td><b>&nbsp;No.</b>&nbsp;</td><td><b>&nbsp;Select&nbsp;</b></td>'.
1.250     albertel  876: 	    '<td>'.&nameUserString('header').'&nbsp;Section/Group</td>';
1.301     albertel  877: 	if ($env{'form.showgrading'} eq 'yes' 
                    878: 	    && $submitonly ne 'queued'
                    879: 	    && $submitonly ne 'all') {
1.110     ng        880: 	    foreach (sort(@$partlist)) {
1.324     albertel  881: 		my $display_part=&get_display_part((split(/_/))[0],$symb);
1.207     albertel  882: 		$gradeTable.='<td><b>&nbsp;Part: '.$display_part.
                    883: 		    ' Status&nbsp;</b></td>';
1.110     ng        884: 	    }
1.301     albertel  885: 	} elsif ($submitonly eq 'queued') {
                    886: 	    $gradeTable.='<td><b>&nbsp;'.&mt('Queue Status').'&nbsp;</b></td>';
1.110     ng        887: 	}
                    888: 	$loop++;
1.126     ng        889: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        890:     }
1.45      ng        891:     $gradeTable.='</tr>'."\n";
1.41      ng        892: 
1.45      ng        893:     my $ctr = 0;
1.294     albertel  894:     foreach my $student (sort 
                    895: 			 {
                    896: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    897: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    898: 			     }
                    899: 			     return $a cmp $b;
                    900: 			 }
                    901: 			 (keys(%$fullname))) {
1.41      ng        902: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  903: 
1.110     ng        904: 	my %status = ();
1.301     albertel  905: 
                    906: 	if ($submitonly eq 'queued') {
                    907: 	    my %queue_status = 
                    908: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    909: 							$udom,$uname);
                    910: 	    next if (!defined($queue_status{'gradingqueue'}));
                    911: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    912: 	}
                    913: 
                    914: 	if ($env{'form.showgrading'} eq 'yes' 
                    915: 	    && $submitonly ne 'queued'
                    916: 	    && $submitonly ne 'all') {
1.324     albertel  917: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel  918: 	    my $submitted = 0;
1.164     albertel  919: 	    my $graded = 0;
1.248     albertel  920: 	    my $incorrect = 0;
1.110     ng        921: 	    foreach (keys(%status)) {
1.145     albertel  922: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel  923: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                    924: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    925: 		
1.110     ng        926: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                    927: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel  928: 		    $submitted = 0;
1.150     albertel  929: 		    my ($part)=split(/\./,$partid);
1.110     ng        930: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel  931: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng        932: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                    933: 		}
1.41      ng        934: 	    }
1.248     albertel  935: 	    
1.156     albertel  936: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                    937: 				     $submitonly eq 'incorrect' ||
                    938: 				     $submitonly eq 'graded'));
1.248     albertel  939: 	    next if (!$graded && ($submitonly eq 'graded'));
                    940: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng        941: 	}
1.34      ng        942: 
1.45      ng        943: 	$ctr++;
1.249     albertel  944: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    945: 
1.104     albertel  946: 	if ( $perm{'vgr'} eq 'F' ) {
1.110     ng        947: 	    $gradeTable.='<tr bgcolor="#ffffe6">' if ($ctr%2 ==1);
1.126     ng        948: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.249     albertel  949:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
                    950:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                    951: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                    952: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
                    953: 	       '&nbsp;'.$section.'</td>'."\n";
1.110     ng        954: 
1.257     albertel  955: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.110     ng        956: 		foreach (sort keys(%status)) {
                    957: 		    next if (/^resource.*?submitted_by$/);
1.276     albertel  958: 		    $gradeTable.='<td align="center">&nbsp;'.$status{$_}.'&nbsp;</td>'."\n";
1.110     ng        959: 		}
1.41      ng        960: 	    }
1.126     ng        961: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.110     ng        962: 	    $gradeTable.='</tr>'."\n" if ($ctr%2 ==0);
1.41      ng        963: 	}
                    964:     }
1.110     ng        965:     if ($ctr%2 ==1) {
1.126     ng        966: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel  967: 	    if ($env{'form.showgrading'} eq 'yes' 
                    968: 		&& $submitonly ne 'queued'
                    969: 		&& $submitonly ne 'all') {
1.110     ng        970: 		foreach (@$partlist) {
                    971: 		    $gradeTable.='<td>&nbsp;</td>';
                    972: 		}
1.301     albertel  973: 	    } elsif ($submitonly eq 'queued') {
                    974: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng        975: 	    }
                    976: 	$gradeTable.='</tr>';
                    977:     }
                    978: 
1.249     albertel  979:     $gradeTable.='</table></td></tr></table>'."\n".
1.45      ng        980: 	'<input type="button" '.
                    981: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1.126     ng        982: 	'value="Next->" /></form>'."\n";
1.45      ng        983:     if ($ctr == 0) {
1.96      albertel  984: 	my $num_students=(scalar(keys(%$fullname)));
                    985: 	if ($num_students eq 0) {
1.398     albertel  986: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">There are no students currently enrolled.</span>';
1.96      albertel  987: 	} else {
1.171     albertel  988: 	    my $submissions='submissions';
                    989: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                    990: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel  991: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel  992: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.171     albertel  993: 		'No '.$submissions.' found for this resource for any students. ('.$num_students.
1.398     albertel  994: 		' students checked for '.$submissions.')</span><br />';
1.96      albertel  995: 	}
1.46      ng        996:     } elsif ($ctr == 1) {
                    997: 	$gradeTable =~ s/type=checkbox/type=checkbox checked/;
1.45      ng        998:     }
1.324     albertel  999:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1000:     $request->print($gradeTable);
1.44      ng       1001:     return '';
1.10      ng       1002: }
                   1003: 
1.44      ng       1004: #---- Called from the listStudents routine
1.249     albertel 1005: 
                   1006: sub check_script {
                   1007:     my ($form, $type)=@_;
                   1008:     my $chkallscript='<script type="text/javascript">
                   1009:     function checkall() {
                   1010:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1011:             ele = document.forms.'.$form.'.elements[i];
                   1012:             if (ele.name == "'.$type.'") {
                   1013:             document.forms.'.$form.'.elements[i].checked=true;
                   1014:                                        }
                   1015:         }
                   1016:     }
                   1017: 
                   1018:     function checksec() {
                   1019:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1020:             ele = document.forms.'.$form.'.elements[i];
                   1021:            string = document.forms.'.$form.'.chksec.value;
                   1022:            if
                   1023:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1024:               document.forms.'.$form.'.elements[i].checked=true;
                   1025:             }
                   1026:         }
                   1027:     }
                   1028: 
                   1029: 
                   1030:     function uncheckall() {
                   1031:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1032:             ele = document.forms.'.$form.'.elements[i];
                   1033:             if (ele.name == "'.$type.'") {
                   1034:             document.forms.'.$form.'.elements[i].checked=false;
                   1035:                                        }
                   1036:         }
                   1037:     }
                   1038: 
                   1039: </script>'."\n";
                   1040:     return $chkallscript;
                   1041: }
                   1042: 
                   1043: sub check_buttons {
                   1044:     my $buttons.='<input type="button" onclick="checkall()" value="Check All" />';
                   1045:     $buttons.='<input type="button" onclick="uncheckall()" value="Uncheck All" />&nbsp;';
                   1046:     $buttons.='<input type="button" onclick="checksec()" value="Check Section/Group" />';
                   1047:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1048:     return $buttons;
                   1049: }
                   1050: 
1.44      ng       1051: #     Displays the submissions for one student or a group of students
1.34      ng       1052: sub processGroup {
1.41      ng       1053:     my ($request)  = shift;
                   1054:     my $ctr        = 0;
1.155     albertel 1055:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1056:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1057: 
1.396     banghart 1058:     foreach my $student (@stuchecked) {
                   1059: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1060: 	$env{'form.student'}        = $uname;
                   1061: 	$env{'form.userdom'}        = $udom;
                   1062: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1063: 	&submission($request,$ctr,$total);
                   1064: 	$ctr++;
                   1065:     }
                   1066:     return '';
1.35      ng       1067: }
1.34      ng       1068: 
1.44      ng       1069: #------------------------------------------------------------------------------------
                   1070: #
                   1071: #-------------------------- Next few routines handles grading by student, essentially
                   1072: #                           handles essay response type problem/part
                   1073: #
                   1074: #--- Javascript to handle the submission page functionality ---
                   1075: sub sub_page_js {
                   1076:     my $request = shift;
                   1077:     $request->print(<<SUBJAVASCRIPT);
                   1078: <script type="text/javascript" language="javascript">
1.71      ng       1079:     function updateRadio(formname,id,weight) {
1.125     ng       1080: 	var gradeBox = formname["GD_BOX"+id];
                   1081: 	var radioButton = formname["RADVAL"+id];
                   1082: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1083: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1084: 	gradeBox.value = pts;
                   1085: 	var resetbox = false;
                   1086: 	if (isNaN(pts) || pts < 0) {
                   1087: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
                   1088: 	    for (var i=0; i<radioButton.length; i++) {
                   1089: 		if (radioButton[i].checked) {
                   1090: 		    gradeBox.value = i;
                   1091: 		    resetbox = true;
                   1092: 		}
                   1093: 	    }
                   1094: 	    if (!resetbox) {
                   1095: 		formtextbox.value = "";
                   1096: 	    }
                   1097: 	    return;
1.44      ng       1098: 	}
1.71      ng       1099: 
                   1100: 	if (pts > weight) {
                   1101: 	    var resp = confirm("You entered a value ("+pts+
                   1102: 			       ") greater than the weight for the part. Accept?");
                   1103: 	    if (resp == false) {
1.125     ng       1104: 		gradeBox.value = oldpts;
1.71      ng       1105: 		return;
                   1106: 	    }
1.44      ng       1107: 	}
1.13      albertel 1108: 
1.71      ng       1109: 	for (var i=0; i<radioButton.length; i++) {
                   1110: 	    radioButton[i].checked=false;
                   1111: 	    if (pts == i && pts != "") {
                   1112: 		radioButton[i].checked=true;
                   1113: 	    }
                   1114: 	}
                   1115: 	updateSelect(formname,id);
1.125     ng       1116: 	formname["stores"+id].value = "0";
1.41      ng       1117:     }
1.5       albertel 1118: 
1.72      ng       1119:     function writeBox(formname,id,pts) {
1.125     ng       1120: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1121: 	if (checkSolved(formname,id) == 'update') {
                   1122: 	    gradeBox.value = pts;
                   1123: 	} else {
1.125     ng       1124: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1125: 	    gradeBox.value = oldpts;
1.125     ng       1126: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1127: 	    for (var i=0; i<radioButton.length; i++) {
                   1128: 		radioButton[i].checked=false;
1.72      ng       1129: 		if (i == oldpts) {
1.71      ng       1130: 		    radioButton[i].checked=true;
                   1131: 		}
                   1132: 	    }
1.41      ng       1133: 	}
1.125     ng       1134: 	formname["stores"+id].value = "0";
1.71      ng       1135: 	updateSelect(formname,id);
                   1136: 	return;
1.41      ng       1137:     }
1.44      ng       1138: 
1.71      ng       1139:     function clearRadBox(formname,id) {
                   1140: 	if (checkSolved(formname,id) == 'noupdate') {
                   1141: 	    updateSelect(formname,id);
                   1142: 	    return;
                   1143: 	}
1.125     ng       1144: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1145: 	for (var i=0; i<gradeSelect.length; i++) {
                   1146: 	    if (gradeSelect[i].selected) {
                   1147: 		var selectx=i;
                   1148: 	    }
                   1149: 	}
1.125     ng       1150: 	var stores = formname["stores"+id];
1.71      ng       1151: 	if (selectx == stores.value) { return };
1.125     ng       1152: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1153: 	gradeBox.value = "";
1.125     ng       1154: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1155: 	for (var i=0; i<radioButton.length; i++) {
                   1156: 	    radioButton[i].checked=false;
                   1157: 	}
                   1158: 	stores.value = selectx;
                   1159:     }
1.5       albertel 1160: 
1.71      ng       1161:     function checkSolved(formname,id) {
1.125     ng       1162: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1163: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1164: 	    if (!reply) {return "noupdate";}
1.120     ng       1165: 	    formname.overRideScore.value = 'yes';
1.41      ng       1166: 	}
1.71      ng       1167: 	return "update";
1.13      albertel 1168:     }
1.71      ng       1169: 
                   1170:     function updateSelect(formname,id) {
1.125     ng       1171: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1172: 	return;
1.41      ng       1173:     }
1.33      ng       1174: 
1.121     ng       1175: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1176:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1177: 	formname.gradeOpt.value = val;
1.71      ng       1178: 	if (val == "Save & Next") {
                   1179: 	    for (i=0;i<=total;i++) {
                   1180: 		for (j=0;j<parttot;j++) {
1.125     ng       1181: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1182: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1183: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1184: 			if (points == "") {
1.125     ng       1185: 			    var name = formname["name"+i].value;
1.129     ng       1186: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1187: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1188: 					       ", part "+partid+". Continue?");
1.71      ng       1189: 			    if (resp == false) {
1.125     ng       1190: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1191: 				return false;
                   1192: 			    }
                   1193: 			}
                   1194: 		    }
                   1195: 		    
                   1196: 		}
                   1197: 	    }
                   1198: 	    
                   1199: 	}
1.121     ng       1200: 	if (val == "Grade Student") {
                   1201: 	    formname.showgrading.value = "yes";
                   1202: 	    if (formname.Status.value == "") {
                   1203: 		formname.Status.value = "Active";
                   1204: 	    }
                   1205: 	    formname.studentNo.value = total;
                   1206: 	}
1.120     ng       1207: 	formname.submit();
                   1208:     }
                   1209: 
1.71      ng       1210: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1211:     function checkSubmitPage(formname,total) {
                   1212: 	noscore = new Array(100);
                   1213: 	var ptr = 0;
                   1214: 	for (i=1;i<total;i++) {
1.125     ng       1215: 	    var partid = formname["q_"+i].value;
1.127     ng       1216: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1217: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1218: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1219: 		if (points == "" && status != "correct_by_student") {
                   1220: 		    noscore[ptr] = i;
                   1221: 		    ptr++;
                   1222: 		}
                   1223: 	    }
                   1224: 	}
                   1225: 	if (ptr != 0) {
                   1226: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1227: 	    var prolist = "";
                   1228: 	    if (ptr == 1) {
                   1229: 		prolist = noscore[0];
                   1230: 	    } else {
                   1231: 		var i = 0;
                   1232: 		while (i < ptr-1) {
                   1233: 		    prolist += noscore[i]+", ";
                   1234: 		    i++;
                   1235: 		}
                   1236: 		prolist += "and "+noscore[i];
                   1237: 	    }
                   1238: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1239: 	    if (resp == false) {
                   1240: 		return false;
                   1241: 	    }
                   1242: 	}
1.45      ng       1243: 
1.71      ng       1244: 	formname.submit();
                   1245:     }
                   1246: </script>
                   1247: SUBJAVASCRIPT
                   1248: }
1.45      ng       1249: 
1.71      ng       1250: #--- javascript for essay type problem --
                   1251: sub sub_page_kw_js {
                   1252:     my $request = shift;
1.80      ng       1253:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1254:     &commonJSfunctions($request);
1.350     albertel 1255: 
1.351     albertel 1256:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1257:     <script text="text/javascript">
                   1258:     function checkInput() {
                   1259:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1260:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1261:       var usrctr = document.msgcenter.usrctr.value;
                   1262:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1263:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1264: 
                   1265:       var msgchk = "";
                   1266:       if (document.msgcenter.subchk.checked) {
                   1267:          msgchk = "msgsub,";
                   1268:       }
                   1269:       var includemsg = 0;
                   1270:       for (var i=1; i<=nmsg; i++) {
                   1271:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1272:           var frmmsg = document.msgcenter["msg"+i];
                   1273:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1274:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1275:           showflg.value = "1";
                   1276:           var chkbox = document.msgcenter["msgn"+i];
                   1277:           if (chkbox.checked) {
                   1278:              msgchk += "savemsg"+i+",";
                   1279:              includemsg = 1;
                   1280:           }
                   1281:       }
                   1282:       if (document.msgcenter.newmsgchk.checked) {
                   1283:          msgchk += "newmsg"+usrctr;
                   1284:          includemsg = 1;
                   1285:       }
                   1286:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1287:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1288:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1289:       includemsg.value = msgchk;
                   1290: 
                   1291:       self.close()
                   1292: 
                   1293:     }
                   1294:     </script>
                   1295: INNERJS
                   1296: 
1.351     albertel 1297:     my $inner_js_highlight_central=<<INNERJS;
                   1298:  <script type="text/javascript">
                   1299:     function updateChoice(flag) {
                   1300:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1301:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1302:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1303:       opener.document.SCORE.refresh.value = "on";
                   1304:       if (opener.document.SCORE.keywords.value!=""){
                   1305:          opener.document.SCORE.submit();
                   1306:       }
                   1307:       self.close()
                   1308:     }
                   1309: </script>
                   1310: INNERJS
                   1311: 
                   1312:     my $start_page_msg_central = 
                   1313:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1314: 				       {'js_ready'  => 1,
                   1315: 					'only_body' => 1,
                   1316: 					'bgcolor'   =>'#FFFFFF',});
                   1317:     my $end_page_msg_central = 
                   1318: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1319: 
                   1320: 
                   1321:     my $start_page_highlight_central = 
                   1322:         &Apache::loncommon::start_page('Highlight Central',
                   1323: 				       $inner_js_highlight_central,
1.350     albertel 1324: 				       {'js_ready'  => 1,
                   1325: 					'only_body' => 1,
                   1326: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1327:     my $end_page_highlight_central = 
1.350     albertel 1328: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1329: 
1.219     www      1330:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1331:     $docopen=~s/^document\.//;
1.71      ng       1332:     $request->print(<<SUBJAVASCRIPT);
                   1333: <script type="text/javascript" language="javascript">
1.45      ng       1334: 
1.44      ng       1335: //===================== Show list of keywords ====================
1.122     ng       1336:   function keywords(formname) {
                   1337:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1338:     if (nret==null) return;
1.122     ng       1339:     formname.keywords.value = nret;
1.44      ng       1340: 
1.122     ng       1341:     if (formname.keywords.value != "") {
1.128     ng       1342: 	formname.refresh.value = "on";
1.122     ng       1343: 	formname.submit();
1.44      ng       1344:     }
                   1345:     return;
                   1346:   }
                   1347: 
                   1348: //===================== Script to view submitted by ==================
                   1349:   function viewSubmitter(submitter) {
                   1350:     document.SCORE.refresh.value = "on";
                   1351:     document.SCORE.NCT.value = "1";
                   1352:     document.SCORE.unamedom0.value = submitter;
                   1353:     document.SCORE.submit();
                   1354:     return;
                   1355:   }
                   1356: 
                   1357: //===================== Script to add keyword(s) ==================
                   1358:   function getSel() {
                   1359:     if (document.getSelection) txt = document.getSelection();
                   1360:     else if (document.selection) txt = document.selection.createRange().text;
                   1361:     else return;
                   1362:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1363:     if (cleantxt=="") {
1.46      ng       1364: 	alert("Please select a word or group of words from document and then click this link.");
1.44      ng       1365: 	return;
                   1366:     }
                   1367:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1368:     if (nret==null) return;
1.127     ng       1369:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1370:     if (document.SCORE.keywords.value != "") {
1.127     ng       1371: 	document.SCORE.refresh.value = "on";
1.44      ng       1372: 	document.SCORE.submit();
                   1373:     }
                   1374:     return;
                   1375:   }
                   1376: 
                   1377: //====================== Script for composing message ==============
1.80      ng       1378:    // preload images
                   1379:    img1 = new Image();
                   1380:    img1.src = "$iconpath/mailbkgrd.gif";
                   1381:    img2 = new Image();
                   1382:    img2.src = "$iconpath/mailto.gif";
                   1383: 
1.44      ng       1384:   function msgCenter(msgform,usrctr,fullname) {
                   1385:     var Nmsg  = msgform.savemsgN.value;
                   1386:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1387:     var subject = msgform.msgsub.value;
1.127     ng       1388:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1389:     re = /msgsub/;
                   1390:     var shwsel = "";
                   1391:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1392:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1393:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1394:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1395: 	var testmsg = "savemsg"+i+",";
                   1396: 	re = new RegExp(testmsg,"g");
1.44      ng       1397: 	shwsel = "";
                   1398: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1399: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1400: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1401: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1402: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1403:     }
1.125     ng       1404:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1405:     shwsel = "";
                   1406:     re = /newmsg/;
                   1407:     if (re.test(msgchk)) { shwsel = "checked" }
                   1408:     newMsg(newmsg,shwsel);
                   1409:     msgTail(); 
                   1410:     return;
                   1411:   }
                   1412: 
1.123     ng       1413:   function checkEntities(strx) {
                   1414:     if (strx.length == 0) return strx;
                   1415:     var orgStr = ["&", "<", ">", '"']; 
                   1416:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1417:     var counter = 0;
                   1418:     while (counter < 4) {
                   1419: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1420: 	counter++;
                   1421:     }
                   1422:     return strx;
                   1423:   }
                   1424: 
                   1425:   function strReplace(strx, orgStr, newStr) {
                   1426:     return strx.split(orgStr).join(newStr);
                   1427:   }
                   1428: 
1.44      ng       1429:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1430:     var height = 70*Nmsg+250;
1.44      ng       1431:     var scrollbar = "no";
                   1432:     if (height > 600) {
                   1433: 	height = 600;
                   1434: 	scrollbar = "yes";
                   1435:     }
1.118     ng       1436:     var xpos = (screen.width-600)/2;
                   1437:     xpos = (xpos < 0) ? '0' : xpos;
                   1438:     var ypos = (screen.height-height)/2-30;
                   1439:     ypos = (ypos < 0) ? '0' : ypos;
                   1440: 
1.206     albertel 1441:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1442:     pWin.focus();
                   1443:     pDoc = pWin.document;
1.219     www      1444:     pDoc.$docopen;
1.351     albertel 1445:     pDoc.write('$start_page_msg_central');
1.76      ng       1446: 
                   1447:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1448:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.398     albertel 1449:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"</span></h3><br /><br />");
1.76      ng       1450: 
                   1451:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1452:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
                   1453:     pDoc.write("<td><b>Type</b></td><td><b>Include</b></td><td><b>Message</td></tr>");
1.44      ng       1454: }
                   1455:     function displaySubject(msg,shwsel) {
1.76      ng       1456:     pDoc = pWin.document;
                   1457:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1458:     pDoc.write("<td>Subject</td>");
                   1459:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1460:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"></td></tr>");
1.44      ng       1461: }
                   1462: 
1.72      ng       1463:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1464:     pDoc = pWin.document;
                   1465:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1466:     pDoc.write("<td align=\\"center\\">"+ctr+"</td>");
                   1467:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1468:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"</textarea></td></tr>");
1.44      ng       1469: }
                   1470: 
                   1471:   function newMsg(newmsg,shwsel) {
1.76      ng       1472:     pDoc = pWin.document;
                   1473:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1474:     pDoc.write("<td align=\\"center\\">New</td>");
                   1475:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1476:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"</textarea></td></tr>");
1.44      ng       1477: }
                   1478: 
                   1479:   function msgTail() {
1.76      ng       1480:     pDoc = pWin.document;
                   1481:     pDoc.write("</table>");
                   1482:     pDoc.write("</td></tr></table>&nbsp;");
                   1483:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
1.326     albertel 1484:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       1485:     pDoc.write("</form>");
1.351     albertel 1486:     pDoc.write('$end_page_msg_central');
1.128     ng       1487:     pDoc.close();
1.44      ng       1488: }
                   1489: 
                   1490: //====================== Script for keyword highlight options ==============
                   1491:   function kwhighlight() {
                   1492:     var kwclr    = document.SCORE.kwclr.value;
                   1493:     var kwsize   = document.SCORE.kwsize.value;
                   1494:     var kwstyle  = document.SCORE.kwstyle.value;
                   1495:     var redsel = "";
                   1496:     var grnsel = "";
                   1497:     var blusel = "";
                   1498:     if (kwclr=="red")   {var redsel="checked"};
                   1499:     if (kwclr=="green") {var grnsel="checked"};
                   1500:     if (kwclr=="blue")  {var blusel="checked"};
                   1501:     var sznsel = "";
                   1502:     var sz1sel = "";
                   1503:     var sz2sel = "";
                   1504:     if (kwsize=="0")  {var sznsel="checked"};
                   1505:     if (kwsize=="+1") {var sz1sel="checked"};
                   1506:     if (kwsize=="+2") {var sz2sel="checked"};
                   1507:     var synsel = "";
                   1508:     var syisel = "";
                   1509:     var sybsel = "";
                   1510:     if (kwstyle=="")    {var synsel="checked"};
                   1511:     if (kwstyle=="<i>") {var syisel="checked"};
                   1512:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1513:     highlightCentral();
                   1514:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1515:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1516:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1517:     highlightend();
                   1518:     return;
                   1519:   }
                   1520: 
                   1521:   function highlightCentral() {
1.76      ng       1522: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1523:     var xpos = (screen.width-400)/2;
                   1524:     xpos = (xpos < 0) ? '0' : xpos;
                   1525:     var ypos = (screen.height-330)/2-30;
                   1526:     ypos = (ypos < 0) ? '0' : ypos;
                   1527: 
1.206     albertel 1528:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1529:     hwdWin.focus();
                   1530:     var hDoc = hwdWin.document;
1.219     www      1531:     hDoc.$docopen;
1.351     albertel 1532:     hDoc.write('$start_page_highlight_central');
1.76      ng       1533:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.398     albertel 1534:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options</span></h3><br /><br />");
1.76      ng       1535: 
                   1536:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1537:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
                   1538:     hDoc.write("<td><b>Text Color</b></td><td><b>Font Size</b></td><td><b>Font Style</td></tr>");
1.44      ng       1539:   }
                   1540: 
                   1541:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1542:     var hDoc = hwdWin.document;
                   1543:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1544:     hDoc.write("<td align=\\"left\\">");
                   1545:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"</td>");
                   1546:     hDoc.write("<td align=\\"left\\">");
                   1547:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"</td>");
                   1548:     hDoc.write("<td align=\\"left\\">");
                   1549:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"</td>");
                   1550:     hDoc.write("</tr>");
1.44      ng       1551:   }
                   1552: 
                   1553:   function highlightend() { 
1.76      ng       1554:     var hDoc = hwdWin.document;
                   1555:     hDoc.write("</table>");
                   1556:     hDoc.write("</td></tr></table>&nbsp;");
                   1557:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
1.326     albertel 1558:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       1559:     hDoc.write("</form>");
1.351     albertel 1560:     hDoc.write('$end_page_highlight_central');
1.128     ng       1561:     hDoc.close();
1.44      ng       1562:   }
                   1563: 
                   1564: </script>
                   1565: SUBJAVASCRIPT
                   1566: }
                   1567: 
1.349     albertel 1568: sub get_increment {
1.348     bowersj2 1569:     my $increment = $env{'form.increment'};
                   1570:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1571:         $increment != .1) {
                   1572:         $increment = 1;
                   1573:     }
                   1574:     return $increment;
                   1575: }
                   1576: 
1.71      ng       1577: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1578: sub gradeBox {
1.322     albertel 1579:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1580:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1581: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       1582: 	'/check.gif" height="16" border="0" />';
                   1583:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
                   1584:     my $wgtmsg = ($wgt > 0 ? '(problem weight)' : 
1.398     albertel 1585: 		  '<span class="LC_info">problem weight assigned by computer</span>');
1.71      ng       1586:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1587:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1588: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1589:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.324     albertel 1590:     my $display_part=&get_display_part($partid,$symb);
1.270     albertel 1591:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1592: 				       [$partid]);
                   1593:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1594:     if ($last_resets{$partid}) {
                   1595:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1596:     }
1.71      ng       1597:     $result.='<table border="0"><tr><td>'.
1.207     albertel 1598: 	'<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
1.71      ng       1599:     my $ctr = 0;
1.348     bowersj2 1600:     my $thisweight = 0;
1.349     albertel 1601:     my $increment = &get_increment();
1.71      ng       1602:     $result.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1603:     while ($thisweight<=$wgt) {
1.381     albertel 1604: 	$result.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.71      ng       1605: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1606: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1607: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.71      ng       1608: 	$result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1609:         $thisweight += $increment;
1.71      ng       1610: 	$ctr++;
                   1611:     }
                   1612:     $result.='</tr></table>';
                   1613:     $result.='</td><td>&nbsp;<b>or</b>&nbsp;</td>'."\n";
                   1614:     $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
                   1615: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
                   1616: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
                   1617: 	$wgt.')" /></td>'."\n";
                   1618:     $result.='<td>/'.$wgt.' '.$wgtmsg.
                   1619: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
                   1620: 	' </td><td>'."\n";
                   1621:     $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
                   1622: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
                   1623:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.384     albertel 1624: 	$result.='<option></option>'.
1.401     albertel 1625: 	    '<option selected="selected">excused</option>';
1.71      ng       1626:     } else {
1.401     albertel 1627: 	$result.='<option selected="selected"></option>'.
1.125     ng       1628: 	    '<option>excused</option>';
1.71      ng       1629:     }
1.125     ng       1630:     $result.='<option>reset status</option></select>'."\n";
1.381     albertel 1631:     $result.="&nbsp;&nbsp;\n";
1.71      ng       1632:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1633: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1634: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1635: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1636:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1637:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1638:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1639:         $aggtries.'" />'."\n";
1.71      ng       1640:     $result.='</td></tr></table>'."\n";
1.323     banghart 1641:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1.318     banghart 1642:     return $result;
                   1643: }
1.322     albertel 1644: 
                   1645: sub handback_box {
1.323     banghart 1646:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1.324     albertel 1647:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.323     banghart 1648:     my (@respids);
1.375     albertel 1649:      my @part_response_id = &flatten_responseType($responseType);
                   1650:     foreach my $part_response_id (@part_response_id) {
                   1651:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1652:         if ($part eq $partid) {
1.375     albertel 1653:             push(@respids,$resp);
1.323     banghart 1654:         }
                   1655:     }
1.318     banghart 1656:     my $result;
1.323     banghart 1657:     foreach my $respid (@respids) {
1.322     albertel 1658: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1659: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1660: 	next if (!@$files);
                   1661: 	my $file_counter = 1;
1.313     banghart 1662: 	foreach my $file (@$files) {
1.368     banghart 1663: 	    if ($file =~ /\/portfolio\//) {
                   1664:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1665:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1666:     	        $file_disp = "$name.$ext";
                   1667:     	        $file = $file_path.$file_disp;
                   1668:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1669:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1670:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1671:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.369     banghart 1672:     	        $result.='(File will be uploaded when you click on Save & Next below.)<br />';
1.368     banghart 1673:     	        $file_counter++;
                   1674: 	    }
1.322     albertel 1675: 	}
1.313     banghart 1676:     }
1.318     banghart 1677:     return $result;    
1.71      ng       1678: }
1.44      ng       1679: 
1.58      albertel 1680: sub show_problem {
1.382     albertel 1681:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1682:     my $rendered;
1.382     albertel 1683:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1684:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1685:     if ($mode eq 'both' or $mode eq 'text') {
                   1686: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1687: 						       $env{'request.course.id'},
                   1688: 						       undef,\%form);
1.144     albertel 1689:     }
1.58      albertel 1690:     if ($removeform) {
                   1691: 	$rendered=~s|<form(.*?)>||g;
                   1692: 	$rendered=~s|</form>||g;
1.374     albertel 1693: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1694:     }
1.144     albertel 1695:     my $companswer;
                   1696:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1697: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1698: 	$companswer=
                   1699: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1700: 						    $env{'request.course.id'},
                   1701: 						    %form);
1.144     albertel 1702:     }
1.58      albertel 1703:     if ($removeform) {
                   1704: 	$companswer=~s|<form(.*?)>||g;
                   1705: 	$companswer=~s|</form>||g;
1.144     albertel 1706: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1707:     }
                   1708:     my $result.='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1.71      ng       1709:     $result.='<table border="0" width="100%">';
1.144     albertel 1710:     if ($viewon) {
                   1711: 	$result.='<tr><td bgcolor="#e6ffff"><b> ';
                   1712: 	if ($mode eq 'both' or $mode eq 'text') {
                   1713: 	    $result.='View of the problem - ';
                   1714: 	} else {
                   1715: 	    $result.='Correct answer: ';
                   1716: 	}
1.257     albertel 1717: 	$result.=$env{'form.fullname'}.'</b></td></tr>';
1.144     albertel 1718:     }
                   1719:     if ($mode eq 'both') {
                   1720: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered.'<br />';
                   1721: 	$result.='<b>Correct answer:</b><br />'.$companswer;
                   1722:     } elsif ($mode eq 'text') {
                   1723: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered;
                   1724:     } elsif ($mode eq 'answer') {
                   1725: 	$result.='<tr><td bgcolor="#ffffff">'.$companswer;
                   1726:     }
1.58      albertel 1727:     $result.='</td></tr></table>';
                   1728:     $result.='</td></tr></table><br />';
1.71      ng       1729:     return $result;
1.58      albertel 1730: }
1.397     albertel 1731: 
1.396     banghart 1732: sub files_exist {
                   1733:     my ($r, $symb) = @_;
                   1734:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1735: 
1.396     banghart 1736:     foreach my $student (@students) {
                   1737:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1738:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1739: 					      $udom,$uname);
1.396     banghart 1740:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1741:         foreach my $submission (@$string) {
                   1742:             my ($partid,$respid) =
                   1743: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1744:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1745: 					   \%record);
                   1746:             return 1 if (@$files);
1.396     banghart 1747:         }
                   1748:     }
1.397     albertel 1749:     return 0;
1.396     banghart 1750: }
1.397     albertel 1751: 
1.394     banghart 1752: sub download_all_link {
                   1753:     my ($r,$symb) = @_;
1.395     albertel 1754:     my $all_students = 
                   1755: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1756: 
                   1757:     my $parts =
                   1758: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1759: 
1.394     banghart 1760:     my $identifier = &Apache::loncommon::get_cgi_id();
                   1761:     &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
                   1762:                             'cgi.'.$identifier.'.symb' => $symb,
1.395     albertel 1763:                             'cgi.'.$identifier.'.parts' => $parts,);
                   1764:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1765: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1766:     return
                   1767: }
1.395     albertel 1768: 
1.432     banghart 1769: sub build_section_inputs {
                   1770:     my $section_inputs;
                   1771:     if ($env{'form.section'} eq '') {
                   1772:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1773:     } else {
                   1774:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1775:         foreach my $section (@sections) {
1.432     banghart 1776:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1777:         }
                   1778:     }
                   1779:     return $section_inputs;
                   1780: }
                   1781: 
1.44      ng       1782: # --------------------------- show submissions of a student, option to grade 
                   1783: sub submission {
                   1784:     my ($request,$counter,$total) = @_;
                   1785: 
1.257     albertel 1786:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1787:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1788:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1789:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.324     albertel 1790:     my $symb = &get_symb($request); 
                   1791:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1792: 
                   1793:     if (!&canview($usec)) {
1.398     albertel 1794: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1795: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1796: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1797: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1798: 	return;
                   1799:     }
                   1800: 
1.257     albertel 1801:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1802:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1803:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1804:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1805:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1806: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1807: 	'/check.gif" height="16" border="0" />';
1.41      ng       1808: 
1.426     albertel 1809:     my %old_essays;
1.41      ng       1810:     # header info
                   1811:     if ($counter == 0) {
                   1812: 	&sub_page_js($request);
1.257     albertel 1813: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1814: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1815: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1816: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1817: 	    &download_all_link($request, $symb);
                   1818: 	}
1.398     albertel 1819: 	$request->print('<h3>&nbsp;<span class="LC_info">Submission Record</span></h3>'."\n".
                   1820: 			'<h4>&nbsp;<b>Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n");
1.118     ng       1821: 
1.257     albertel 1822: 	if ($env{'form.handgrade'} eq 'no') {
1.118     ng       1823: 	    my $checkMark='<br /><br />&nbsp;<b>Note:</b> Part(s) graded correct by the computer is marked with a '.
                   1824: 		$checkIcon.' symbol.'."\n";
                   1825: 	    $request->print($checkMark);
                   1826: 	}
1.41      ng       1827: 
1.44      ng       1828: 	# option to display problem, only once else it cause problems 
                   1829:         # with the form later since the problem has a form.
1.257     albertel 1830: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1831: 	    my $mode;
1.257     albertel 1832: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1833: 		$mode='both';
1.257     albertel 1834: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1835: 		$mode='text';
1.257     albertel 1836: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1837: 		$mode='answer';
                   1838: 	    }
1.329     albertel 1839: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1840: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1841: 	}
1.441     www      1842: 
1.44      ng       1843: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1844:         # if this subroutine has been called once.
1.41      ng       1845: 	my %keyhash = ();
1.257     albertel 1846: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1847: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1848: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1849: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1850: 
1.257     albertel 1851: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1852: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1853: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1854: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1855: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1856: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1857: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1858: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1859: 	}
1.257     albertel 1860: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1861: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1862: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1863: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1864: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 1865: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1866: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1867: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1868: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1869: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1870: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1871: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1872: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1873: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1874: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1875: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1876: 			&build_section_inputs().
1.326     albertel 1877: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1878: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1879: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1880: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1881: 	if ($env{'form.handgrade'} eq 'yes') {
                   1882: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1883: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1884: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1885: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1886: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1887: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1888: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1889: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1890: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1891: 	    }
1.123     ng       1892: 	}
1.41      ng       1893: 	
                   1894: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1895: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1896: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1897: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1898: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1899: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1900: 		'" />'."\n".
                   1901: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1902: 	    $cts++;
                   1903: 	}
                   1904: 	$request->print($prnmsg);
1.32      ng       1905: 
1.257     albertel 1906: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      1907: #
                   1908: # Print out the keyword options line
                   1909: #
1.41      ng       1910: 	    $request->print(<<KEYWORDS);
1.38      ng       1911: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 1912: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.38      ng       1913: <a href="#" onMouseDown="javascript:getSel(); return false"
                   1914:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 1915: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       1916: KEYWORDS
1.88      www      1917: #
                   1918: # Load the other essays for similarity check
                   1919: #
1.324     albertel 1920:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 1921: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      1922: 	    $apath=&escape($apath);
1.88      www      1923: 	    $apath=~s/\W/\_/gs;
1.426     albertel 1924: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       1925:         }
                   1926:     }
1.44      ng       1927: 
1.441     www      1928: # This is where output for one specific student would start
                   1929:     my $bgcolor='#DDEEDD';
                   1930:     if (int($counter/2) eq $counter) { $bgcolor='#DDDDEE'; }
                   1931:     $request->print("\n\n".
                   1932:                     '<p><table border="2"><tr><th bgcolor="'.$bgcolor.'">'.$env{'form.fullname'}.'</th></tr><tr><td bgcolor="'.$bgcolor.'">');
                   1933: 
1.257     albertel 1934:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 1935: 	my $mode;
1.257     albertel 1936: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 1937: 	    $mode='both';
1.257     albertel 1938: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 1939: 	    $mode='text';
1.257     albertel 1940: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 1941: 	    $mode='answer';
                   1942: 	}
1.329     albertel 1943: 	&Apache::lonxml::clear_problem_counter();
1.144     albertel 1944: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode));
1.58      albertel 1945:     }
1.144     albertel 1946: 
1.257     albertel 1947:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 1948:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.41      ng       1949: 
1.44      ng       1950:     # Display student info
1.41      ng       1951:     $request->print(($counter == 0 ? '' : '<br />'));
1.326     albertel 1952:     my $result='<table border="0" width="100%"><tr><td bgcolor="#777777">'."\n".
                   1953: 	'<table border="0" width="100%"><tr bgcolor="#edffff"><td>'."\n";
1.44      ng       1954: 
1.257     albertel 1955:     $result.='<b>Fullname: </b>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'<br />'."\n";
1.45      ng       1956:     $result.='<input type="hidden" name="name'.$counter.
1.257     albertel 1957: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
1.41      ng       1958: 
1.118     ng       1959:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.45      ng       1960:     my @col_fullnames;
1.56      matthew  1961:     my ($classlist,$fullname);
1.257     albertel 1962:     if ($env{'form.handgrade'} eq 'yes') {
1.80      ng       1963: 	($classlist,undef,$fullname) = &getclasslist('all','0');
1.41      ng       1964: 	for (keys (%$handgrade)) {
1.44      ng       1965: 	    my $ncol = &Apache::lonnet::EXT('resource.'.$_.
1.57      matthew  1966: 					    '.maxcollaborators',
                   1967:                                             $symb,$udom,$uname);
                   1968: 	    next if ($ncol <= 0);
                   1969:             s/\_/\./g;
                   1970:             next if ($record{'resource.'.$_.'.collaborators'} eq '');
1.86      ng       1971:             my @goodcollaborators = ();
                   1972:             my @badcollaborators  = ();
                   1973: 	    foreach (split(/,?\s+/,$record{'resource.'.$_.'.collaborators'})) { 
                   1974: 		$_ =~ s/[\$\^\(\)]//g;
                   1975: 		next if ($_ eq '');
1.80      ng       1976: 		my ($co_name,$co_dom) = split /\@|:/,$_;
1.86      ng       1977: 		$co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
1.80      ng       1978: 		next if ($co_name eq $uname && $co_dom eq $udom);
1.86      ng       1979: 		# Doing this grep allows 'fuzzy' specification
                   1980: 		my @Matches = grep /^$co_name:$co_dom$/i,keys %$classlist;
                   1981: 		if (! scalar(@Matches)) {
                   1982: 		    push @badcollaborators,$_;
                   1983: 		} else {
                   1984: 		    push @goodcollaborators, @Matches;
                   1985: 		}
1.80      ng       1986: 	    }
1.86      ng       1987:             if (scalar(@goodcollaborators) != 0) {
1.57      matthew  1988:                 $result.='<b>Collaborators: </b>';
1.86      ng       1989:                 foreach (@goodcollaborators) {
                   1990: 		    my ($lastname,$givenn) = split(/,/,$$fullname{$_});
                   1991: 		    push @col_fullnames, $givenn.' '.$lastname;
                   1992: 		    $result.=$$fullname{$_}.'&nbsp; &nbsp; &nbsp;';
                   1993: 		}
1.57      matthew  1994:                 $result.='<br />'."\n";
1.150     albertel 1995: 		my ($part)=split(/\./,$_);
1.86      ng       1996: 		$result.='<input type="hidden" name="collaborator'.$counter.
1.150     albertel 1997: 		    '" value="'.$part.':'.(join ':',@goodcollaborators).'" />'.
                   1998: 		    "\n";
1.86      ng       1999: 	    }
                   2000: 	    if (scalar(@badcollaborators) > 0) {
                   2001: 		$result.='<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   2002: 		$result.='This student has submitted ';
                   2003: 		$result.=(scalar(@badcollaborators) == 1) ? 'an invalid collaborator' : 'invalid collaborators';
                   2004: 		$result .= ': '.join(', ',@badcollaborators);
                   2005: 		$result .= '</td></tr></table>';
                   2006: 	    }         
                   2007: 	    if (scalar(@badcollaborators > $ncol)) {
                   2008: 		$result .= '<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   2009: 		$result .= 'This student has submitted too many '.
                   2010: 		    'collaborators.  Maximum is '.$ncol.'.';
                   2011: 		$result .= '</td></tr></table>';
                   2012: 	    }
1.41      ng       2013: 	}
                   2014:     }
1.44      ng       2015:     $request->print($result."\n");
1.33      ng       2016: 
1.44      ng       2017:     # print student answer/submission
                   2018:     # Options are (1) Handgaded submission only
                   2019:     #             (2) Last submission, includes submission that is not handgraded 
                   2020:     #                  (for multi-response type part)
                   2021:     #             (3) Last submission plus the parts info
                   2022:     #             (4) The whole record for this student
1.257     albertel 2023:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2024: 	my ($string,$timestamp)= &get_last_submission(\%record);
                   2025: 	my $lastsubonly=''.
                   2026: 	    ($$timestamp eq '' ? '' : '<b>Date Submitted:</b> '.
                   2027: 	     $$timestamp)."</td></tr>\n";
                   2028: 	if ($$timestamp eq '') {
                   2029: 	    $lastsubonly.='<tr><td bgcolor="#ffffe6">'.$$string[0]; 
                   2030: 	} else {
                   2031: 	    my %seenparts;
1.375     albertel 2032: 	    my @part_response_id = &flatten_responseType($responseType);
                   2033: 	    foreach my $part (@part_response_id) {
1.393     albertel 2034: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2035: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2036: 
1.375     albertel 2037: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2038: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2039: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2040: 		    if (exists($seenparts{$partid})) { next; }
                   2041: 		    $seenparts{$partid}=1;
1.207     albertel 2042: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2043: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2044: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2045: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2046: 			'\');" target="_self">'.
1.257     albertel 2047: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2048: 		    $request->print($submitby);
                   2049: 		    next;
                   2050: 		}
                   2051: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2052: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.207     albertel 2053: 		    $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
1.398     albertel 2054: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
                   2055: 			' )</span>&nbsp; &nbsp;'.
                   2056: 			'<span class="LC_warning">Nothing submitted - no attempts</span><br /><br />';
1.151     albertel 2057: 		    next;
                   2058: 		}
                   2059: 		foreach (@$string) {
                   2060: 		    my ($partid,$respid) = /^resource\.([^\.]*)\.([^\.]*)\.submission/;
1.375     albertel 2061: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.151     albertel 2062: 		    my ($ressub,$subval) = split(/:/,$_,2);
                   2063: 		    # Similarity check
                   2064: 		    my $similar='';
1.257     albertel 2065: 		    if($env{'form.checkPlag'}){
1.151     albertel 2066: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2067: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2068: 			if ($osim) {
                   2069: 			    $osim=int($osim*100.0);
1.426     albertel 2070: 			    my %old_course_desc = 
                   2071: 				&Apache::lonnet::coursedescription($ocrsid,
                   2072: 								   {'one_time' => 1});
                   2073: 
                   2074: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
1.427     albertel 2075: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
1.426     albertel 2076: 				    $osim,
                   2077: 				    &Apache::loncommon::plainname($oname,$odom),
1.427     albertel 2078: 				    $oname,$odom,
1.426     albertel 2079: 				    $old_course_desc{'description'},
1.427     albertel 2080: 				    $old_course_desc{'num'},
1.426     albertel 2081: 				    $old_course_desc{'domain'}).
1.398     albertel 2082: 				'</span></h3><blockquote><i>'.
1.151     albertel 2083: 				&keywords_highlight($oessay).
                   2084: 				'</i></blockquote><hr />';
                   2085: 			}
1.150     albertel 2086: 		    }
1.151     albertel 2087: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2088: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2089: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2090: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2091: 			my $display_part=&get_display_part($partid,$symb);
1.403     albertel 2092: 			$lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
                   2093: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
1.398     albertel 2094: 			    ' )</span>&nbsp; &nbsp;';
1.313     banghart 2095: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2096: 			if (@$files) {
1.398     albertel 2097: 			    $lastsubonly.='<br /><span class="LC_warning">Like all files provided by users, this file may contain virusses</span><br />';
1.303     banghart 2098: 			    my $file_counter = 0;
1.313     banghart 2099: 			    foreach my $file (@$files) {
1.303     banghart 2100: 			        $file_counter ++;
1.232     albertel 2101: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.335     albertel 2102: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
1.232     albertel 2103: 			    }
1.236     albertel 2104: 			    $lastsubonly.='<br />';
1.41      ng       2105: 			}
1.151     albertel 2106: 			$lastsubonly.='<b>Submitted Answer: </b>'.
                   2107: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2108: 					 $respid,\%record,$order);
                   2109: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.41      ng       2110: 		    }
                   2111: 		}
                   2112: 	    }
1.151     albertel 2113: 	}
                   2114: 	$lastsubonly.='</td></tr><tr bgcolor="#ffffff"><td>'."\n";
                   2115: 	$request->print($lastsubonly);
1.257     albertel 2116:     } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2117: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2118: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2119:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2120: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2121: 								 $env{'request.course.id'},
1.44      ng       2122: 								 $last,'.submission',
                   2123: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2124:     }
1.120     ng       2125: 
1.121     ng       2126:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2127: 	.$udom.'" />'."\n");
1.41      ng       2128:     
1.44      ng       2129:     # return if view submission with no grading option
1.257     albertel 2130:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2131: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       2132: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2133: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.169     albertel 2134: 	$toGrade.='</td></tr></table></td></tr></table>'."\n";
1.257     albertel 2135: 	if (($env{'form.command'} eq 'submission') || 
                   2136: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2137: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2138: 	}
1.180     albertel 2139: 	$request->print($toGrade);
1.41      ng       2140: 	return;
1.180     albertel 2141:     } else {
                   2142: 	$request->print('</td></tr></table></td></tr></table>'."\n");
1.41      ng       2143:     }
1.33      ng       2144: 
1.121     ng       2145:     # essay grading message center
1.257     albertel 2146:     if ($env{'form.handgrade'} eq 'yes') {
                   2147: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2148: 	my $msgfor = $givenn.' '.$lastname;
                   2149: 	if (scalar(@col_fullnames) > 0) {
                   2150: 	    my $lastone = pop @col_fullnames;
                   2151: 	    $msgfor .= ', '.(join ', ',@col_fullnames).' and '.$lastone.'.';
                   2152: 	}
                   2153: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.121     ng       2154: 	$result='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   2155: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2156: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2157: 	    ',\''.$msgfor.'\');" target="_self">'.
1.350     albertel 2158: 	    &mt('Compose message to student').(scalar(@col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
                   2159: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2160: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2161: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2162: 	    '<br />&nbsp;('.
                   2163: 	    &mt('Message will be sent when you click on Save & Next below.').")\n";
1.121     ng       2164: 	$request->print($result);
1.118     ng       2165:     }
1.300     albertel 2166:     if ($perm{'vgr'}) {
1.297     www      2167: 	$request->print('<br />'.
1.300     albertel 2168: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   2169: 						   $uname,$udom,'check'));
1.297     www      2170:     }
1.300     albertel 2171:     if ($perm{'opa'}) {
1.297     www      2172: 	$request->print('<br />'.
1.300     albertel 2173: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   2174: 					 $uname,$udom,$symb,'check'));
1.297     www      2175:     }
1.41      ng       2176: 
                   2177:     my %seen = ();
                   2178:     my @partlist;
1.129     ng       2179:     my @gradePartRespid;
1.375     albertel 2180:     my @part_response_id = &flatten_responseType($responseType);
                   2181:     foreach my $part_response_id (@part_response_id) {
                   2182:     	my ($partid,$respid) = @{ $part_response_id };
                   2183: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2184: 	next if ($seen{$partid} > 0);
1.41      ng       2185: 	$seen{$partid}++;
1.393     albertel 2186: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2187: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.41      ng       2188: 	push @partlist,$partid;
1.129     ng       2189: 	push @gradePartRespid,$partid.'.'.$respid;
1.322     albertel 2190: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2191:     }
1.45      ng       2192:     $result='<input type="hidden" name="partlist'.$counter.
                   2193: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2194:     $result.='<input type="hidden" name="gradePartRespid'.
                   2195: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2196:     my $ctr = 0;
                   2197:     while ($ctr < scalar(@partlist)) {
                   2198: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2199: 	    $partlist[$ctr].'" />'."\n";
                   2200: 	$ctr++;
                   2201:     }
                   2202:     $request->print($result.'</td></tr></table></td></tr></table>'."\n");
1.41      ng       2203: 
1.441     www      2204: # Done with printing info for one student
                   2205: 
                   2206:     $request->print('</td></tr></table></p>');
                   2207: 
                   2208: 
1.41      ng       2209:     # print end of form
                   2210:     if ($counter == $total) {
1.297     www      2211: 	my $endform='<table border="0"><tr><td>'."\n";
1.119     ng       2212: 	$endform.='<input type="button" value="Save & Next" '.
                   2213: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2214: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2215: 	my $ntstu ='<select name="NTSTU">'.
                   2216: 	    '<option>1</option><option>2</option>'.
                   2217: 	    '<option>3</option><option>5</option>'.
                   2218: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2219: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2220: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.119     ng       2221: 	$endform.=$ntstu.'student(s) &nbsp;&nbsp;';
1.126     ng       2222: 	$endform.='<input type="button" value="Previous" '.
1.417     albertel 2223: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.126     ng       2224: 	    '<input type="button" value="Next" '.
1.417     albertel 2225: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.126     ng       2226: 	$endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
1.349     albertel 2227:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2228:             "' name='increment' />";
1.45      ng       2229: 	$endform.='</td><tr></table></form>';
1.324     albertel 2230: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2231: 	$request->print($endform);
                   2232:     }
                   2233:     return '';
1.38      ng       2234: }
                   2235: 
1.44      ng       2236: #--- Retrieve the last submission for all the parts
1.38      ng       2237: sub get_last_submission {
1.119     ng       2238:     my ($returnhash)=@_;
1.46      ng       2239:     my (@string,$timestamp);
1.119     ng       2240:     if ($$returnhash{'version'}) {
1.46      ng       2241: 	my %lasthash=();
                   2242: 	my ($version);
1.119     ng       2243: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2244: 	    foreach my $key (sort(split(/\:/,
                   2245: 					$$returnhash{$version.':keys'}))) {
                   2246: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2247: 		$timestamp = 
                   2248: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
1.46      ng       2249: 	    }
                   2250: 	}
1.397     albertel 2251: 	foreach my $key (keys(%lasthash)) {
                   2252: 	    next if ($key !~ /\.submission$/);
                   2253: 
                   2254: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2255: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2256: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.397     albertel 2257: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
1.41      ng       2258: 	}
                   2259:     }
1.397     albertel 2260:     if (!@string) {
                   2261: 	$string[0] =
1.398     albertel 2262: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
1.397     albertel 2263:     }
                   2264:     return (\@string,\$timestamp);
1.38      ng       2265: }
1.35      ng       2266: 
1.44      ng       2267: #--- High light keywords, with style choosen by user.
1.38      ng       2268: sub keywords_highlight {
1.44      ng       2269:     my $string    = shift;
1.257     albertel 2270:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2271:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2272:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2273:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2274:     foreach my $keyword (@keylist) {
                   2275: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2276:     }
                   2277:     return $string;
1.38      ng       2278: }
1.36      ng       2279: 
1.44      ng       2280: #--- Called from submission routine
1.38      ng       2281: sub processHandGrade {
1.41      ng       2282:     my ($request) = shift;
1.324     albertel 2283:     my $symb   = &get_symb($request);
                   2284:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2285:     my $button = $env{'form.gradeOpt'};
                   2286:     my $ngrade = $env{'form.NCT'};
                   2287:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2288:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2289:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2290: 
1.44      ng       2291:     if ($button eq 'Save & Next') {
                   2292: 	my $ctr = 0;
                   2293: 	while ($ctr < $ngrade) {
1.257     albertel 2294: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2295: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2296: 	    if ($errorflag eq 'no_score') {
                   2297: 		$ctr++;
                   2298: 		next;
                   2299: 	    }
1.104     albertel 2300: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2301: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2302: 		$ctr++;
                   2303: 		next;
                   2304: 	    }
1.257     albertel 2305: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2306: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2307: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2308:             my ($feedurl,$showsymb) =
                   2309: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2310: 	    my $messagetail;
1.62      albertel 2311: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2312: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2313: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2314: 		$subject.=' ['.$restitle.']';
1.44      ng       2315: 		my (@msgnum) = split(/,/,$includemsg);
                   2316: 		foreach (@msgnum) {
1.257     albertel 2317: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2318: 		}
1.80      ng       2319: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2320: 		if ($env{'form.withgrades'.$ctr}) {
                   2321: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2322: 		    $messagetail = " for <a href=\"".
1.418     albertel 2323: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2324: 		}
                   2325: 		$msgstatus = 
                   2326:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2327: 						     $message.$messagetail,
1.418     albertel 2328:                                                      undef,$feedurl,undef,
1.386     raeburn  2329:                                                      undef,undef,$showsymb,
                   2330:                                                      $restitle);
                   2331: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
1.296     www      2332: 				$msgstatus);
1.44      ng       2333: 	    }
1.257     albertel 2334: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2335: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2336: 		foreach my $collabstr (@collabstrs) {
                   2337: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2338: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2339: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2340: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2341: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2342: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2343: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2344: 			    next;
1.418     albertel 2345: 			} elsif ($message ne '') {
                   2346: 			    my ($baseurl,$showsymb) = 
                   2347: 				&get_feedurl_and_symb($symb,$collaborator,
                   2348: 						      $udom);
                   2349: 			    if ($env{'form.withgrades'.$ctr}) {
                   2350: 				$messagetail = " for <a href=\"".
1.386     raeburn  2351:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2352: 			    }
1.418     albertel 2353: 			    $msgstatus = 
                   2354: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2355: 			}
1.44      ng       2356: 		    }
                   2357: 		}
                   2358: 	    }
                   2359: 	    $ctr++;
                   2360: 	}
                   2361:     }
                   2362: 
1.257     albertel 2363:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2364: 	# Keywords sorted in alphabatical order
1.257     albertel 2365: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2366: 	my %keyhash = ();
1.257     albertel 2367: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2368: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2369: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2370: 	$env{'form.keywords'} = join(' ',@keywords);
                   2371: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2372: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2373: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2374: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2375: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2376: 
                   2377: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2378: 	# New messages are saved in env for the next student.
1.119     ng       2379: 	# All messages are saved in nohist_handgrade.db
                   2380: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2381: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2382: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2383: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2384: 		$idx++;
                   2385: 	    }
                   2386: 	    $ctr++;
1.41      ng       2387: 	}
1.119     ng       2388: 	$ctr = 0;
                   2389: 	while ($ctr < $ngrade) {
1.257     albertel 2390: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2391: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2392: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2393: 		$idx++;
                   2394: 	    }
                   2395: 	    $ctr++;
1.41      ng       2396: 	}
1.257     albertel 2397: 	$env{'form.savemsgN'} = --$idx;
                   2398: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2399: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2400: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2401:     }
1.44      ng       2402:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2403:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2404:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2405: 	my ($ctr,$total) = (0,0);
                   2406: 	while ($ctr < $ngrade) {
1.257     albertel 2407: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2408: 	    $ctr++;
                   2409: 	}
1.257     albertel 2410: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2411: 	$ctr = 0;
                   2412: 	while ($ctr < $total) {
1.257     albertel 2413: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2414: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2415: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2416: 	    &submission($request,$ctr,$total-1);
1.41      ng       2417: 	    $ctr++;
                   2418: 	}
                   2419: 	return '';
                   2420:     }
1.36      ng       2421: 
1.121     ng       2422: # Go directly to grade student - from submission or link from chart page
1.120     ng       2423:     if ($button eq 'Grade Student') {
1.324     albertel 2424: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2425: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2426: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2427: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2428: 	&submission($request,0,0);
                   2429: 	return '';
                   2430:     }
                   2431: 
1.44      ng       2432:     # Get the next/previous one or group of students
1.257     albertel 2433:     my $firststu = $env{'form.unamedom0'};
                   2434:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2435:     my $ctr = 2;
1.41      ng       2436:     while ($laststu eq '') {
1.257     albertel 2437: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2438: 	$ctr++;
                   2439: 	$laststu = $firststu if ($ctr > $ngrade);
                   2440:     }
1.44      ng       2441: 
1.41      ng       2442:     my (@parsedlist,@nextlist);
                   2443:     my ($nextflg) = 0;
1.294     albertel 2444:     foreach (sort 
                   2445: 	     {
                   2446: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2447: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2448: 		 }
                   2449: 		 return $a cmp $b;
                   2450: 	     } (keys(%$fullname))) {
1.41      ng       2451: 	if ($nextflg == 1 && $button =~ /Next$/) {
                   2452: 	    push @parsedlist,$_;
                   2453: 	}
                   2454: 	$nextflg = 1 if ($_ eq $laststu);
                   2455: 	if ($button eq 'Previous') {
                   2456: 	    last if ($_ eq $firststu);
                   2457: 	    push @parsedlist,$_;
                   2458: 	}
                   2459:     }
                   2460:     $ctr = 0;
                   2461:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.324     albertel 2462:     my ($partlist) = &response_type($symb);
1.41      ng       2463:     foreach my $student (@parsedlist) {
1.257     albertel 2464: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2465: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2466: 	
                   2467: 	if ($submitonly eq 'queued') {
                   2468: 	    my %queue_status = 
                   2469: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2470: 							$udom,$uname);
                   2471: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2472: 	}
                   2473: 
1.156     albertel 2474: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2475: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2476: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2477: 	    my $submitted = 0;
1.248     albertel 2478: 	    my $ungraded = 0;
                   2479: 	    my $incorrect = 0;
1.145     albertel 2480: 	    foreach (keys(%status)) {
                   2481: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 2482: 		$ungraded = 1 if ($status{$_} =~ /^ungraded/);
                   2483: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
1.145     albertel 2484: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   2485: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2486: 		    $submitted = 0;
                   2487: 		}
1.41      ng       2488: 	    }
1.156     albertel 2489: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2490: 				     $submitonly eq 'incorrect' ||
                   2491: 				     $submitonly eq 'graded'));
1.248     albertel 2492: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2493: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2494: 	}
                   2495: 	push @nextlist,$student if ($ctr < $ntstu);
1.129     ng       2496: 	last if ($ctr == $ntstu);
1.41      ng       2497: 	$ctr++;
                   2498:     }
1.36      ng       2499: 
1.41      ng       2500:     $ctr = 0;
                   2501:     my $total = scalar(@nextlist)-1;
1.39      ng       2502: 
1.41      ng       2503:     foreach (sort @nextlist) {
                   2504: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2505: 	$env{'form.student'}  = $uname;
                   2506: 	$env{'form.userdom'}  = $udom;
                   2507: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2508: 	&submission($request,$ctr,$total);
                   2509: 	$ctr++;
                   2510:     }
                   2511:     if ($total < 0) {
1.398     albertel 2512: 	my $the_end = '<h3><span class="LC_info">LON-CAPA User Message</span></h3><br />'."\n";
1.41      ng       2513: 	$the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
                   2514: 	$the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
1.324     albertel 2515: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2516: 	$request->print($the_end);
                   2517:     }
                   2518:     return '';
1.38      ng       2519: }
1.36      ng       2520: 
1.44      ng       2521: #---- Save the score and award for each student, if changed
1.38      ng       2522: sub saveHandGrade {
1.324     albertel 2523:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2524:     my @version_parts;
1.104     albertel 2525:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2526: 					   $env{'request.course.id'});
1.104     albertel 2527:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2528:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2529:     my @parts_graded;
1.77      ng       2530:     my %newrecord  = ();
                   2531:     my ($pts,$wgt) = ('','');
1.269     raeburn  2532:     my %aggregate = ();
                   2533:     my $aggregateflag = 0;
1.301     albertel 2534:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2535:     foreach my $new_part (@parts) {
1.337     banghart 2536: 	#collaborator ($submi may vary for different parts
1.259     banghart 2537: 	if ($submitter && $new_part ne $part) { next; }
                   2538: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2539: 	if ($dropMenu eq 'excused') {
1.259     banghart 2540: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2541: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2542: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2543: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2544: 		}
1.364     banghart 2545: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2546: 	    }
1.125     ng       2547: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2548: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.197     albertel 2549: 	    foreach my $key (keys (%record)) {
1.259     banghart 2550: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2551: 	    }
1.259     banghart 2552: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2553: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2554:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2555: 
                   2556:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2557: 					       [$new_part]);
                   2558:             my $aggtries =$totaltries;
1.269     raeburn  2559:             if ($last_resets{$new_part}) {
1.270     albertel 2560:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2561: 					   $new_part);
1.269     raeburn  2562:             }
1.270     albertel 2563: 
                   2564:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2565:             if ($aggtries > 0) {
1.327     albertel 2566:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2567:                 $aggregateflag = 1;
                   2568:             }
1.125     ng       2569: 	} elsif ($dropMenu eq '') {
1.259     banghart 2570: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2571: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2572: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2573: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2574: 		next;
                   2575: 	    }
1.259     banghart 2576: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2577: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2578: 	    my $partial= $pts/$wgt;
1.259     banghart 2579: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2580: 		#do not update score for part if not changed.
1.346     banghart 2581:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2582: 		next;
1.251     banghart 2583: 	    } else {
1.259     banghart 2584: 	        push @parts_graded, $new_part;
1.153     albertel 2585: 	    }
1.259     banghart 2586: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2587: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2588: 	    }
1.259     banghart 2589: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2590: 	    if ($partial == 0) {
1.153     albertel 2591: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2592: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2593: 		}
1.41      ng       2594: 	    } else {
1.153     albertel 2595: 		if ($record{$reckey} ne 'correct_by_override') {
                   2596: 		    $newrecord{$reckey} = 'correct_by_override';
                   2597: 		}
                   2598: 	    }	    
                   2599: 	    if ($submitter && 
1.259     banghart 2600: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2601: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2602: 	    }
1.259     banghart 2603: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2604: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2605: 	}
1.259     banghart 2606: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2607: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2608: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2609: 	        $dropMenu eq 'reset status')
                   2610: 	   {
1.342     banghart 2611: 	    push (@version_parts,$new_part);
1.259     banghart 2612: 	}
1.41      ng       2613:     }
1.301     albertel 2614:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2615:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2616: 
1.344     albertel 2617:     if (%newrecord) {
                   2618:         if (@version_parts) {
1.364     banghart 2619:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2620:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2621: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2622: 	    foreach my $new_part (@version_parts) {
                   2623: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2624: 				$new_part,\%newrecord);
                   2625: 	    }
1.259     banghart 2626:         }
1.44      ng       2627: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2628: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2629: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2630: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2631:     }
1.269     raeburn  2632:     if ($aggregateflag) {
                   2633:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2634: 			      $cdom,$cnum);
1.269     raeburn  2635:     }
1.301     albertel 2636:     return ('',$pts,$wgt);
1.36      ng       2637: }
1.322     albertel 2638: 
1.380     albertel 2639: sub check_and_remove_from_queue {
                   2640:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2641:     my @ungraded_parts;
                   2642:     foreach my $part (@{$parts}) {
                   2643: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2644: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2645: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2646: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2647: 		) {
                   2648: 	    push(@ungraded_parts, $part);
                   2649: 	}
                   2650:     }
                   2651:     if ( !@ungraded_parts ) {
                   2652: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2653: 					       $cnum,$domain,$stuname);
                   2654:     }
                   2655: }
                   2656: 
1.337     banghart 2657: sub handback_files {
                   2658:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.359     www      2659:     my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
                   2660:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.375     albertel 2661: 
                   2662:     my @part_response_id = &flatten_responseType($responseType);
                   2663:     foreach my $part_response_id (@part_response_id) {
                   2664:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2665: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2666:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2667:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2668:                 my $file_counter = 1;
1.367     albertel 2669: 		my $file_msg;
1.337     banghart 2670:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2671:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2672:                     my ($directory,$answer_file) = 
                   2673:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2674:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2675: 		        &file_name_version_ext($answer_file);
1.355     banghart 2676: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.341     banghart 2677: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
1.338     banghart 2678: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2679:                     # fix file name
                   2680:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2681:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2682:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2683:             	                                $save_file_name);
1.337     banghart 2684:                     if ($result !~ m|^/uploaded/|) {
1.401     albertel 2685:                         $request->print('<span class="LC_error">An error occurred ('.$result.
1.398     albertel 2686:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
1.356     banghart 2687:                     } else {
1.360     banghart 2688:                         # mark the file as read only
                   2689:                         my @files = ($save_file_name);
1.372     albertel 2690:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2691:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2692: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2693: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2694: 			}
                   2695:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2696: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2697: 
1.337     banghart 2698:                     }
                   2699:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2700:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2701:                     $file_counter++;
                   2702:                 }
1.367     albertel 2703: 		my $subject = "File Handed Back by Instructor ";
                   2704: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2705: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2706: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2707: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2708: 		my ($feedurl,$showsymb) = 
                   2709: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2710:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2711: 		my $msgstatus = 
                   2712:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2713: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2714:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2715:             }
                   2716:         }
1.338     banghart 2717:     return;
1.337     banghart 2718: }
                   2719: 
1.418     albertel 2720: sub get_feedurl_and_symb {
                   2721:     my ($symb,$uname,$udom) = @_;
                   2722:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2723:     $url = &Apache::lonnet::clutter($url);
                   2724:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2725: 					$symb,$udom,$uname);
                   2726:     if ($encrypturl =~ /^yes$/i) {
                   2727: 	&Apache::lonenc::encrypted(\$url,1);
                   2728: 	&Apache::lonenc::encrypted(\$symb,1);
                   2729:     }
                   2730:     return ($url,$symb);
                   2731: }
                   2732: 
1.313     banghart 2733: sub get_submitted_files {
                   2734:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2735:     my @files;
                   2736:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2737:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2738:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2739:     	    push(@files,$file_url.$file);
                   2740:         }
                   2741:     }
                   2742:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2743:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2744:     }
                   2745:     return (\@files);
                   2746: }
1.322     albertel 2747: 
1.269     raeburn  2748: # ----------- Provides number of tries since last reset.
                   2749: sub get_num_tries {
                   2750:     my ($record,$last_reset,$part) = @_;
                   2751:     my $timestamp = '';
                   2752:     my $num_tries = 0;
                   2753:     if ($$record{'version'}) {
                   2754:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2755:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2756:                 $timestamp = $$record{$version.':timestamp'};
                   2757:                 if ($timestamp > $last_reset) {
                   2758:                     $num_tries ++;
                   2759:                 } else {
                   2760:                     last;
                   2761:                 }
                   2762:             }
                   2763:         }
                   2764:     }
                   2765:     return $num_tries;
                   2766: }
                   2767: 
                   2768: # ----------- Determine decrements required in aggregate totals 
                   2769: sub decrement_aggs {
                   2770:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2771:     my %decrement = (
                   2772:                         attempts => 0,
                   2773:                         users => 0,
                   2774:                         correct => 0
                   2775:                     );
                   2776:     $decrement{'attempts'} = $aggtries;
                   2777:     if ($solvedstatus =~ /^correct/) {
                   2778:         $decrement{'correct'} = 1;
                   2779:     }
                   2780:     if ($aggtries == $totaltries) {
                   2781:         $decrement{'users'} = 1;
                   2782:     }
                   2783:     foreach my $type (keys (%decrement)) {
                   2784:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2785:     }
                   2786:     return;
                   2787: }
                   2788: 
                   2789: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2790: sub get_last_resets {
1.270     albertel 2791:     my ($symb,$courseid,$partids) =@_;
                   2792:     my %last_resets;
1.269     raeburn  2793:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2794:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2795:     my @keys;
                   2796:     foreach my $part (@{$partids}) {
                   2797: 	push(@keys,"$symb\0$part\0resettime");
                   2798:     }
                   2799:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2800: 				     $cdom,$cname);
                   2801:     foreach my $part (@{$partids}) {
                   2802: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2803:     }
1.270     albertel 2804:     return %last_resets;
1.269     raeburn  2805: }
                   2806: 
1.251     banghart 2807: # ----------- Handles creating versions for portfolio files as answers
                   2808: sub version_portfiles {
1.343     banghart 2809:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2810:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2811:     my @returned_keys;
1.255     banghart 2812:     my $parts = join('|', @$parts_graded);
1.359     www      2813:     my $portfolio_root = &propath($domain,$stu_name).
                   2814: 	'/userfiles/portfolio';
1.277     albertel 2815:     foreach my $key (keys(%$record)) {
1.259     banghart 2816:         my $new_portfiles;
1.263     banghart 2817:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2818:             my @versioned_portfiles;
1.367     albertel 2819:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2820:             foreach my $file (@portfiles) {
1.306     banghart 2821:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2822:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2823: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2824: 		    &file_name_version_ext($answer_file);
1.306     banghart 2825:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
1.342     banghart 2826:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2827:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2828:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2829:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2830:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2831:                         [$directory.$new_answer],
1.306     banghart 2832:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2833:                 }
1.252     banghart 2834:             }
1.343     banghart 2835:             $$record{$key} = join(',',@versioned_portfiles);
                   2836:             push(@returned_keys,$key);
1.251     banghart 2837:         }
                   2838:     } 
1.343     banghart 2839:     return (@returned_keys);   
1.305     banghart 2840: }
                   2841: 
1.307     banghart 2842: sub get_next_version {
1.341     banghart 2843:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 2844:     my $version;
                   2845:     foreach my $row (@$dir_list) {
                   2846:         my ($file) = split(/\&/,$row,2);
                   2847:         my ($file_name,$file_version,$file_ext) =
                   2848: 	    &file_name_version_ext($file);
                   2849:         if (($file_name eq $answer_name) && 
                   2850: 	    ($file_ext eq $answer_ext)) {
                   2851:                 # gets here if filename and extension match, regardless of version
                   2852:                 if ($file_version ne '') {
                   2853:                 # a versioned file is found  so save it for later
                   2854:                 if ($file_version > $version) {
                   2855: 		    $version = $file_version;
                   2856: 	        }
                   2857:             }
                   2858:         }
                   2859:     } 
                   2860:     $version ++;
                   2861:     return($version);
                   2862: }
                   2863: 
1.305     banghart 2864: sub version_selected_portfile {
1.306     banghart 2865:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   2866:     my ($answer_name,$answer_ver,$answer_ext) =
                   2867:         &file_name_version_ext($file_name);
                   2868:     my $new_answer;
                   2869:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   2870:     if($env{'form.copy'} eq '-1') {
                   2871:         $new_answer = 'problem getting file';
                   2872:     } else {
                   2873:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   2874:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   2875:                             $stu_name,$domain,'copy',
                   2876: 		        '/portfolio'.$directory.$new_answer);
                   2877:     }    
                   2878:     return ($new_answer);
1.251     banghart 2879: }
                   2880: 
1.304     albertel 2881: sub file_name_version_ext {
                   2882:     my ($file)=@_;
                   2883:     my @file_parts = split(/\./, $file);
                   2884:     my ($name,$version,$ext);
                   2885:     if (@file_parts > 1) {
                   2886: 	$ext=pop(@file_parts);
                   2887: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   2888: 	    $version=pop(@file_parts);
                   2889: 	}
                   2890: 	$name=join('.',@file_parts);
                   2891:     } else {
                   2892: 	$name=join('.',@file_parts);
                   2893:     }
                   2894:     return($name,$version,$ext);
                   2895: }
                   2896: 
1.44      ng       2897: #--------------------------------------------------------------------------------------
                   2898: #
                   2899: #-------------------------- Next few routines handles grading by section or whole class
                   2900: #
                   2901: #--- Javascript to handle grading by section or whole class
1.42      ng       2902: sub viewgrades_js {
                   2903:     my ($request) = shift;
                   2904: 
1.41      ng       2905:     $request->print(<<VIEWJAVASCRIPT);
                   2906: <script type="text/javascript" language="javascript">
1.45      ng       2907:    function writePoint(partid,weight,point) {
1.125     ng       2908: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   2909: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       2910: 	if (point == "textval") {
1.125     ng       2911: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  2912: 	    if (isNaN(point) || parseFloat(point) < 0) {
                   2913: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.42      ng       2914: 		var resetbox = false;
                   2915: 		for (var i=0; i<radioButton.length; i++) {
                   2916: 		    if (radioButton[i].checked) {
                   2917: 			textbox.value = i;
                   2918: 			resetbox = true;
                   2919: 		    }
                   2920: 		}
                   2921: 		if (!resetbox) {
                   2922: 		    textbox.value = "";
                   2923: 		}
                   2924: 		return;
                   2925: 	    }
1.109     matthew  2926: 	    if (parseFloat(point) > parseFloat(weight)) {
                   2927: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2928: 				   ") greater than the weight for the part. Accept?");
                   2929: 		if (resp == false) {
                   2930: 		    textbox.value = "";
                   2931: 		    return;
                   2932: 		}
                   2933: 	    }
1.42      ng       2934: 	    for (var i=0; i<radioButton.length; i++) {
                   2935: 		radioButton[i].checked=false;
1.109     matthew  2936: 		if (parseFloat(point) == i) {
1.42      ng       2937: 		    radioButton[i].checked=true;
                   2938: 		}
                   2939: 	    }
1.41      ng       2940: 
1.42      ng       2941: 	} else {
1.125     ng       2942: 	    textbox.value = parseFloat(point);
1.42      ng       2943: 	}
1.41      ng       2944: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2945: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 2946: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2947: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2948: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2949: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2950: 	    if (saveval != "correct") {
                   2951: 		scorename.value = point;
1.43      ng       2952: 		if (selname[0].selected != true) {
                   2953: 		    selname[0].selected = true;
                   2954: 		}
1.42      ng       2955: 	    }
                   2956: 	}
1.125     ng       2957: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       2958:     }
                   2959: 
                   2960:     function writeRadText(partid,weight) {
1.125     ng       2961: 	var selval   = document.classgrade["SELVAL_"+partid];
                   2962: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      2963:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       2964: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   2965: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       2966: 	    for (var i=0; i<radioButton.length; i++) {
                   2967: 		radioButton[i].checked=false;
                   2968: 
                   2969: 	    }
                   2970: 	    textbox.value = "";
                   2971: 
                   2972: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2973: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2974: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2975: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2976: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2977: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      2978: 		if ((saveval != "correct") || override) {
1.42      ng       2979: 		    scorename.value = "";
1.125     ng       2980: 		    if (selval[1].selected) {
                   2981: 			selname[1].selected = true;
                   2982: 		    } else {
                   2983: 			selname[2].selected = true;
                   2984: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   2985: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   2986: 		    }
1.42      ng       2987: 		}
                   2988: 	    }
1.43      ng       2989: 	} else {
                   2990: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2991: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2992: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2993: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2994: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2995: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      2996: 		if ((saveval != "correct") || override) {
1.125     ng       2997: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       2998: 		    selname[0].selected = true;
                   2999: 		}
                   3000: 	    }
                   3001: 	}	    
1.42      ng       3002:     }
                   3003: 
                   3004:     function changeSelect(partid,user) {
1.125     ng       3005: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3006: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3007: 	var point  = textbox.value;
1.125     ng       3008: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3009: 
1.109     matthew  3010: 	if (isNaN(point) || parseFloat(point) < 0) {
                   3011: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.44      ng       3012: 	    textbox.value = "";
                   3013: 	    return;
                   3014: 	}
1.109     matthew  3015: 	if (parseFloat(point) > parseFloat(weight)) {
                   3016: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3017: 			       ") greater than the weight of the part. Accept?");
                   3018: 	    if (resp == false) {
                   3019: 		textbox.value = "";
                   3020: 		return;
                   3021: 	    }
                   3022: 	}
1.42      ng       3023: 	selval[0].selected = true;
                   3024:     }
                   3025: 
                   3026:     function changeOneScore(partid,user) {
1.125     ng       3027: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3028: 	if (selval[1].selected || selval[2].selected) {
                   3029: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3030: 	    if (selval[2].selected) {
                   3031: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3032: 	    }
1.269     raeburn  3033:         }
1.42      ng       3034:     }
                   3035: 
                   3036:     function resetEntry(numpart) {
                   3037: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3038: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3039: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3040: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3041: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3042: 	    for (var i=0; i<radioButton.length; i++) {
                   3043: 		radioButton[i].checked=false;
                   3044: 
                   3045: 	    }
                   3046: 	    textbox.value = "";
                   3047: 	    selval[0].selected = true;
                   3048: 
                   3049: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3050: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3051: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3052: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3053: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3054: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3055: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3056: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3057: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3058: 		if (saveselval == "excused") {
1.43      ng       3059: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3060: 		} else {
1.43      ng       3061: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3062: 		}
                   3063: 	    }
1.41      ng       3064: 	}
1.42      ng       3065:     }
                   3066: 
1.41      ng       3067: </script>
                   3068: VIEWJAVASCRIPT
1.42      ng       3069: }
                   3070: 
1.44      ng       3071: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3072: sub viewgrades {
                   3073:     my ($request) = shift;
                   3074:     &viewgrades_js($request);
1.41      ng       3075: 
1.324     albertel 3076:     my ($symb) = &get_symb($request);
1.168     albertel 3077:     #need to make sure we have the correct data for later EXT calls, 
                   3078:     #thus invalidate the cache
                   3079:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3080:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3081:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3082:     &Apache::lonnet::clear_EXT_cache_status();
                   3083: 
1.398     albertel 3084:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
                   3085:     $result.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n";
1.41      ng       3086: 
                   3087:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3088:     $result.=&jscriptNform($symb);
1.41      ng       3089: 
1.44      ng       3090:     #beginning of class grading form
1.442     banghart 3091:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3092:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3093: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3094: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3095: 	&build_section_inputs().
1.257     albertel 3096: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3097: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3098: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3099: 
1.126     ng       3100:     my $sectionClass;
1.430     banghart 3101:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.257     albertel 3102:     if ($env{'form.section'} eq 'all') {
1.126     ng       3103: 	$sectionClass='Class </h3>';
1.257     albertel 3104:     } elsif ($env{'form.section'} eq 'none') {
1.431     banghart 3105: 	$sectionClass=&mt('Students in no Section').'</h3>';
1.52      albertel 3106:     } else {
1.431     banghart 3107: 	$sectionClass=&mt('Students in Section(s) [_1]',$section_display).'</h3>';
1.52      albertel 3108:     }
1.431     banghart 3109:     $result.='<h3>'.&mt('Assign Common Grade To [_1]',$sectionClass);
1.52      albertel 3110:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
                   3111: 	'<table border=0><tr bgcolor="#ffffdd"><td>';
1.44      ng       3112:     #radio buttons/text box for assigning points for a section or class.
                   3113:     #handles different parts of a problem
1.375     albertel 3114:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       3115:     my %weight = ();
                   3116:     my $ctsparts = 0;
1.41      ng       3117:     $result.='<table border="0">';
1.45      ng       3118:     my %seen = ();
1.375     albertel 3119:     my @part_response_id = &flatten_responseType($responseType);
                   3120:     foreach my $part_response_id (@part_response_id) {
                   3121:     	my ($partid,$respid) = @{ $part_response_id };
                   3122: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3123: 	next if $seen{$partid};
                   3124: 	$seen{$partid}++;
1.375     albertel 3125: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3126: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3127: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3128: 
1.44      ng       3129: 	$result.='<input type="hidden" name="partid_'.
                   3130: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3131: 	$result.='<input type="hidden" name="weight_'.
                   3132: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
1.324     albertel 3133: 	my $display_part=&get_display_part($partid,$symb);
1.207     albertel 3134: 	$result.='<tr><td><b>Part:</b> '.$display_part.'&nbsp; &nbsp;<b>Point:</b> </td><td>';
1.42      ng       3135: 	$result.='<table border="0"><tr>';  
1.41      ng       3136: 	my $ctr = 0;
1.42      ng       3137: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.288     albertel 3138: 	    $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3139: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3140: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3141: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3142: 	    $ctr++;
                   3143: 	}
                   3144: 	$result.='</tr></table>';
1.44      ng       3145: 	$result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
1.54      albertel 3146: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3147: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.42      ng       3148: 	    $weight{$partid}.' (problem weight)</td>'."\n";
                   3149: 	$result.= '</td><td><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3150: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3151: 		$weight{$partid}.')"> '.
1.401     albertel 3152: 	    '<option selected="selected"> </option>'.
1.125     ng       3153: 	    '<option>excused</option>'.
1.265     www      3154: 	    '<option>reset status</option></select></td>'.
1.266     albertel 3155:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
1.42      ng       3156: 	$ctsparts++;
1.41      ng       3157:     }
1.52      albertel 3158:     $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
                   3159: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.391     banghart 3160:     $result.='<input type="button" value="Revert to Default" '.
1.417     albertel 3161: 	'onClick="javascript:resetEntry('.$ctsparts.');" target="_self" />';
1.41      ng       3162: 
1.44      ng       3163:     #table listing all the students in a section/class
                   3164:     #header of table
1.126     ng       3165:     $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
1.42      ng       3166:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
1.126     ng       3167: 	'<table border=0><tr bgcolor="#deffff"><td>&nbsp;<b>No.</b>&nbsp;</td>'.
1.129     ng       3168: 	'<td>'.&nameUserString('header')."</td>\n";
1.324     albertel 3169:     my (@parts) = sort(&getpartlist($symb));
                   3170:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3171:     my @partids = ();
1.41      ng       3172:     foreach my $part (@parts) {
                   3173: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.126     ng       3174: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
1.41      ng       3175: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3176: 	my ($partid) = &split_part_type($part);
1.269     raeburn  3177:         push(@partids, $partid);
1.324     albertel 3178: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3179: 	if ($display =~ /^Partial Credit Factor/) {
1.207     albertel 3180: 	    $result.='<td><b>Score Part:</b> '.$display_part.
                   3181: 		' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
1.41      ng       3182: 	    next;
1.207     albertel 3183: 	} else {
                   3184: 	    $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
1.41      ng       3185: 	}
1.53      albertel 3186: 	$display =~ s|Problem Status|Grade Status<br />|;
1.207     albertel 3187: 	$result.='<td><b>'.$display.'</td>'."\n";
1.41      ng       3188:     }
                   3189:     $result.='</tr>';
1.44      ng       3190: 
1.270     albertel 3191:     my %last_resets = 
                   3192: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3193: 
1.41      ng       3194:     #get info for each student
1.44      ng       3195:     #list all the students - with points and grade status
1.257     albertel 3196:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3197:     my $ctr = 0;
1.294     albertel 3198:     foreach (sort 
                   3199: 	     {
                   3200: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3201: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3202: 		 }
                   3203: 		 return $a cmp $b;
                   3204: 	     } (keys(%$fullname))) {
1.126     ng       3205: 	$ctr++;
1.324     albertel 3206: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3207: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3208:     }
                   3209:     $result.='</table></td></tr></table>';
                   3210:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.126     ng       3211:     $result.='<input type="button" value="Save" '.
1.417     albertel 3212: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3213:     if (scalar(%$fullname) eq 0) {
                   3214: 	my $colspan=3+scalar(@parts);
1.433     banghart 3215: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3216:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3217: 	$result='<span class="LC_warning">'.
                   3218: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade',
1.442     banghart 3219: 	        $section_display, $stu_status).
1.433     banghart 3220: 	    '</span>';
1.96      albertel 3221:     }
1.324     albertel 3222:     $result.=&show_grading_menu_form($symb);
1.41      ng       3223:     return $result;
                   3224: }
                   3225: 
1.44      ng       3226: #--- call by previous routine to display each student
1.41      ng       3227: sub viewstudentgrade {
1.324     albertel 3228:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3229:     my ($uname,$udom) = split(/:/,$student);
                   3230:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3231:     my %aggregates = (); 
1.233     albertel 3232:     my $result='<tr bgcolor="#ffffdd"><td align="right">'.
                   3233: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3234: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3235: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3236: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3237: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3238:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3239:     foreach my $apart (@$parts) {
                   3240: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3241: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3242:         $result.='<td align="center">';
1.269     raeburn  3243:         my ($aggtries,$totaltries);
                   3244:         unless (exists($aggregates{$part})) {
1.270     albertel 3245: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3246: 
                   3247: 	    $aggtries = $totaltries;
1.269     raeburn  3248:             if ($$last_resets{$part}) {  
1.270     albertel 3249:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3250: 					   $part);
                   3251:             }
1.269     raeburn  3252:             $result.='<input type="hidden" name="'.
                   3253:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3254:             $result.='<input type="hidden" name="'.
                   3255:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3256:             $aggregates{$part} = 1;
                   3257:         }
1.41      ng       3258: 	if ($type eq 'awarded') {
1.320     albertel 3259: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3260: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3261: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3262: 	    $result.='<input type="text" name="'.
1.89      albertel 3263: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3264: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3265: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3266: 	} elsif ($type eq 'solved') {
                   3267: 	    my ($status,$foo)=split(/_/,$score,2);
                   3268: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3269: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3270: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3271: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3272: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3273: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.401     albertel 3274: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>' 
                   3275: 		: '<option selected="selected"> </option><option>excused</option>')."\n";
1.125     ng       3276: 	    $result.='<option>reset status</option>';
1.126     ng       3277: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3278: 	} else {
                   3279: 	    $result.='<input type="hidden" name="'.
                   3280: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3281: 		    "\n";
1.233     albertel 3282: 	    $result.='<input type="text" name="'.
1.122     ng       3283: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3284: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3285: 	}
                   3286:     }
                   3287:     $result.='</tr>';
                   3288:     return $result;
1.38      ng       3289: }
                   3290: 
1.44      ng       3291: #--- change scores for all the students in a section/class
                   3292: #    record does not get update if unchanged
1.38      ng       3293: sub editgrades {
1.41      ng       3294:     my ($request) = @_;
                   3295: 
1.324     albertel 3296:     my $symb=&get_symb($request);
1.433     banghart 3297:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3298:     my $title='<h3><span class="LC_info">'.&mt('Current Grade Status').'</span></h3>';
                   3299:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4><br />'."\n";
                   3300:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3301: 
1.44      ng       3302:     my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
1.129     ng       3303:     $result.= '<table border="0"><tr bgcolor="#deffff">'.
                   3304: 	'<td rowspan=2 valign="center">&nbsp;<b>No.</b>&nbsp;</td>'.
                   3305: 	'<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
1.43      ng       3306: 
                   3307:     my %scoreptr = (
                   3308: 		    'correct'  =>'correct_by_override',
                   3309: 		    'incorrect'=>'incorrect_by_override',
                   3310: 		    'excused'  =>'excused',
                   3311: 		    'ungraded' =>'ungraded_attempted',
                   3312: 		    'nothing'  => '',
                   3313: 		    );
1.257     albertel 3314:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3315: 
1.44      ng       3316:     my (@partid);
                   3317:     my %weight = ();
1.54      albertel 3318:     my %columns = ();
1.44      ng       3319:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3320: 
1.324     albertel 3321:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3322:     my $header;
1.257     albertel 3323:     while ($ctr < $env{'form.totalparts'}) {
                   3324: 	my $partid = $env{'form.partid_'.$ctr};
1.44      ng       3325: 	push @partid,$partid;
1.257     albertel 3326: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3327: 	$ctr++;
1.54      albertel 3328:     }
1.324     albertel 3329:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3330:     foreach my $partid (@partid) {
                   3331: 	$header .= '<td align="center">&nbsp;<b>Old Score</b>&nbsp;</td>'.
                   3332: 	    '<td align="center">&nbsp;<b>New Score</b>&nbsp;</td>';
                   3333: 	$columns{$partid}=2;
                   3334: 	foreach my $stores (@parts) {
                   3335: 	    my ($part,$type) = &split_part_type($stores);
                   3336: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3337: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3338: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
                   3339: 	    $display =~ s/\[Part: (\w)+\]//;
1.125     ng       3340: 	    $display =~ s/Number of Attempts/Tries/;
                   3341: 	    $header .= '<td align="center">&nbsp;<b>Old '.$display.'</b>&nbsp;</td>'.
                   3342: 		'<td align="center">&nbsp;<b>New '.$display.'</b>&nbsp;</td>';
1.54      albertel 3343: 	    $columns{$partid}+=2;
                   3344: 	}
                   3345:     }
                   3346:     foreach my $partid (@partid) {
1.324     albertel 3347: 	my $display_part=&get_display_part($partid,$symb);
1.54      albertel 3348: 	$result .= '<td colspan="'.$columns{$partid}.
1.207     albertel 3349: 	    '" align="center"><b>Part:</b> '.$display_part.
                   3350: 	    ' (Weight = '.$weight{$partid}.')</td>';
1.54      albertel 3351: 
1.44      ng       3352:     }
                   3353:     $result .= '</tr><tr bgcolor="#deffff">';
1.54      albertel 3354:     $result .= $header;
1.44      ng       3355:     $result .= '</tr>'."\n";
1.93      albertel 3356:     my $noupdate;
1.126     ng       3357:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3358:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3359: 	my $line;
1.257     albertel 3360: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3361: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3362: 	my %newrecord;
                   3363: 	my $updateflag = 0;
1.281     albertel 3364: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3365: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3366: 	if (!&canmodify($usec)) {
1.126     ng       3367: 	    my $numcols=scalar(@partid)*4+2;
1.399     albertel 3368: 	    $noupdate.=$line."<td colspan=\"$numcols\"><span class=\"LC_warning\">Not allowed to modify student</span></td></tr>";
1.105     albertel 3369: 	    next;
                   3370: 	}
1.269     raeburn  3371:         my %aggregate = ();
                   3372:         my $aggregateflag = 0;
1.281     albertel 3373: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3374: 	foreach (@partid) {
1.257     albertel 3375: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3376: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3377: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3378: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3379: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3380: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3381: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3382: 	    my $score;
                   3383: 	    if ($partial eq '') {
1.257     albertel 3384: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3385: 	    } elsif ($partial > 0) {
                   3386: 		$score = 'correct_by_override';
                   3387: 	    } elsif ($partial == 0) {
                   3388: 		$score = 'incorrect_by_override';
                   3389: 	    }
1.257     albertel 3390: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3391: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3392: 
1.292     albertel 3393: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3394: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3395: 	    if ($dropMenu eq 'reset status' &&
                   3396: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3397: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3398: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3399: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3400: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3401: 		$updateflag = 1;
1.269     raeburn  3402:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3403:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3404:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3405:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3406:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3407:                     $aggregateflag = 1;
                   3408:                 }
1.139     albertel 3409: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3410: 		$updateflag = 1;
                   3411: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3412: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3413: 		$rec_update++;
1.125     ng       3414: 	    }
                   3415: 
1.93      albertel 3416: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3417: 		'<td align="center">'.$awarded.
                   3418: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3419: 
1.54      albertel 3420: 
                   3421: 	    my $partid=$_;
                   3422: 	    foreach my $stores (@parts) {
                   3423: 		my ($part,$type) = &split_part_type($stores);
                   3424: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3425: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3426: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3427: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3428: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3429: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3430: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3431: 		    $updateflag=1;
                   3432: 		}
1.93      albertel 3433: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3434: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3435: 	    }
1.44      ng       3436: 	}
1.93      albertel 3437: 	$line.='</tr>'."\n";
1.301     albertel 3438: 
                   3439: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3440: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3441: 
1.44      ng       3442: 	if ($updateflag) {
                   3443: 	    $count++;
1.257     albertel 3444: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3445: 				    $udom,$uname);
1.301     albertel 3446: 
                   3447: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3448: 					      $cnum,$udom,$uname)) {
                   3449: 		# need to figure out if should be in queue.
                   3450: 		my %record =  
                   3451: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3452: 					     $udom,$uname);
                   3453: 		my $all_graded = 1;
                   3454: 		my $none_graded = 1;
                   3455: 		foreach my $part (@parts) {
                   3456: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3457: 			$all_graded = 0;
                   3458: 		    } else {
                   3459: 			$none_graded = 0;
                   3460: 		    }
                   3461: 		}
                   3462: 
                   3463: 		if ($all_graded || $none_graded) {
                   3464: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3465: 							   $symb,$cdom,$cnum,
                   3466: 							   $udom,$uname);
                   3467: 		}
                   3468: 	    }
                   3469: 
1.126     ng       3470: 	    $result.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line;
                   3471: 	    $updateCtr++;
1.93      albertel 3472: 	} else {
1.126     ng       3473: 	    $noupdate.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line;
                   3474: 	    $noupdateCtr++;
1.44      ng       3475: 	}
1.269     raeburn  3476:         if ($aggregateflag) {
                   3477:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3478: 				  $cdom,$cnum);
1.269     raeburn  3479:         }
1.93      albertel 3480:     }
                   3481:     if ($noupdate) {
1.126     ng       3482: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3483: 	my $numcols=scalar(@partid)*4+2;
1.204     albertel 3484: 	$result .= '<tr bgcolor="#ffffff"><td align="center" colspan="'.$numcols.'">No Changes Occurred For the Students Below</td></tr><tr bgcolor="#ffffde">'.$noupdate;
1.44      ng       3485:     }
1.72      ng       3486:     $result .= '</table></td></tr></table>'."\n".
1.324     albertel 3487: 	&show_grading_menu_form ($symb);
1.125     ng       3488:     my $msg = '<br /><b>Number of records updated = '.$rec_update.
1.44      ng       3489: 	' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
1.257     albertel 3490: 	'<b>Total number of students = '.$env{'form.total'}.'</b><br />';
1.44      ng       3491:     return $title.$msg.$result;
1.5       albertel 3492: }
1.54      albertel 3493: 
                   3494: sub split_part_type {
                   3495:     my ($partstr) = @_;
                   3496:     my ($temp,@allparts)=split(/_/,$partstr);
                   3497:     my $type=pop(@allparts);
1.439     albertel 3498:     my $part=join('_',@allparts);
1.54      albertel 3499:     return ($part,$type);
                   3500: }
                   3501: 
1.44      ng       3502: #------------- end of section for handling grading by section/class ---------
                   3503: #
                   3504: #----------------------------------------------------------------------------
                   3505: 
1.5       albertel 3506: 
1.44      ng       3507: #----------------------------------------------------------------------------
                   3508: #
                   3509: #-------------------------- Next few routines handles grading by csv upload
                   3510: #
                   3511: #--- Javascript to handle csv upload
1.27      albertel 3512: sub csvupload_javascript_reverse_associate {
1.246     albertel 3513:     my $error1=&mt('You need to specify the username or ID');
                   3514:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3515:   return(<<ENDPICK);
                   3516:   function verify(vf) {
                   3517:     var foundsomething=0;
                   3518:     var founduname=0;
1.243     albertel 3519:     var foundID=0;
1.27      albertel 3520:     for (i=0;i<=vf.nfields.value;i++) {
                   3521:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3522:       if (i==0 && tw!=0) { foundID=1; }
                   3523:       if (i==1 && tw!=0) { founduname=1; }
                   3524:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3525:     }
1.246     albertel 3526:     if (founduname==0 && foundID==0) {
                   3527: 	alert('$error1');
                   3528: 	return;
1.27      albertel 3529:     }
                   3530:     if (foundsomething==0) {
1.246     albertel 3531: 	alert('$error2');
                   3532: 	return;
1.27      albertel 3533:     }
                   3534:     vf.submit();
                   3535:   }
                   3536:   function flip(vf,tf) {
                   3537:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3538:     var i;
                   3539:     for (i=0;i<=vf.nfields.value;i++) {
                   3540:       //can not pick the same destination field for both name and domain
                   3541:       if (((i ==0)||(i ==1)) && 
                   3542:           ((tf==0)||(tf==1)) && 
                   3543:           (i!=tf) &&
                   3544:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3545:         eval('vf.f'+i+'.selectedIndex=0;')
                   3546:       }
                   3547:     }
                   3548:   }
                   3549: ENDPICK
                   3550: }
                   3551: 
                   3552: sub csvupload_javascript_forward_associate {
1.246     albertel 3553:     my $error1=&mt('You need to specify the username or ID');
                   3554:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3555:   return(<<ENDPICK);
                   3556:   function verify(vf) {
                   3557:     var foundsomething=0;
                   3558:     var founduname=0;
1.243     albertel 3559:     var foundID=0;
1.27      albertel 3560:     for (i=0;i<=vf.nfields.value;i++) {
                   3561:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3562:       if (tw==1) { foundID=1; }
                   3563:       if (tw==2) { founduname=1; }
                   3564:       if (tw>3) { foundsomething=1; }
1.27      albertel 3565:     }
1.246     albertel 3566:     if (founduname==0 && foundID==0) {
                   3567: 	alert('$error1');
                   3568: 	return;
1.27      albertel 3569:     }
                   3570:     if (foundsomething==0) {
1.246     albertel 3571: 	alert('$error2');
                   3572: 	return;
1.27      albertel 3573:     }
                   3574:     vf.submit();
                   3575:   }
                   3576:   function flip(vf,tf) {
                   3577:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3578:     var i;
                   3579:     //can not pick the same destination field twice
                   3580:     for (i=0;i<=vf.nfields.value;i++) {
                   3581:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3582:         eval('vf.f'+i+'.selectedIndex=0;')
                   3583:       }
                   3584:     }
                   3585:   }
                   3586: ENDPICK
                   3587: }
                   3588: 
1.26      albertel 3589: sub csvuploadmap_header {
1.324     albertel 3590:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3591:     my $javascript;
1.257     albertel 3592:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3593: 	$javascript=&csvupload_javascript_reverse_associate();
                   3594:     } else {
                   3595: 	$javascript=&csvupload_javascript_forward_associate();
                   3596:     }
1.45      ng       3597: 
1.324     albertel 3598:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3599:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3600:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3601:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3602:     $request->print(<<ENDPICK);
1.26      albertel 3603: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3604: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3605: $result
1.326     albertel 3606: <hr />
1.26      albertel 3607: <h3>Identify fields</h3>
                   3608: Total number of records found in file: $distotal <hr />
                   3609: Enter as many fields as you can. The system will inform you and bring you back
                   3610: to this page if the data selected is insufficient to run your class.<hr />
                   3611: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3612: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3613: <input type="hidden" name="associate"  value="" />
                   3614: <input type="hidden" name="phase"      value="three" />
                   3615: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3616: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3617: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3618: <input type="hidden" name="upfile_associate" 
1.257     albertel 3619:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3620: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3621: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3622: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3623: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3624: <hr />
                   3625: <script type="text/javascript" language="Javascript">
                   3626: $javascript
                   3627: </script>
                   3628: ENDPICK
1.118     ng       3629:     return '';
1.26      albertel 3630: 
                   3631: }
                   3632: 
                   3633: sub csvupload_fields {
1.324     albertel 3634:     my ($symb) = @_;
                   3635:     my (@parts) = &getpartlist($symb);
1.243     albertel 3636:     my @fields=(['ID','Student ID'],
                   3637: 		['username','Student Username'],
                   3638: 		['domain','Student Domain']);
1.324     albertel 3639:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3640:     foreach my $part (sort(@parts)) {
                   3641: 	my @datum;
                   3642: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3643: 	my $name=$part;
                   3644: 	if  (!$display) { $display = $name; }
                   3645: 	@datum=($name,$display);
1.244     albertel 3646: 	if ($name=~/^stores_(.*)_awarded/) {
                   3647: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3648: 	}
1.41      ng       3649: 	push(@fields,\@datum);
                   3650:     }
                   3651:     return (@fields);
1.26      albertel 3652: }
                   3653: 
                   3654: sub csvuploadmap_footer {
1.41      ng       3655:     my ($request,$i,$keyfields) =@_;
                   3656:     $request->print(<<ENDPICK);
1.26      albertel 3657: </table>
                   3658: <input type="hidden" name="nfields" value="$i" />
                   3659: <input type="hidden" name="keyfields" value="$keyfields" />
                   3660: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3661: </form>
                   3662: ENDPICK
                   3663: }
                   3664: 
1.283     albertel 3665: sub checkforfile_js {
1.86      ng       3666:     my $result =<<CSVFORMJS;
                   3667: <script type="text/javascript" language="javascript">
                   3668:     function checkUpload(formname) {
                   3669: 	if (formname.upfile.value == "") {
                   3670: 	    alert("Please use the browse button to select a file from your local directory.");
                   3671: 	    return false;
                   3672: 	}
                   3673: 	formname.submit();
                   3674:     }
                   3675:     </script>
                   3676: CSVFORMJS
1.283     albertel 3677:     return $result;
                   3678: }
                   3679: 
                   3680: sub upcsvScores_form {
                   3681:     my ($request) = shift;
1.324     albertel 3682:     my ($symb)=&get_symb($request);
1.283     albertel 3683:     if (!$symb) {return '';}
                   3684:     my $result=&checkforfile_js();
1.257     albertel 3685:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3686:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3687:     $result.=$table;
1.326     albertel 3688:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3689:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.370     www      3690:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
1.86      ng       3691: 	'.</b></td></tr>'."\n";
                   3692:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3693:     my $upload=&mt("Upload Scores");
1.86      ng       3694:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3695:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3696:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3697:     $result.=<<ENDUPFORM;
1.106     albertel 3698: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3699: <input type="hidden" name="symb" value="$symb" />
                   3700: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3701: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3702: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3703: $upfile_select
1.370     www      3704: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3705: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3706: </form>
                   3707: ENDUPFORM
1.370     www      3708:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3709:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3710:     .'</td></tr></table>'."\n";
1.86      ng       3711:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3712:     $result.=&show_grading_menu_form($symb);
1.86      ng       3713:     return $result;
                   3714: }
                   3715: 
                   3716: 
1.26      albertel 3717: sub csvuploadmap {
1.41      ng       3718:     my ($request)= @_;
1.324     albertel 3719:     my ($symb)=&get_symb($request);
1.41      ng       3720:     if (!$symb) {return '';}
1.72      ng       3721: 
1.41      ng       3722:     my $datatoken;
1.257     albertel 3723:     if (!$env{'form.datatoken'}) {
1.41      ng       3724: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3725:     } else {
1.257     albertel 3726: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3727: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3728:     }
1.41      ng       3729:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3730:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3731:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3732:     my ($i,$keyfields);
                   3733:     if (@records) {
1.324     albertel 3734: 	my @fields=&csvupload_fields($symb);
1.45      ng       3735: 
1.257     albertel 3736: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3737: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3738: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3739: 							  \@fields);
                   3740: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3741: 	    chop($keyfields);
                   3742: 	} else {
                   3743: 	    unshift(@fields,['none','']);
                   3744: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3745: 							    \@fields);
1.311     banghart 3746:             foreach my $rec (@records) {
                   3747:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3748:                 if (%temp) {
                   3749:                     $keyfields=join(',',sort(keys(%temp)));
                   3750:                     last;
                   3751:                 }
                   3752:             }
1.41      ng       3753: 	}
                   3754:     }
                   3755:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3756:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3757: 
1.41      ng       3758:     return '';
1.27      albertel 3759: }
                   3760: 
1.246     albertel 3761: sub csvuploadoptions {
1.41      ng       3762:     my ($request)= @_;
1.324     albertel 3763:     my ($symb)=&get_symb($request);
1.257     albertel 3764:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3765:     my $ignore=&mt('Ignore First Line');
                   3766:     $request->print(<<ENDPICK);
                   3767: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3768: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3769: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3770: <!--
1.246     albertel 3771: <p>
                   3772: <label>
                   3773:    <input type="checkbox" name="show_full_results" />
                   3774:    Show a table of all changes
                   3775: </label>
                   3776: </p>
1.302     albertel 3777: -->
1.246     albertel 3778: <p>
                   3779: <label>
                   3780:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3781:    Overwrite any existing score
                   3782: </label>
                   3783: </p>
                   3784: ENDPICK
                   3785:     my %fields=&get_fields();
                   3786:     if (!defined($fields{'domain'})) {
1.257     albertel 3787: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3788: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3789:     }
1.257     albertel 3790:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3791: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3792: 	my $cleankey=$1;
                   3793: 	if ($cleankey eq 'command') { next; }
                   3794: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3795: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3796:     }
                   3797:     # FIXME do a check for any duplicated user ids...
                   3798:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3799:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3800: <hr /></form>'."\n");
1.324     albertel 3801:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3802:     return '';
                   3803: }
                   3804: 
                   3805: sub get_fields {
                   3806:     my %fields;
1.257     albertel 3807:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3808:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3809: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3810: 	    if ($env{'form.f'.$i} ne 'none') {
                   3811: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3812: 	    }
                   3813: 	} else {
1.257     albertel 3814: 	    if ($env{'form.f'.$i} ne 'none') {
                   3815: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3816: 	    }
                   3817: 	}
1.27      albertel 3818:     }
1.246     albertel 3819:     return %fields;
                   3820: }
                   3821: 
                   3822: sub csvuploadassign {
                   3823:     my ($request)= @_;
1.324     albertel 3824:     my ($symb)=&get_symb($request);
1.246     albertel 3825:     if (!$symb) {return '';}
1.345     bowersj2 3826:     my $error_msg = '';
1.246     albertel 3827:     &Apache::loncommon::load_tmp_file($request);
                   3828:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3829:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3830:     my %fields=&get_fields();
1.41      ng       3831:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3832:     my $courseid=$env{'request.course.id'};
1.97      albertel 3833:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3834:     my @notallowed;
1.41      ng       3835:     my @skipped;
                   3836:     my $countdone=0;
                   3837:     foreach my $grade (@gradedata) {
                   3838: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 3839: 	my $domain;
                   3840: 	if ($entries{$fields{'domain'}}) {
                   3841: 	    $domain=$entries{$fields{'domain'}};
                   3842: 	} else {
1.257     albertel 3843: 	    $domain=$env{'form.default_domain'};
1.246     albertel 3844: 	}
1.243     albertel 3845: 	$domain=~s/\s//g;
1.41      ng       3846: 	my $username=$entries{$fields{'username'}};
1.160     albertel 3847: 	$username=~s/\s//g;
1.243     albertel 3848: 	if (!$username) {
                   3849: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 3850: 	    $id=~s/\s//g;
1.243     albertel 3851: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   3852: 	    $username=$ids{$id};
                   3853: 	}
1.41      ng       3854: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 3855: 	    my $id=$entries{$fields{'ID'}};
                   3856: 	    $id=~s/\s//g;
                   3857: 	    if ($id) {
                   3858: 		push(@skipped,"$id:$domain");
                   3859: 	    } else {
                   3860: 		push(@skipped,"$username:$domain");
                   3861: 	    }
1.41      ng       3862: 	    next;
                   3863: 	}
1.108     albertel 3864: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 3865: 	if (!&canmodify($usec)) {
                   3866: 	    push(@notallowed,"$username:$domain");
                   3867: 	    next;
                   3868: 	}
1.244     albertel 3869: 	my %points;
1.41      ng       3870: 	my %grades;
                   3871: 	foreach my $dest (keys(%fields)) {
1.244     albertel 3872: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   3873: 		$dest eq 'domain') { next; }
                   3874: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   3875: 	    if ($dest=~/stores_(.*)_points/) {
                   3876: 		my $part=$1;
                   3877: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   3878: 					      $symb,$domain,$username);
1.345     bowersj2 3879:                 if ($wgt) {
                   3880:                     $entries{$fields{$dest}}=~s/\s//g;
                   3881:                     my $pcr=$entries{$fields{$dest}} / $wgt;
                   3882:                     my $award='correct_by_override';
                   3883:                     $grades{"resource.$part.awarded"}=$pcr;
                   3884:                     $grades{"resource.$part.solved"}=$award;
                   3885:                     $points{$part}=1;
                   3886:                 } else {
                   3887:                     $error_msg = "<br />" .
                   3888:                         &mt("Some point values were assigned"
                   3889:                             ." for problems with a weight "
                   3890:                             ."of zero. These values were "
                   3891:                             ."ignored.");
                   3892:                 }
1.244     albertel 3893: 	    } else {
                   3894: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   3895: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   3896: 		my $store_key=$dest;
                   3897: 		$store_key=~s/^stores/resource/;
                   3898: 		$store_key=~s/_/\./g;
                   3899: 		$grades{$store_key}=$entries{$fields{$dest}};
                   3900: 	    }
1.41      ng       3901: 	}
1.398     albertel 3902: 	if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
1.257     albertel 3903: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
1.302     albertel 3904: 	my $result=&Apache::lonnet::cstore(\%grades,$symb,
                   3905: 					   $env{'request.course.id'},
                   3906: 					   $domain,$username);
                   3907: 	if ($result eq 'ok') {
                   3908: 	    $request->print('.');
                   3909: 	} else {
                   3910: 	    $request->print("<p>
1.398     albertel 3911:                               <span class=\"LC_error\">
                   3912:                                  Failed to save student $username:$domain.
                   3913:                                  Message when trying to save was ($result)
                   3914:                               </span>
1.302     albertel 3915:                              </p>" );
                   3916: 	}
1.41      ng       3917: 	$request->rflush();
                   3918: 	$countdone++;
                   3919:     }
1.398     albertel 3920:     $request->print("<br />Saved $countdone students\n");
1.41      ng       3921:     if (@skipped) {
1.398     albertel 3922: 	$request->print('<p><h4><b>Skipped Students</b></h4></p>');
1.106     albertel 3923: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   3924:     }
                   3925:     if (@notallowed) {
1.398     albertel 3926: 	$request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
1.106     albertel 3927: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       3928:     }
1.106     albertel 3929:     $request->print("<br />\n");
1.324     albertel 3930:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 3931:     return $error_msg;
1.26      albertel 3932: }
1.44      ng       3933: #------------- end of section for handling csv file upload ---------
                   3934: #
                   3935: #-------------------------------------------------------------------
                   3936: #
1.122     ng       3937: #-------------- Next few routines handle grading by page/sequence
1.72      ng       3938: #
                   3939: #--- Select a page/sequence and a student to grade
1.68      ng       3940: sub pickStudentPage {
                   3941:     my ($request) = shift;
                   3942: 
                   3943:     $request->print(<<LISTJAVASCRIPT);
                   3944: <script type="text/javascript" language="javascript">
                   3945: 
                   3946: function checkPickOne(formname) {
1.76      ng       3947:     if (radioSelection(formname.student) == null) {
1.68      ng       3948: 	alert("Please select the student you wish to grade.");
                   3949: 	return;
                   3950:     }
1.125     ng       3951:     ptr = pullDownSelection(formname.selectpage);
                   3952:     formname.page.value = formname["page"+ptr].value;
                   3953:     formname.title.value = formname["title"+ptr].value;
1.68      ng       3954:     formname.submit();
                   3955: }
                   3956: 
                   3957: </script>
                   3958: LISTJAVASCRIPT
1.118     ng       3959:     &commonJSfunctions($request);
1.324     albertel 3960:     my ($symb) = &get_symb($request);
1.257     albertel 3961:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3962:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3963:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       3964: 
1.398     albertel 3965:     my $result='<h3><span class="LC_info">&nbsp;'.
                   3966: 	'Manual Grading by Page or Sequence</span></h3>';
1.68      ng       3967: 
1.80      ng       3968:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.70      ng       3969:     $result.='&nbsp;<b>Problems from:</b> <select name="selectpage">'."\n";
1.423     albertel 3970:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 3971:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   3972: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   3973: #    my $type=($curpage =~ /\.(page|sequence)/);
1.70      ng       3974:     my $ctr=0;
1.68      ng       3975:     foreach (@$titles) {
                   3976: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.70      ng       3977: 	$result.='<option value="'.$ctr.'" '.
1.401     albertel 3978: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       3979: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       3980: 	$ctr++;
1.68      ng       3981:     }
1.326     albertel 3982:     $result.= '</select>'."<br />\n";
1.70      ng       3983:     $ctr=0;
                   3984:     foreach (@$titles) {
                   3985: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   3986: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   3987: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   3988: 	$ctr++;
                   3989:     }
1.72      ng       3990:     $result.='<input type="hidden" name="page" />'."\n".
                   3991: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       3992: 
1.401     albertel 3993:     $result.='&nbsp;<b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.288     albertel 3994: 	'<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
1.72      ng       3995: 
1.71      ng       3996:     $result.='&nbsp;<b>Submission Details: </b>'.
1.288     albertel 3997: 	'<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
1.401     albertel 3998: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
1.288     albertel 3999: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
1.432     banghart 4000:     
                   4001:     $result.=&build_section_inputs();
1.442     banghart 4002:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4003:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4004: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4005: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4006: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4007: 
1.382     albertel 4008:     $result.='&nbsp;<b>'.&mt('Use CODE:').' </b>'.
                   4009: 	'<input type="text" name="CODE" value="" /><br />'."\n";
                   4010: 
1.80      ng       4011:     $result.='&nbsp;<input type="button" '.
1.126     ng       4012: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
1.72      ng       4013: 
1.68      ng       4014:     $request->print($result);
                   4015: 
1.326     albertel 4016:     my $studentTable.='&nbsp;<b>Select a student you wish to grade and then click on the Next button.</b><br />'.
1.68      ng       4017: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   4018: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.126     ng       4019: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       4020: 	'<td>'.&nameUserString('header').'</td>'.
1.126     ng       4021: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       4022: 	'<td>'.&nameUserString('header').'</td></tr>';
1.68      ng       4023:  
1.76      ng       4024:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4025:     my $ptr = 1;
1.294     albertel 4026:     foreach my $student (sort 
                   4027: 			 {
                   4028: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4029: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4030: 			     }
                   4031: 			     return $a cmp $b;
                   4032: 			 } (keys(%$fullname))) {
1.68      ng       4033: 	my ($uname,$udom) = split(/:/,$student);
1.126     ng       4034: 	$studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
                   4035: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4036: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4037: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.126     ng       4038: 	$studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
1.68      ng       4039: 	$ptr++;
                   4040:     }
1.381     albertel 4041:     $studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td></tr>' if ($ptr%2 == 0);
                   4042:     $studentTable.='</table></td></tr></table>'."\n";
1.126     ng       4043:     $studentTable.='<input type="button" '.
                   4044: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
1.68      ng       4045: 
1.324     albertel 4046:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4047:     $request->print($studentTable);
                   4048: 
                   4049:     return '';
                   4050: }
                   4051: 
                   4052: sub getSymbMap {
1.132     bowersj2 4053:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       4054: 
                   4055:     my %symbx = ();
                   4056:     my @titles = ();
1.117     bowersj2 4057:     my $minder = 0;
                   4058: 
                   4059:     # Gather every sequence that has problems.
1.240     albertel 4060:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4061: 					       1,0,1);
1.117     bowersj2 4062:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4063: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4064: 	    my $title = $minder.'.'.
                   4065: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4066: 	    push(@titles, $title); # minder in case two titles are identical
                   4067: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4068: 	    $minder++;
1.241     albertel 4069: 	}
1.68      ng       4070:     }
                   4071:     return \@titles,\%symbx;
                   4072: }
                   4073: 
1.72      ng       4074: #
                   4075: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4076: sub displayPage {
                   4077:     my ($request) = shift;
                   4078: 
1.324     albertel 4079:     my ($symb) = &get_symb($request);
1.257     albertel 4080:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4081:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4082:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4083:     my $pageTitle = $env{'form.page'};
1.103     albertel 4084:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4085:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4086:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4087: 
                   4088:     #need to make sure we have the correct data for later EXT calls, 
                   4089:     #thus invalidate the cache
                   4090:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4091:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4092:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4093:     &Apache::lonnet::clear_EXT_cache_status();
                   4094: 
1.103     albertel 4095:     if (!&canview($usec)) {
1.398     albertel 4096: 	$request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
1.324     albertel 4097: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4098: 	return;
                   4099:     }
1.398     albertel 4100:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4101:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
1.129     ng       4102: 	'</h3>'."\n";
1.382     albertel 4103:     if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4104: 	$result.='<h3>&nbsp;CODE: '.$env{'form.CODE'}.'</h3>'."\n";
                   4105:     } else {
                   4106: 	delete($env{'form.CODE'});
                   4107:     }
1.71      ng       4108:     &sub_page_js($request);
                   4109:     $request->print($result);
                   4110: 
1.132     bowersj2 4111:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4112:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4113:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4114:     if (!$map) {
1.398     albertel 4115: 	$request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4116: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4117: 	return; 
                   4118:     }
1.68      ng       4119:     my $iterator = $navmap->getIterator($map->map_start(),
                   4120: 					$map->map_finish());
                   4121: 
1.71      ng       4122:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4123: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4124: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4125: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4126: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4127: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4128: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4129: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4130: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4131: 
1.382     albertel 4132:     if (defined($env{'form.CODE'})) {
                   4133: 	$studentTable.=
                   4134: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4135:     }
1.381     albertel 4136:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   4137: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       4138: 	'/check.gif" height="16" border="0" />';
                   4139: 
1.118     ng       4140:     $studentTable.='&nbsp;<b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
                   4141: 	' symbol.'."\n".
1.71      ng       4142: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   4143: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.118     ng       4144: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.257     albertel 4145: 	'<td><b>&nbsp;'.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
1.71      ng       4146: 
1.329     albertel 4147:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4148:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4149:     $iterator->next(); # skip the first BEGIN_MAP
                   4150:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4151:     while ($depth > 0) {
1.68      ng       4152:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4153:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4154: 
1.385     albertel 4155:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4156: 	    my $parts = $curRes->parts();
1.68      ng       4157:             my $title = $curRes->compTitle();
1.71      ng       4158: 	    my $symbx = $curRes->symb();
1.196     albertel 4159: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4160: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4161: 	    $studentTable.='<td valign="top">';
1.382     albertel 4162: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4163: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4164: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4165: 					     undef,'both',\%form);
1.71      ng       4166: 	    } else {
1.382     albertel 4167: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4168: 		$companswer =~ s|<form(.*?)>||g;
                   4169: 		$companswer =~ s|</form>||g;
1.71      ng       4170: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4171: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4172: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4173: #		}
1.116     ng       4174: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.326     albertel 4175: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>Correct answer:</b><br />'.$companswer;
1.71      ng       4176: 	    }
                   4177: 
1.257     albertel 4178: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4179: 
1.257     albertel 4180: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4181: 		if ($record{'version'} eq '') {
1.398     albertel 4182: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">No recorded submission for this problem</span><br />';
1.71      ng       4183: 		} else {
1.116     ng       4184: 		    my %responseType = ();
                   4185: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4186: 			my @responseIds =$curRes->responseIds($partid);
                   4187: 			my @responseType =$curRes->responseType($partid);
                   4188: 			my %responseIds;
                   4189: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4190: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4191: 			}
                   4192: 			$responseType{$partid} = \%responseIds;
1.116     ng       4193: 		    }
1.148     albertel 4194: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4195: 
1.71      ng       4196: 		}
1.257     albertel 4197: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4198: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4199: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4200: 									$env{'request.course.id'},
1.71      ng       4201: 									'','.submission');
                   4202:  
                   4203: 	    }
1.103     albertel 4204: 	    if (&canmodify($usec)) {
                   4205: 		foreach my $partid (@{$parts}) {
                   4206: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4207: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4208: 		    $question++;
                   4209: 		}
1.196     albertel 4210: 		$prob++;
1.71      ng       4211: 	    }
                   4212: 	    $studentTable.='</td></tr>';
1.68      ng       4213: 
1.103     albertel 4214: 	}
1.68      ng       4215:         $curRes = $iterator->next();
                   4216:     }
                   4217: 
1.381     albertel 4218:     $studentTable.='</table></td></tr></table>'."\n".
1.125     ng       4219: 	'<input type="button" value="Save" '.
1.381     albertel 4220: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4221: 	'</form>'."\n";
1.324     albertel 4222:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4223:     $request->print($studentTable);
                   4224: 
                   4225:     return '';
1.119     ng       4226: }
                   4227: 
                   4228: sub displaySubByDates {
1.148     albertel 4229:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4230:     my $isCODE=0;
1.335     albertel 4231:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4232:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.119     ng       4233:     my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
                   4234: 	'<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
                   4235: 	'<td><b>Date/Time</b></td>'.
1.224     albertel 4236: 	($isCODE?'<td><b>CODE</b></td>':'').
1.119     ng       4237: 	'<td><b>Submission</b></td>'.
                   4238: 	'<td><b>Status&nbsp;</b></td></tr>';
                   4239:     my ($version);
                   4240:     my %mark;
1.148     albertel 4241:     my %orders;
1.119     ng       4242:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4243:     if (!exists($$record{'1:timestamp'})) {
1.398     albertel 4244: 	return '<br />&nbsp;<span class="LC_warning">Nothing submitted - no attempts</span><br />';
1.147     albertel 4245:     }
1.335     albertel 4246: 
                   4247:     my $interaction;
1.119     ng       4248:     for ($version=1;$version<=$$record{'version'};$version++) {
                   4249: 	my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
1.335     albertel 4250: 	if (exists($$record{$version.':resource.0.version'})) {
                   4251: 	    $interaction = $$record{$version.':resource.0.version'};
                   4252: 	}
                   4253: 
                   4254: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4255: 		             : "$version:resource");
1.119     ng       4256: 	$studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
1.224     albertel 4257: 	if ($isCODE) {
                   4258: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4259: 	}
1.119     ng       4260: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4261: 	my @displaySub = ();
                   4262: 	foreach my $partid (@{$parts}) {
1.335     albertel 4263: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4264: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4265: 	    
                   4266: 
1.122     ng       4267: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4268: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4269: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4270: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4271: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4272: 
                   4273: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4274: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.207     albertel 4275: 		    $displaySub[0].='<b>Part:</b>&nbsp;'.$display_part.'&nbsp;';
1.398     albertel 4276: 		    $displaySub[0].='<span class="LC_internal_info">(ID&nbsp;'.
                   4277: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4278: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.147     albertel 4279: 			$displaySub[0].='Trial&nbsp;not&nbsp;counted';
                   4280: 		    } else {
                   4281: 			$displaySub[0].='Trial&nbsp;'.
1.335     albertel 4282: 			    $$record{"$where.$partid.tries"};
1.147     albertel 4283: 		    }
1.335     albertel 4284: 		    my $responseType=($isTask ? 'Task'
                   4285:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4286: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4287: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4288: 			$orders{$partid}->{$responseId}=
                   4289: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
                   4290: 		    }
1.147     albertel 4291: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4292: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4293: 		}
                   4294: 	    }
1.335     albertel 4295: 	    if (exists($$record{"$where.$partid.checkedin"})) {
                   4296: 		$displaySub[1].='Checked in by '.
                   4297: 		    $$record{"$where.$partid.checkedin"}.' into slot '.
                   4298: 		    $$record{"$where.$partid.checkedin.slot"}.
                   4299: 		    '<br />';
                   4300: 	    }
                   4301: 	    if (exists $$record{"$where.$partid.award"}) {
1.207     albertel 4302: 		$displaySub[1].='<b>Part:</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4303: 		    lc($$record{"$where.$partid.award"}).' '.
                   4304: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4305: 		    '<br />';
                   4306: 	    }
1.335     albertel 4307: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4308: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4309: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4310: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4311: 		$displaySub[2].=
                   4312: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4313: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4314: 	    }
                   4315: 	}
                   4316: 	# needed because old essay regrader has not parts info
                   4317: 	if (exists $$record{"$version:resource.regrader"}) {
                   4318: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4319: 	}
                   4320: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4321: 	if ($displaySub[2]) {
                   4322: 	    $studentTable.='Manually graded by '.$displaySub[2];
                   4323: 	}
1.382     albertel 4324: 	$studentTable.='&nbsp;</td></tr>';
1.147     albertel 4325:     
1.119     ng       4326:     }
                   4327:     $studentTable.='</table></td></tr></table>';
                   4328:     return $studentTable;
1.71      ng       4329: }
                   4330: 
                   4331: sub updateGradeByPage {
                   4332:     my ($request) = shift;
                   4333: 
1.257     albertel 4334:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4335:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4336:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4337:     my $pageTitle = $env{'form.page'};
1.103     albertel 4338:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4339:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4340:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4341:     if (!&canmodify($usec)) {
1.398     albertel 4342: 	$request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
1.324     albertel 4343: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4344: 	return;
                   4345:     }
1.398     albertel 4346:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4347:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4348: 	'</h3>'."\n";
1.70      ng       4349: 
1.68      ng       4350:     $request->print($result);
                   4351: 
1.132     bowersj2 4352:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4353:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4354:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4355:     if (!$map) {
1.398     albertel 4356: 	$request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4357: 	my ($symb)=&get_symb($request);
                   4358: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4359: 	return; 
                   4360:     }
1.71      ng       4361:     my $iterator = $navmap->getIterator($map->map_start(),
                   4362: 					$map->map_finish());
1.70      ng       4363: 
1.71      ng       4364:     my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
1.68      ng       4365: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.125     ng       4366: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.71      ng       4367: 	'<td><b>&nbsp;Title&nbsp;</b></td>'.
                   4368: 	'<td><b>&nbsp;Previous Score&nbsp;</b></td>'.
                   4369: 	'<td><b>&nbsp;New Score&nbsp;</b></td></tr>';
                   4370: 
                   4371:     $iterator->next(); # skip the first BEGIN_MAP
                   4372:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4373:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4374:     while ($depth > 0) {
1.71      ng       4375:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4376:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4377: 
1.385     albertel 4378:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4379: 	    my $parts = $curRes->parts();
1.71      ng       4380:             my $title = $curRes->compTitle();
                   4381: 	    my $symbx = $curRes->symb();
1.196     albertel 4382: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4383: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4384: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4385: 
                   4386: 	    my %newrecord=();
                   4387: 	    my @displayPts=();
1.269     raeburn  4388:             my %aggregate = ();
                   4389:             my $aggregateflag = 0;
1.71      ng       4390: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4391: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4392: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4393: 
1.257     albertel 4394: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4395: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4396: 		my $partial = $newpts/$wgt;
                   4397: 		my $score;
                   4398: 		if ($partial > 0) {
                   4399: 		    $score = 'correct_by_override';
1.125     ng       4400: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4401: 		    $score = 'incorrect_by_override';
                   4402: 		}
1.257     albertel 4403: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4404: 		if ($dropMenu eq 'excused') {
1.71      ng       4405: 		    $partial = '';
                   4406: 		    $score = 'excused';
1.125     ng       4407: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4408: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4409: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4410: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4411: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4412: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4413: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4414: 		    $changeflag++;
                   4415: 		    $newpts = '';
1.269     raeburn  4416:                     
                   4417:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4418:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4419:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4420:                     if ($aggtries > 0) {
                   4421:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4422:                         $aggregateflag = 1;
                   4423:                     }
1.71      ng       4424: 		}
1.324     albertel 4425: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4426: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.207     albertel 4427: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.71      ng       4428: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4429: 		    '&nbsp;<br />';
1.207     albertel 4430: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.125     ng       4431: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4432: 		    '&nbsp;<br />';
1.71      ng       4433: 		$question++;
1.380     albertel 4434: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4435: 
1.71      ng       4436: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4437: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4438: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4439: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4440: 
                   4441: 		$changeflag++;
                   4442: 	    }
                   4443: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4444: 		my %record = 
                   4445: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4446: 					     $udom,$uname);
                   4447: 
                   4448: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4449: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4450: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4451: 		    $newrecord{'resource.CODE'} = '';
                   4452: 		}
1.257     albertel 4453: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4454: 					$udom,$uname);
1.382     albertel 4455: 		%record = &Apache::lonnet::restore($symbx,
                   4456: 						   $env{'request.course.id'},
                   4457: 						   $udom,$uname);
1.380     albertel 4458: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4459: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4460: 	    }
1.380     albertel 4461: 	    
1.269     raeburn  4462:             if ($aggregateflag) {
                   4463:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4464:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4465:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4466:             }
1.125     ng       4467: 
1.71      ng       4468: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4469: 		'<td valign="top">'.$displayPts[1].'</td>'.
                   4470: 		'</tr>';
1.68      ng       4471: 
1.196     albertel 4472: 	    $prob++;
1.68      ng       4473: 	}
1.71      ng       4474:         $curRes = $iterator->next();
1.68      ng       4475:     }
1.98      albertel 4476: 
1.71      ng       4477:     $studentTable.='</td></tr></table></td></tr></table>';
1.324     albertel 4478:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.76      ng       4479:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
                   4480: 		  'The scores were changed for '.
                   4481: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
                   4482:     $request->print($grademsg.$studentTable);
1.68      ng       4483: 
1.70      ng       4484:     return '';
                   4485: }
                   4486: 
1.72      ng       4487: #-------- end of section for handling grading by page/sequence ---------
                   4488: #
                   4489: #-------------------------------------------------------------------
                   4490: 
1.75      albertel 4491: #--------------------Scantron Grading-----------------------------------
                   4492: #
                   4493: #------ start of section for handling grading by page/sequence ---------
                   4494: 
1.423     albertel 4495: =pod
                   4496: 
                   4497: =head1 Bubble sheet grading routines
                   4498: 
1.424     albertel 4499:   For this documentation:
                   4500: 
                   4501:    'scanline' refers to the full line of characters
                   4502:    from the file that we are parsing that represents one entire sheet
                   4503: 
                   4504:    'bubble line' refers to the data
                   4505:    representing the line of bubbles that are on the physical bubble sheet
                   4506: 
                   4507: 
                   4508: The overall process is that a scanned in bubble sheet data is uploaded
                   4509: into a course. When a user wants to grade, they select a
                   4510: sequence/folder of resources, a file of bubble sheet info, and pick
                   4511: one of the predefined configurations for what each scanline looks
                   4512: like.
                   4513: 
                   4514: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4515: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4516: because too light bubbling), 'double bubble' (each bubble line should
                   4517: have no more that one letter picked), invalid or duplicated CODE,
                   4518: invalid student ID
                   4519: 
                   4520: If the CODE option is used that determines the randomization of the
                   4521: homework problems, either way the student ID is looked up into a
                   4522: username:domain.
                   4523: 
                   4524: During the validation phase the instructor can choose to skip scanlines. 
                   4525: 
1.435     foxr     4526: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4527: 
                   4528:   scantron_original_filename (unmodified original file)
                   4529:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4530:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4531: 
                   4532: Also there is a separate hash nohist_scantrondata that contains extra
                   4533: correction information that isn't representable in the bubble sheet
                   4534: file (see &scantron_getfile() for more information)
                   4535: 
                   4536: After all scanlines are either valid, marked as valid or skipped, then
                   4537: foreach line foreach problem in the picked sequence, an ssi request is
                   4538: made that simulates a user submitting their selected letter(s) against
                   4539: the homework problem.
1.423     albertel 4540: 
                   4541: =over 4
                   4542: 
                   4543: 
                   4544: 
                   4545: =item defaultFormData
                   4546: 
                   4547:   Returns html hidden inputs used to hold context/default values.
                   4548: 
                   4549:  Arguments:
                   4550:   $symb - $symb of the current resource 
                   4551: 
                   4552: =cut
1.422     foxr     4553: 
1.81      albertel 4554: sub defaultFormData {
1.324     albertel 4555:     my ($symb)=@_;
1.447   ! foxr     4556:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4557:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4558:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4559: }
                   4560: 
1.447   ! foxr     4561: 
1.423     albertel 4562: =pod 
                   4563: 
                   4564: =item getSequenceDropDown
                   4565: 
                   4566:    Return html dropdown of possible sequences to grade
                   4567:  
                   4568:  Arguments:
                   4569:    $symb - $symb of the current resource 
                   4570: 
                   4571: =cut
1.422     foxr     4572: 
1.75      albertel 4573: sub getSequenceDropDown {
1.423     albertel 4574:     my ($symb)=@_;
1.75      albertel 4575:     my $result='<select name="selectpage">'."\n";
1.423     albertel 4576:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4577:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4578:     my $ctr=0;
                   4579:     foreach (@$titles) {
                   4580: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4581: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4582: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4583: 	    '>'.$showtitle.'</option>'."\n";
                   4584: 	$ctr++;
                   4585:     }
                   4586:     $result.= '</select>';
                   4587:     return $result;
                   4588: }
                   4589: 
1.423     albertel 4590: 
                   4591: =pod 
                   4592: 
                   4593: =item scantron_filenames
                   4594: 
                   4595:    Returns a list of the scantron files in the current course 
                   4596: 
                   4597: =cut
1.422     foxr     4598: 
1.202     albertel 4599: sub scantron_filenames {
1.257     albertel 4600:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4601:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.157     albertel 4602:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.359     www      4603: 				    &propath($cdom,$cname));
1.202     albertel 4604:     my @possiblenames;
1.201     albertel 4605:     foreach my $filename (sort(@files)) {
1.157     albertel 4606: 	($filename)=split(/&/,$filename);
                   4607: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4608: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4609: 	push(@possiblenames,$filename);
                   4610:     }
                   4611:     return @possiblenames;
                   4612: }
                   4613: 
1.423     albertel 4614: =pod 
                   4615: 
                   4616: =item scantron_uploads
                   4617: 
                   4618:    Returns  html drop-down list of scantron files in current course.
                   4619: 
                   4620:  Arguments:
                   4621:    $file2grade - filename to set as selected in the dropdown
                   4622: 
                   4623: =cut
1.422     foxr     4624: 
1.202     albertel 4625: sub scantron_uploads {
1.209     ng       4626:     my ($file2grade) = @_;
1.202     albertel 4627:     my $result=	'<select name="scantron_selectfile">';
                   4628:     $result.="<option></option>";
                   4629:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4630: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4631:     }
                   4632:     $result.="</select>";
                   4633:     return $result;
                   4634: }
                   4635: 
1.423     albertel 4636: =pod 
                   4637: 
                   4638: =item scantron_scantab
                   4639: 
                   4640:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4641:   file.
                   4642: 
                   4643: =cut
1.422     foxr     4644: 
1.82      albertel 4645: sub scantron_scantab {
                   4646:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4647:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4648:     $result.='<option></option>'."\n";
1.82      albertel 4649:     foreach my $line (<$fh>) {
                   4650: 	my ($name,$descrip)=split(/:/,$line);
                   4651: 	if ($name =~ /^\#/) { next; }
                   4652: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4653:     }
                   4654:     $result.='</select>'."\n";
                   4655: 
                   4656:     return $result;
                   4657: }
                   4658: 
1.423     albertel 4659: =pod 
                   4660: 
                   4661: =item scantron_CODElist
                   4662: 
                   4663:   Returns html drop down of the saved CODE lists from current course,
                   4664:   generated from earlier printings.
                   4665: 
                   4666: =cut
1.422     foxr     4667: 
1.186     albertel 4668: sub scantron_CODElist {
1.257     albertel 4669:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4670:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4671:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4672:     my $namechoice='<option></option>';
1.225     albertel 4673:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4674: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4675: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4676: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4677:     }
                   4678:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4679:     return $namechoice;
                   4680: }
                   4681: 
1.423     albertel 4682: =pod 
                   4683: 
                   4684: =item scantron_CODEunique
                   4685: 
                   4686:   Returns the html for "Each CODE to be used once" radio.
                   4687: 
                   4688: =cut
1.422     foxr     4689: 
1.186     albertel 4690: sub scantron_CODEunique {
1.381     albertel 4691:     my $result='<span style="white-space: nowrap;">
1.272     albertel 4692:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4693:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 4694:                 </span>
                   4695:                 <span style="white-space: nowrap;">
1.272     albertel 4696:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4697:                         value="no" />'.&mt('No').' </label>
1.381     albertel 4698:                 </span>';
1.186     albertel 4699:     return $result;
                   4700: }
1.423     albertel 4701: 
                   4702: =pod 
                   4703: 
                   4704: =item scantron_selectphase
                   4705: 
                   4706:   Generates the initial screen to start the bubble sheet process.
                   4707:   Allows for - starting a grading run.
1.424     albertel 4708:              - downloading existing scan data (original, corrected
1.423     albertel 4709:                                                 or skipped info)
                   4710: 
                   4711:              - uploading new scan data
                   4712: 
                   4713:  Arguments:
                   4714:   $r          - The Apache request object
                   4715:   $file2grade - name of the file that contain the scanned data to score
                   4716: 
                   4717: =cut
1.186     albertel 4718: 
1.75      albertel 4719: sub scantron_selectphase {
1.209     ng       4720:     my ($r,$file2grade) = @_;
1.324     albertel 4721:     my ($symb)=&get_symb($r);
1.75      albertel 4722:     if (!$symb) {return '';}
1.423     albertel 4723:     my $sequence_selector=&getSequenceDropDown($symb);
1.324     albertel 4724:     my $default_form_data=&defaultFormData($symb);
                   4725:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       4726:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 4727:     my $format_selector=&scantron_scantab();
1.186     albertel 4728:     my $CODE_selector=&scantron_CODElist();
                   4729:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 4730:     my $result;
1.422     foxr     4731: 
                   4732:     # Chunk of form to prompt for a file to grade and how:
                   4733: 
1.75      albertel 4734:     $result.= <<SCANTRONFORM;
1.162     albertel 4735:     <table width="100%" border="0">
1.75      albertel 4736:     <tr>
1.226     albertel 4737:      <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
1.75      albertel 4738:       <td bgcolor="#777777">
1.203     albertel 4739:        <input type="hidden" name="command" value="scantron_warning" />
1.162     albertel 4740:         $default_form_data
1.75      albertel 4741:         <table width="100%" border="0">
                   4742:           <tr bgcolor="#e6ffff">
1.174     albertel 4743:             <td colspan="2">
                   4744:               &nbsp;<b>Specify file and which Folder/Sequence to grade</b>
1.75      albertel 4745:             </td>
                   4746:           </tr>
                   4747:           <tr bgcolor="#ffffe6">
1.174     albertel 4748:             <td> Sequence to grade: </td><td> $sequence_selector </td>
1.75      albertel 4749:           </tr>
                   4750:           <tr bgcolor="#ffffe6">
1.174     albertel 4751:             <td> Filename of scoring office file: </td><td> $file_selector </td>
1.75      albertel 4752:           </tr>
1.82      albertel 4753:           <tr bgcolor="#ffffe6">
1.174     albertel 4754:             <td> Format of data file: </td><td> $format_selector </td>
1.82      albertel 4755:           </tr>
1.157     albertel 4756:           <tr bgcolor="#ffffe6">
1.186     albertel 4757:             <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
                   4758:           </tr>
                   4759:           <tr bgcolor="#ffffe6">
                   4760:             <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
                   4761:           </tr>
                   4762:           <tr bgcolor="#ffffe6">
1.187     albertel 4763: 	    <td> Options: </td>
                   4764:             <td>
1.272     albertel 4765: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
1.424     albertel 4766:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
1.331     albertel 4767:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
1.187     albertel 4768: 	    </td>
                   4769:           </tr>
                   4770:           <tr bgcolor="#ffffe6">
1.174     albertel 4771:             <td colspan="2">
1.265     www      4772:               <input type="submit" value="Grading: Validate Scantron Records" />
1.162     albertel 4773:             </td>
                   4774:           </tr>
                   4775:         </table>
1.226     albertel 4776:        </td>
                   4777:      </form>
1.162     albertel 4778:     </tr>
                   4779: SCANTRONFORM
                   4780:    
                   4781:     $r->print($result);
                   4782: 
1.257     albertel 4783:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   4784:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 4785: 
1.422     foxr     4786: 	# Chunk of form to prompt for a scantron file upload.
                   4787: 
1.162     albertel 4788:         $r->print(<<SCANTRONFORM);
                   4789:     <tr>
                   4790:       <td bgcolor="#777777">
                   4791:         <table width="100%" border="0">
                   4792:           <tr bgcolor="#e6ffff">
                   4793:             <td>
1.174     albertel 4794:               &nbsp;<b>Specify a Scantron data file to upload.</b>
1.162     albertel 4795:             </td>
                   4796:           </tr>
                   4797:           <tr bgcolor="#ffffe6">
                   4798:             <td>
                   4799: SCANTRONFORM
1.324     albertel 4800:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 4801:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4802:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.174     albertel 4803:     $r->print(<<UPLOAD);
                   4804:               <script type="text/javascript" language="javascript">
                   4805:     function checkUpload(formname) {
                   4806: 	if (formname.upfile.value == "") {
                   4807: 	    alert("Please use the browse button to select a file from your local directory.");
                   4808: 	    return false;
                   4809: 	}
                   4810: 	formname.submit();
                   4811:     }
                   4812:               </script>
                   4813: 
                   4814:               <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
                   4815:                 $default_form_data
                   4816:                 <input name='courseid' type='hidden' value='$cnum' />
                   4817:                 <input name='domainid' type='hidden' value='$cdom' />
                   4818:                 <input name='command' value='scantronupload_save' type='hidden' />
                   4819:                 File to upload:<input type="file" name="upfile" size="50" />
                   4820:                 <br />
                   4821:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   4822:               </form>
                   4823: UPLOAD
1.162     albertel 4824: 
                   4825:         $r->print(<<SCANTRONFORM);
                   4826:             </td>
                   4827:           </tr>
1.75      albertel 4828:         </table>
                   4829:       </td>
                   4830:     </tr>
1.162     albertel 4831: SCANTRONFORM
                   4832:     }
1.422     foxr     4833: 
                   4834:     # Chunk of the form that prompts to view a scoring office file,
                   4835:     # corrected file, skipped records in a file.
                   4836: 
1.187     albertel 4837:     $r->print(<<SCANTRONFORM);
                   4838:     <tr>
1.226     albertel 4839:       <form action='/adm/grades' name='scantron_download'>
                   4840:         <td bgcolor="#777777">
1.379     albertel 4841: 	  $default_form_data
1.187     albertel 4842:           <input type="hidden" name="command" value="scantron_download" />
                   4843:           <table width="100%" border="0">
                   4844:             <tr bgcolor="#e6ffff">
                   4845:               <td colspan="2">
                   4846:                 &nbsp;<b>Download a scoring office file</b>
                   4847:               </td>
                   4848:             </tr>
                   4849:             <tr bgcolor="#ffffe6">
                   4850:               <td> Filename of scoring office file: </td><td> $file_selector </td>
                   4851:             </tr>
                   4852:             <tr bgcolor="#ffffe6">
                   4853:               <td colspan="2">
1.293     www      4854:                 <input type="submit" value="Download: Show List of Associated Files" />
1.187     albertel 4855:               </td>
                   4856:             </tr>
                   4857:           </table>
1.226     albertel 4858:         </td>
                   4859:       </form>
1.187     albertel 4860:     </tr>
                   4861: SCANTRONFORM
1.162     albertel 4862: 
                   4863:     $r->print(<<SCANTRONFORM);
1.75      albertel 4864:   </table>
1.81      albertel 4865: $grading_menu_button
1.75      albertel 4866: SCANTRONFORM
                   4867: 
1.162     albertel 4868:     return
1.75      albertel 4869: }
                   4870: 
1.423     albertel 4871: =pod
                   4872: 
                   4873: =item get_scantron_config
                   4874: 
                   4875:    Parse and return the scantron configuration line selected as a
                   4876:    hash of configuration file fields.
                   4877: 
                   4878:  Arguments:
                   4879:     which - the name of the configuration to parse from the file.
                   4880: 
                   4881: 
                   4882:  Returns:
                   4883:             If the named configuration is not in the file, an empty
                   4884:             hash is returned.
                   4885:     a hash with the fields
                   4886:       name         - internal name for the this configuration setup
                   4887:       description  - text to display to operator that describes this config
                   4888:       CODElocation - if 0 or the string 'none'
                   4889:                           - no CODE exists for this config
                   4890:                      if -1 || the string 'letter'
                   4891:                           - a CODE exists for this config and is
                   4892:                             a string of letters
                   4893:                      Unsupported value (but planned for future support)
                   4894:                           if a positive integer
                   4895:                                - The CODE exists as the first n items from
                   4896:                                  the question section of the form
                   4897:                           if the string 'number'
                   4898:                                - The CODE exists for this config and is
                   4899:                                  a string of numbers
                   4900:       CODEstart   - (only matter if a CODE exists) column in the line where
                   4901:                      the CODE starts
                   4902:       CODElength  - length of the CODE
                   4903:       IDstart     - column where the student ID number starts
                   4904:       IDlength    - length of the student ID info
                   4905:       Qstart      - column where the information from the bubbled
                   4906:                     'questions' start
                   4907:       Qlength     - number of columns comprising a single bubble line from
                   4908:                     the sheet. (usually either 1 or 10)
1.424     albertel 4909:       Qon         - either a single character representing the character used
1.423     albertel 4910:                     to signal a bubble was chosen in the positional setup, or
                   4911:                     the string 'letter' if the letter of the chosen bubble is
                   4912:                     in the final, or 'number' if a number representing the
                   4913:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 4914:       Qoff        - the character used to represent that a bubble was
                   4915:                     left blank
1.423     albertel 4916:       PaperID     - if the scanning process generates a unique number for each
                   4917:                     sheet scanned the column that this ID number starts in
                   4918:       PaperIDlength - number of columns that comprise the unique ID number
                   4919:                       for the sheet of paper
1.424     albertel 4920:       FirstName   - column that the first name starts in
1.423     albertel 4921:       FirstNameLength - number of columns that the first name spans
                   4922:  
                   4923:       LastName    - column that the last name starts in
                   4924:       LastNameLength - number of columns that the last name spans
                   4925: 
                   4926: =cut
1.422     foxr     4927: 
1.82      albertel 4928: sub get_scantron_config {
                   4929:     my ($which) = @_;
                   4930:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4931:     my %config;
1.157     albertel 4932:     #FIXME probably should move to XML it has already gotten a bit much now
1.82      albertel 4933:     foreach my $line (<$fh>) {
                   4934: 	my ($name,$descrip)=split(/:/,$line);
                   4935: 	if ($name ne $which ) { next; }
                   4936: 	chomp($line);
                   4937: 	my @config=split(/:/,$line);
                   4938: 	$config{'name'}=$config[0];
                   4939: 	$config{'description'}=$config[1];
                   4940: 	$config{'CODElocation'}=$config[2];
                   4941: 	$config{'CODEstart'}=$config[3];
                   4942: 	$config{'CODElength'}=$config[4];
                   4943: 	$config{'IDstart'}=$config[5];
                   4944: 	$config{'IDlength'}=$config[6];
                   4945: 	$config{'Qstart'}=$config[7];
                   4946: 	$config{'Qlength'}=$config[8];
                   4947: 	$config{'Qoff'}=$config[9];
                   4948: 	$config{'Qon'}=$config[10];
1.157     albertel 4949: 	$config{'PaperID'}=$config[11];
                   4950: 	$config{'PaperIDlength'}=$config[12];
                   4951: 	$config{'FirstName'}=$config[13];
                   4952: 	$config{'FirstNamelength'}=$config[14];
                   4953: 	$config{'LastName'}=$config[15];
                   4954: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 4955: 	last;
                   4956:     }
                   4957:     return %config;
                   4958: }
                   4959: 
1.423     albertel 4960: =pod 
                   4961: 
                   4962: =item username_to_idmap
                   4963: 
                   4964:     creates a hash keyed by student id with values of the corresponding
                   4965:     student username:domain.
                   4966: 
                   4967:   Arguments:
                   4968: 
                   4969:     $classlist - reference to the class list hash. This is a hash
                   4970:                  keyed by student name:domain  whose elements are references
1.424     albertel 4971:                  to arrays containing various chunks of information
1.423     albertel 4972:                  about the student. (See loncoursedata for more info).
                   4973: 
                   4974:   Returns
                   4975:     %idmap - the constructed hash
                   4976: 
                   4977: =cut
                   4978: 
1.82      albertel 4979: sub username_to_idmap {
                   4980:     my ($classlist)= @_;
                   4981:     my %idmap;
                   4982:     foreach my $student (keys(%$classlist)) {
                   4983: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   4984: 	    $student;
                   4985:     }
                   4986:     return %idmap;
                   4987: }
1.423     albertel 4988: 
                   4989: =pod
                   4990: 
1.424     albertel 4991: =item scantron_fixup_scanline
1.423     albertel 4992: 
                   4993:    Process a requested correction to a scanline.
                   4994: 
                   4995:   Arguments:
                   4996:     $scantron_config   - hash from &get_scantron_config()
                   4997:     $scan_data         - hash of correction information 
                   4998:                           (see &scantron_getfile())
                   4999:     $line              - existing scanline
                   5000:     $whichline         - line number of the passed in scanline
                   5001:     $field             - type of change to process 
                   5002:                          (either 
                   5003:                           'ID'     -> correct the student ID number
                   5004:                           'CODE'   -> correct the CODE
                   5005:                           'answer' -> fixup the submitted answers)
                   5006:     
                   5007:    $args               - hash of additional info,
                   5008:                           - 'ID' 
                   5009:                                'newid' -> studentID to use in replacement
1.424     albertel 5010:                                           of existing one
1.423     albertel 5011:                           - 'CODE' 
                   5012:                                'CODE_ignore_dup' - set to true if duplicates
                   5013:                                                    should be ignored.
                   5014: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5015:                                         if the existing unfound code should
1.423     albertel 5016:                                         be used as is
                   5017:                           - 'answer'
                   5018:                                'response' - new answer or 'none' if blank
                   5019:                                'question' - the bubble line to change
                   5020: 
                   5021:   Returns:
                   5022:     $line - the modified scanline
                   5023: 
                   5024:   Side effects: 
                   5025:     $scan_data - may be updated
                   5026: 
                   5027: =cut
                   5028: 
1.82      albertel 5029: 
1.157     albertel 5030: sub scantron_fixup_scanline {
                   5031:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
1.423     albertel 5032: 
1.157     albertel 5033:     if ($field eq 'ID') {
                   5034: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5035: 	    return ($line,1,'New value too large');
1.157     albertel 5036: 	}
                   5037: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5038: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5039: 				     $args->{'newid'});
                   5040: 	}
                   5041: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5042: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5043: 	if ($args->{'newid'}=~/^\s*$/) {
                   5044: 	    &scan_data($scan_data,"$whichline.user",
                   5045: 		       $args->{'username'}.':'.$args->{'domain'});
                   5046: 	}
1.186     albertel 5047:     } elsif ($field eq 'CODE') {
1.192     albertel 5048: 	if ($args->{'CODE_ignore_dup'}) {
                   5049: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5050: 	}
                   5051: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5052: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5053: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5054: 		return ($line,1,'New CODE value too large');
                   5055: 	    }
                   5056: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5057: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5058: 	    }
                   5059: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5060: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5061: 	}
1.157     albertel 5062:     } elsif ($field eq 'answer') {
                   5063: 	my $length=$scantron_config->{'Qlength'};
                   5064: 	my $off=$scantron_config->{'Qoff'};
                   5065: 	my $on=$scantron_config->{'Qon'};
                   5066: 	my $answer=${off}x$length;
                   5067: 	if ($args->{'response'} eq 'none') {
                   5068: 	    &scan_data($scan_data,
                   5069: 		       "$whichline.no_bubble.".$args->{'question'},'1');
                   5070: 	} else {
1.274     albertel 5071: 	    if ($on eq 'letter') {
                   5072: 		my @alphabet=('A'..'Z');
                   5073: 		$answer=$alphabet[$args->{'response'}];
                   5074: 	    } elsif ($on eq 'number') {
                   5075: 		$answer=$args->{'response'}+1;
1.389     albertel 5076: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5077: 	    } else {
                   5078: 		substr($answer,$args->{'response'},1)=$on;
                   5079: 	    }
1.157     albertel 5080: 	    &scan_data($scan_data,
                   5081: 		       "$whichline.no_bubble.".$args->{'question'},undef,'1');
                   5082: 	}
                   5083: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5084: 	substr($line,$where-1,$length)=$answer;
                   5085:     }
                   5086:     return $line;
                   5087: }
1.423     albertel 5088: 
                   5089: =pod
                   5090: 
                   5091: =item scan_data
                   5092: 
                   5093:     Edit or look up  an item in the scan_data hash.
                   5094: 
                   5095:   Arguments:
                   5096:     $scan_data  - The hash (see scantron_getfile)
                   5097:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5098:                   scantronfilename_key).
1.423     albertel 5099:     $data        - New value of the hash entry.
                   5100:     $delete      - If true, the entry is removed from the hash.
                   5101: 
                   5102:   Returns:
                   5103:     The new value of the hash table field (undefined if deleted).
                   5104: 
                   5105: =cut
                   5106: 
                   5107: 
1.157     albertel 5108: sub scan_data {
                   5109:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5110:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5111:     if (defined($value)) {
                   5112: 	$scan_data->{$filename.'_'.$key} = $value;
                   5113:     }
                   5114:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5115:     return $scan_data->{$filename.'_'.$key};
                   5116: }
1.423     albertel 5117: 
                   5118: =pod 
                   5119: 
                   5120: =item scantron_parse_scanline
                   5121: 
                   5122:   Decodes a scanline from the selected scantron file
                   5123: 
                   5124:  Arguments:
                   5125:     line             - The text of the scantron file line to process
                   5126:     whichline        - Line number
                   5127:     scantron_config  - Hash describing the format of the scantron lines.
                   5128:     scan_data        - Hash of extra information about the scanline
                   5129:                        (see scantron_getfile for more information)
                   5130:     just_header      - True if should not process question answers but only
                   5131:                        the stuff to the left of the answers.
                   5132:  Returns:
                   5133:    Hash containing the result of parsing the scanline
                   5134: 
                   5135:    Keys are all proceeded by the string 'scantron.'
                   5136: 
                   5137:        CODE    - the CODE in use for this scanline
                   5138:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5139:                  by the operator
                   5140:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5141:                             CODEs were selected, but the usage has been
                   5142:                             forced by the operator
                   5143:        ID  - student ID
                   5144:        PaperID - if used, the ID number printed on the sheet when the 
                   5145:                  paper was scanned
                   5146:        FirstName - first name from the sheet
                   5147:        LastName  - last name from the sheet
                   5148: 
                   5149:      if just_header was not true these key may also exist
                   5150: 
1.447   ! foxr     5151:        missingerror - a list of bubble ranges that are considered to be answers
        !          5152:                       to a single question that don't have any bubbles filled in.
        !          5153:                       Of the form questionnumber:firstbubblenumber:count.
        !          5154:        doubleerror  - a list of bubble ranges that are considered to be answers
        !          5155:                       to a single question that have more than one bubble filled in.
        !          5156:                       Of the form questionnumber::firstbubblenumber:count
        !          5157:    
        !          5158:                 In the above, count is the number of bubble responses in the
        !          5159:                 input line needed to represent the possible answers to the question.
        !          5160:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
        !          5161:                 per line would have count = 2.
        !          5162: 
1.423     albertel 5163:        maxquest     - the number of the last bubble line that was parsed
                   5164: 
                   5165:        (<number> starts at 1)
                   5166:        <number>.answer - zero or more letters representing the selected
                   5167:                          letters from the scanline for the bubble line 
                   5168:                          <number>.
                   5169:                          if blank there was either no bubble or there where
                   5170:                          multiple bubbles, (consult the keys missingerror and
                   5171:                          doubleerror if this is an error condition)
                   5172: 
                   5173: =cut
                   5174: 
1.82      albertel 5175: sub scantron_parse_scanline {
1.423     albertel 5176:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.82      albertel 5177:     my %record;
1.422     foxr     5178:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
                   5179:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5180:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5181: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5182: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5183: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5184: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5185: 	    $record{'scantron.CODE'}=substr($data,
                   5186: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5187: 					    $$scantron_config{'CODElength'});
1.191     albertel 5188: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5189: 		$record{'scantron.useCODE'}=1;
                   5190: 	    }
1.192     albertel 5191: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5192: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5193: 	    }
1.82      albertel 5194: 	} else {
                   5195: 	    #FIXME interpret first N questions
                   5196: 	}
                   5197:     }
1.83      albertel 5198:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5199: 				  $$scantron_config{'IDlength'});
1.157     albertel 5200:     $record{'scantron.PaperID'}=
                   5201: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5202: 	       $$scantron_config{'PaperIDlength'});
                   5203:     $record{'scantron.FirstName'}=
                   5204: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5205: 	       $$scantron_config{'FirstNamelength'});
                   5206:     $record{'scantron.LastName'}=
                   5207: 	substr($data,$$scantron_config{'LastName'}-1,
                   5208: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5209:     if ($just_header) { return \%record; }
1.194     albertel 5210: 
1.82      albertel 5211:     my @alphabet=('A'..'Z');
                   5212:     my $questnum=0;
1.447   ! foxr     5213:     my $ansnum  =1;		# Multiple 'answer lines'/question.
        !          5214: 
1.82      albertel 5215:     while ($questions) {
1.447   ! foxr     5216: 	my $answers_needed = $bubble_lines_per_response{$questnum};
        !          5217: 	my $answer_length  = $$scantron_config{'Qlength'} * $answers_needed;
        !          5218: 
        !          5219: 
        !          5220: 
1.82      albertel 5221: 	$questnum++;
1.447   ! foxr     5222: 	my $currentquest = substr($questions,0,$answer_length);
        !          5223: 	$questions       = substr($questions,0,$answer_length)='';
        !          5224: 	if (length($currentquest) < $answer_length) { next; }
        !          5225: 
        !          5226: 	# Qon letter implies for each slot in currentquest we have:
        !          5227: 	#    ? or * for doubles a letter in A-Z for a bubble and
        !          5228:         #    about anything else (esp. a value of Qoff for missing
        !          5229: 	#    bubbles.
        !          5230: 
        !          5231: 
1.239     albertel 5232: 	if ($$scantron_config{'Qon'} eq 'letter') {
1.447   ! foxr     5233: 
        !          5234: 	    if ($currentquest =~ /\?/
        !          5235: 		|| $currentquest =~ /\*/
        !          5236: 		|| (&occurence_count($currentquest, "[A-Z]") > 1)) {
1.274     albertel 5237: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447   ! foxr     5238: 		for (my $ans = 0; $ans < $answers_needed; $ans++) { 
        !          5239: 		    $record{"scantron.$ansnum.answer"}='';
        !          5240: 		    $ansnum++;
        !          5241: 		}
        !          5242: 
1.389     albertel 5243: 	    } elsif (!defined($currentquest)
1.447   ! foxr     5244: 		     || (&occurence_count($currentquest, $$scantron_config{'Qoff'}) == length($currentquest))
        !          5245: 		     || (&occurence_count($currentquest, "[A-Z]") == 0)) {
        !          5246: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
        !          5247: 		    $record{"scantron.$ansnum.answer"}='';
        !          5248: 		    $ansnum++;
        !          5249: 
        !          5250: 		}
1.239     albertel 5251: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5252: 		    push(@{$record{"scantron.missingerror"}},$questnum);
1.447   ! foxr     5253: 		    $ansnum += $answers_needed;
1.239     albertel 5254: 		}
1.447   ! foxr     5255: 
1.239     albertel 5256: 	    } else {
1.447   ! foxr     5257: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
        !          5258: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
        !          5259: 		    $ansnum++;
        !          5260: 		}
1.239     albertel 5261: 	    }
1.447   ! foxr     5262: 
        !          5263: 	# Qon 'number' implies each slot gives a digit that indexes the
        !          5264: 	#    the bubbles filled or Qoff or a non number for unbubbled lines.
        !          5265:         #    and *? for double bubbles on a line.
        !          5266: 	#    these answers are also stored as letters.
        !          5267: 
1.239     albertel 5268: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
1.447   ! foxr     5269: 	    if ($currentquest =~ /\?/
        !          5270: 		|| $currentquest =~ /\*/
        !          5271: 		|| (&occurence_count($currentquest, '\d') > 1)) {
1.274     albertel 5272: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447   ! foxr     5273: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
        !          5274: 		    $record{"scantron.$ansnum.answer"}='';
        !          5275: 		    $ansnum++;
        !          5276: 		}
        !          5277: 
1.389     albertel 5278: 	    } elsif (!defined($currentquest)
1.447   ! foxr     5279: 		     || (&occurence_count($currentquest,$$scantron_config{'Qoff'}) == length($currentquest)) 
        !          5280: 		     || (&occurence_count($currentquest, '\d') == 0)) {
        !          5281: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
        !          5282: 		    $record{"scantron.$ansnum.answer"}='';
        !          5283: 		    $ansnum++;
        !          5284: 
        !          5285: 		}
1.239     albertel 5286: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5287: 		    push(@{$record{"scantron.missingerror"}},$questnum);
1.447   ! foxr     5288: 		    $ansnum += $answers_needed;
1.239     albertel 5289: 		}
1.447   ! foxr     5290: 
1.239     albertel 5291: 	    } else {
1.447   ! foxr     5292: 		$currentquest = &digits_to_letters($currentquest);
        !          5293: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
        !          5294: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
        !          5295: 		    $ansnum++;
1.371     albertel 5296: 		}
1.239     albertel 5297: 	    }
1.82      albertel 5298: 	} else {
1.447   ! foxr     5299: 
        !          5300: 	    # Otherwise there's a positional notation;
        !          5301: 	    # each bubble line requires Qlength items, and there are filled in
        !          5302: 	    # bubbles for each case where there 'Qon' characters.
        !          5303: 	    #
        !          5304: 
1.239     albertel 5305: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
1.447   ! foxr     5306: 
        !          5307: 	    # If the split only  giveas us one element.. the full length of the
        !          5308: 	    # answser string, no bubbles are filled in:
        !          5309: 
        !          5310: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
        !          5311: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
        !          5312: 		    $record{"scantron.$ansnum.answer"}='';
        !          5313: 		    $ansnum++;
        !          5314: 
        !          5315: 		}
1.239     albertel 5316: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5317: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5318: 		}
1.447   ! foxr     5319: 	    } elsif (scalar(@array) lt 2) {
        !          5320: 
        !          5321: 		my $location      = [length($array[0])];
        !          5322: 		my $line_num      = $location / $$scantron_config{'Qlength'};
        !          5323: 		my $bubble        = $alphabet[$location % $$scantron_config{'Qlength'}];
        !          5324: 
        !          5325: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
        !          5326: 		    if ($ans eq $line_num) {
        !          5327: 			$record{"scantron.$ansnum.answer"} = $bubble;
        !          5328: 		    } else {
        !          5329: 			$record{"scantron.$ansnum.answer"} = ' ';
        !          5330: 		    }
        !          5331: 		    $ansnum++;
        !          5332: 		}
1.239     albertel 5333: 	    }
1.447   ! foxr     5334: 	    #  If there's more than one instance of a bubble character
        !          5335: 	    #  That's a double bubble; with positional notation we can
        !          5336: 	    #  record all the bubbles filled in as well as the 
        !          5337: 	    #  fact this response consists of multiple bubbles.
        !          5338: 	    #
        !          5339: 	    else {
1.239     albertel 5340: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447   ! foxr     5341: 
        !          5342: 		my $first_answer = $ansnum;
        !          5343: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
        !          5344: 		    $record{"scantron.$ansnum.answer"} = '';
        !          5345: 		    $ans++;
        !          5346: 		}
        !          5347: 
1.239     albertel 5348: 		my @ans=@array;
                   5349: 		my $i=length($ans[0]);shift(@ans);
                   5350: 		while ($#ans) {
                   5351: 		    $i+=length($ans[0])+1;
1.447   ! foxr     5352: 		    my $line   = $i/$$scantron_config{'Qlength'} + $first_answer;
        !          5353: 		    my $bubble = $i%$$scantron_config{'Qlength'};
        !          5354: 
        !          5355: 		    $record{"scantron.$line.answer"}.=$alphabet[$bubble];
1.239     albertel 5356: 		    shift(@ans);
                   5357: 		}
                   5358: 	    }
1.82      albertel 5359: 	}
                   5360:     }
1.83      albertel 5361:     $record{'scantron.maxquest'}=$questnum;
                   5362:     return \%record;
1.82      albertel 5363: }
                   5364: 
1.423     albertel 5365: =pod
                   5366: 
                   5367: =item scantron_add_delay
                   5368: 
                   5369:    Adds an error message that occurred during the grading phase to a
                   5370:    queue of messages to be shown after grading pass is complete
                   5371: 
                   5372:  Arguments:
1.424     albertel 5373:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5374:    $scanline    - the scanline that caused the error
                   5375:    $errormesage - the error message
                   5376:    $errorcode   - a numeric code for the error
                   5377: 
                   5378:  Side Effects:
1.424     albertel 5379:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5380: 
                   5381: =cut
                   5382: 
1.82      albertel 5383: sub scantron_add_delay {
1.140     albertel 5384:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5385:     push(@$delayqueue,
                   5386: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5387: 	  'ecode' => $errorcode }
                   5388: 	 );
1.82      albertel 5389: }
                   5390: 
1.423     albertel 5391: =pod
                   5392: 
                   5393: =item scantron_find_student
                   5394: 
1.424     albertel 5395:    Finds the username for the current scanline
                   5396: 
                   5397:   Arguments:
                   5398:    $scantron_record - hash result from scantron_parse_scanline
                   5399:    $scan_data       - hash of correction information 
                   5400:                       (see &scantron_getfile() form more information)
                   5401:    $idmap           - hash from &username_to_idmap()
                   5402:    $line            - number of current scanline
                   5403:  
                   5404:   Returns:
                   5405:    Either 'username:domain' or undef if unknown
                   5406: 
1.423     albertel 5407: =cut
                   5408: 
1.82      albertel 5409: sub scantron_find_student {
1.157     albertel 5410:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5411:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5412:     if ($scanID =~ /^\s*$/) {
                   5413:  	return &scan_data($scan_data,"$line.user");
                   5414:     }
1.83      albertel 5415:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5416:  	if (lc($id) eq lc($scanID)) {
                   5417:  	    return $$idmap{$id};
                   5418:  	}
1.83      albertel 5419:     }
                   5420:     return undef;
                   5421: }
                   5422: 
1.423     albertel 5423: =pod
                   5424: 
                   5425: =item scantron_filter
                   5426: 
1.424     albertel 5427:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5428:    hidden resources was selected
                   5429: 
1.423     albertel 5430: =cut
                   5431: 
1.83      albertel 5432: sub scantron_filter {
                   5433:     my ($curres)=@_;
1.331     albertel 5434: 
                   5435:     if (ref($curres) && $curres->is_problem()) {
                   5436: 	# if the user has asked to not have either hidden
                   5437: 	# or 'randomout' controlled resources to be graded
                   5438: 	# don't include them
                   5439: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5440: 	    && $curres->randomout) {
                   5441: 	    return 0;
                   5442: 	}
1.83      albertel 5443: 	return 1;
                   5444:     }
                   5445:     return 0;
1.82      albertel 5446: }
                   5447: 
1.423     albertel 5448: =pod
                   5449: 
                   5450: =item scantron_process_corrections
                   5451: 
1.424     albertel 5452:    Gets correction information out of submitted form data and corrects
                   5453:    the scanline
                   5454: 
1.423     albertel 5455: =cut
                   5456: 
1.157     albertel 5457: sub scantron_process_corrections {
                   5458:     my ($r) = @_;
1.257     albertel 5459:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5460:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5461:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5462:     my $which=$env{'form.scantron_line'};
1.200     albertel 5463:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5464:     my ($skip,$err,$errmsg);
1.257     albertel 5465:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5466: 	$skip=1;
1.257     albertel 5467:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5468: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5469: 	    $env{'form.scantron_domain'};
1.157     albertel 5470: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5471: 	($line,$err,$errmsg)=
                   5472: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5473: 				     'ID',{'newid'=>$newid,
1.257     albertel 5474: 				    'username'=>$env{'form.scantron_username'},
                   5475: 				    'domain'=>$env{'form.scantron_domain'}});
                   5476:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5477: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5478: 	my $newCODE;
1.192     albertel 5479: 	my %args;
1.190     albertel 5480: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5481: 	    $newCODE='use_unfound';
1.190     albertel 5482: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5483: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5484: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5485: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5486: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5487: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5488: 	}
1.257     albertel 5489: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5490: 	    $args{'CODE_ignore_dup'}=1;
                   5491: 	}
                   5492: 	$args{'CODE'}=$newCODE;
1.186     albertel 5493: 	($line,$err,$errmsg)=
                   5494: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 5495: 				     'CODE',\%args);
1.257     albertel 5496:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   5497: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 5498: 	    ($line,$err,$errmsg)=
                   5499: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   5500: 					 $which,'answer',
                   5501: 					 { 'question'=>$question,
1.257     albertel 5502: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
1.157     albertel 5503: 	    if ($err) { last; }
                   5504: 	}
                   5505:     }
                   5506:     if ($err) {
1.398     albertel 5507: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 5508:     } else {
1.200     albertel 5509: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 5510: 	&scantron_putfile($scanlines,$scan_data);
                   5511:     }
                   5512: }
                   5513: 
1.423     albertel 5514: =pod
                   5515: 
                   5516: =item reset_skipping_status
                   5517: 
1.424     albertel 5518:    Forgets the current set of remember skipped scanlines (and thus
                   5519:    reverts back to considering all lines in the
                   5520:    scantron_skipped_<filename> file)
                   5521: 
1.423     albertel 5522: =cut
                   5523: 
1.200     albertel 5524: sub reset_skipping_status {
                   5525:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5526:     &scan_data($scan_data,'remember_skipping',undef,1);
                   5527:     &scantron_putfile(undef,$scan_data);
                   5528: }
                   5529: 
1.423     albertel 5530: =pod
                   5531: 
                   5532: =item start_skipping
                   5533: 
1.424     albertel 5534:    Marks a scanline to be skipped. 
                   5535: 
1.423     albertel 5536: =cut
                   5537: 
1.376     albertel 5538: sub start_skipping {
1.200     albertel 5539:     my ($scan_data,$i)=@_;
                   5540:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5541:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   5542: 	$remembered{$i}=2;
                   5543:     } else {
                   5544: 	$remembered{$i}=1;
                   5545:     }
1.200     albertel 5546:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   5547: }
                   5548: 
1.423     albertel 5549: =pod
                   5550: 
                   5551: =item should_be_skipped
                   5552: 
1.424     albertel 5553:    Checks whether a scanline should be skipped.
                   5554: 
1.423     albertel 5555: =cut
                   5556: 
1.200     albertel 5557: sub should_be_skipped {
1.376     albertel 5558:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 5559:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 5560: 	# not redoing old skips
1.376     albertel 5561: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 5562: 	return 0;
                   5563:     }
                   5564:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5565: 
                   5566:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   5567: 	return 0;
                   5568:     }
1.200     albertel 5569:     return 1;
                   5570: }
                   5571: 
1.423     albertel 5572: =pod
                   5573: 
                   5574: =item remember_current_skipped
                   5575: 
1.424     albertel 5576:    Discovers what scanlines are in the scantron_skipped_<filename>
                   5577:    file and remembers them into scan_data for later use.
                   5578: 
1.423     albertel 5579: =cut
                   5580: 
1.200     albertel 5581: sub remember_current_skipped {
                   5582:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5583:     my %to_remember;
                   5584:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5585: 	if ($scanlines->{'skipped'}[$i]) {
                   5586: 	    $to_remember{$i}=1;
                   5587: 	}
                   5588:     }
1.376     albertel 5589: 
1.200     albertel 5590:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   5591:     &scantron_putfile(undef,$scan_data);
                   5592: }
                   5593: 
1.423     albertel 5594: =pod
                   5595: 
                   5596: =item check_for_error
                   5597: 
1.424     albertel 5598:     Checks if there was an error when attempting to remove a specific
                   5599:     scantron_.. bubble sheet data file. Prints out an error if
                   5600:     something went wrong.
                   5601: 
1.423     albertel 5602: =cut
                   5603: 
1.200     albertel 5604: sub check_for_error {
                   5605:     my ($r,$result)=@_;
                   5606:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.401     albertel 5607: 	$r->print("An error occurred ($result) when trying to Remove the existing corrections.");
1.200     albertel 5608:     }
                   5609: }
1.157     albertel 5610: 
1.423     albertel 5611: =pod
                   5612: 
                   5613: =item scantron_warning_screen
                   5614: 
1.424     albertel 5615:    Interstitial screen to make sure the operator has selected the
                   5616:    correct options before we start the validation phase.
                   5617: 
1.423     albertel 5618: =cut
                   5619: 
1.203     albertel 5620: sub scantron_warning_screen {
                   5621:     my ($button_text)=@_;
1.257     albertel 5622:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 5623:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 5624:     my $CODElist;
1.284     albertel 5625:     if ($scantron_config{'CODElocation'} &&
                   5626: 	$scantron_config{'CODEstart'} &&
                   5627: 	$scantron_config{'CODElength'}) {
                   5628: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 5629: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 5630: 	$CODElist=
                   5631: 	    '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
1.373     albertel 5632: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 5633:     }
1.203     albertel 5634:     return (<<STUFF);
                   5635: <p>
1.398     albertel 5636: <span class="LC_warning">Please double check the information
                   5637:                  below before clicking on '$button_text'</span>
1.203     albertel 5638: </p>
                   5639: <table>
1.284     albertel 5640: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
1.257     albertel 5641: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
1.284     albertel 5642: $CODElist
1.203     albertel 5643: </table>
                   5644: <br />
                   5645: <p> If this information is correct, please click on '$button_text'.</p>
                   5646: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
                   5647: 
                   5648: <br />
                   5649: STUFF
                   5650: }
                   5651: 
1.423     albertel 5652: =pod
                   5653: 
                   5654: =item scantron_do_warning
                   5655: 
1.424     albertel 5656:    Check if the operator has picked something for all required
                   5657:    fields. Error out if something is missing.
                   5658: 
1.423     albertel 5659: =cut
                   5660: 
1.203     albertel 5661: sub scantron_do_warning {
                   5662:     my ($r)=@_;
1.324     albertel 5663:     my ($symb)=&get_symb($r);
1.203     albertel 5664:     if (!$symb) {return '';}
1.324     albertel 5665:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 5666:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 5667:     if ( $env{'form.selectpage'} eq '' ||
                   5668: 	 $env{'form.scantron_selectfile'} eq '' ||
                   5669: 	 $env{'form.scantron_format'} eq '' ) {
1.237     albertel 5670: 	$r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
1.257     albertel 5671: 	if ( $env{'form.selectpage'} eq '') {
1.398     albertel 5672: 	    $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
1.237     albertel 5673: 	} 
1.257     albertel 5674: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.398     albertel 5675: 	    $r->print('<p><span class="LC_error">You have not selected a file that contains the student\'s response data.</span></p>');
1.237     albertel 5676: 	} 
1.257     albertel 5677: 	if ( $env{'form.scantron_format'} eq '') {
1.398     albertel 5678: 	    $r->print('<p><span class="LC_error">You have not selected a the format of the student\'s response data.</span></p>');
1.237     albertel 5679: 	} 
                   5680:     } else {
1.265     www      5681: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.237     albertel 5682: 	$r->print(<<STUFF);
1.203     albertel 5683: $warning
1.265     www      5684: <input type="submit" name="submit" value="Grading: Validate Records" />
1.203     albertel 5685: <input type="hidden" name="command" value="scantron_validate" />
                   5686: STUFF
1.237     albertel 5687:     }
1.352     albertel 5688:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 5689:     return '';
                   5690: }
                   5691: 
1.423     albertel 5692: =pod
                   5693: 
                   5694: =item scantron_form_start
                   5695: 
1.424     albertel 5696:     html hidden input for remembering all selected grading options
                   5697: 
1.423     albertel 5698: =cut
                   5699: 
1.203     albertel 5700: sub scantron_form_start {
                   5701:     my ($max_bubble)=@_;
                   5702:     my $result= <<SCANTRONFORM;
                   5703: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 5704:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   5705:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   5706:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 5707:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 5708:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   5709:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   5710:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   5711:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 5712:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 5713: SCANTRONFORM
1.447   ! foxr     5714: 
        !          5715:   my $line = 0;
        !          5716:     while (defined($env{"form.scantron.bubblelines.$line"})) {
        !          5717:        my $chunk =
        !          5718: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
        !          5719:        $chunk +=
        !          5720: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line'." value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
        !          5721:        $result .= $chunk;
        !          5722:        $line++;
        !          5723:    }
1.203     albertel 5724:     return $result;
                   5725: }
                   5726: 
1.423     albertel 5727: =pod
                   5728: 
                   5729: =item scantron_validate_file
                   5730: 
1.424     albertel 5731:     Dispatch routine for doing validation of a bubble sheet data file.
                   5732: 
                   5733:     Also processes any necessary information resets that need to
                   5734:     occur before validation begins (ignore previous corrections,
                   5735:     restarting the skipped records processing)
                   5736: 
1.423     albertel 5737: =cut
                   5738: 
1.157     albertel 5739: sub scantron_validate_file {
                   5740:     my ($r) = @_;
1.324     albertel 5741:     my ($symb)=&get_symb($r);
1.157     albertel 5742:     if (!$symb) {return '';}
1.324     albertel 5743:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 5744:     
                   5745:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 5746:     # them when doing the corrections reset
1.257     albertel 5747:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 5748: 	&reset_skipping_status();
                   5749:     }
1.257     albertel 5750:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 5751: 	&remember_current_skipped();
1.257     albertel 5752: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 5753:     }
                   5754: 
1.257     albertel 5755:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 5756: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   5757: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   5758: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 5759: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 5760:     }
1.200     albertel 5761: 
1.257     albertel 5762:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 5763: 	&scantron_process_corrections($r);
                   5764:     }
1.424     albertel 5765:     $r->print("<p>Gathering necessary info.</p>");$r->rflush();
1.157     albertel 5766:     #get the student pick code ready
                   5767:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 5768:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 5769:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 5770:     $r->print($result);
                   5771:     
1.334     albertel 5772:     my @validate_phases=( 'sequence',
                   5773: 			  'ID',
1.157     albertel 5774: 			  'CODE',
                   5775: 			  'doublebubble',
                   5776: 			  'missingbubbles');
1.257     albertel 5777:     if (!$env{'form.validatepass'}) {
                   5778: 	$env{'form.validatepass'} = 0;
1.157     albertel 5779:     }
1.257     albertel 5780:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 5781: 
                   5782:     my $stop=0;
                   5783:     while (!$stop && $currentphase < scalar(@validate_phases)) {
                   5784: 	$r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
                   5785: 	$r->rflush();
                   5786: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   5787: 	{
                   5788: 	    no strict 'refs';
                   5789: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   5790: 	}
                   5791:     }
                   5792:     if (!$stop) {
1.203     albertel 5793: 	my $warning=&scantron_warning_screen('Start Grading');
                   5794: 	$r->print(<<STUFF);
                   5795: Validation process complete.<br />
                   5796: $warning
                   5797: <input type="submit" name="submit" value="Start Grading" />
                   5798: <input type="hidden" name="command" value="scantron_process" />
                   5799: STUFF
                   5800: 
1.157     albertel 5801:     } else {
                   5802: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   5803: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   5804:     }
                   5805:     if ($stop) {
1.334     albertel 5806: 	if ($validate_phases[$currentphase] eq 'sequence') {
                   5807: 	    $r->print('<input type="submit" name="submit" value="Ignore -> " />');
                   5808: 	    $r->print(' this error <br />');
                   5809: 
                   5810: 	    $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
                   5811: 	} else {
                   5812: 	    $r->print('<input type="submit" name="submit" value="Continue ->" />');
                   5813: 	    $r->print(' using corrected info <br />');
                   5814: 	    $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
                   5815: 	    $r->print(" this scanline saving it for later.");
                   5816: 	}
1.157     albertel 5817:     }
1.352     albertel 5818:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 5819:     return '';
                   5820: }
                   5821: 
1.423     albertel 5822: 
                   5823: =pod
                   5824: 
                   5825: =item scantron_remove_file
                   5826: 
1.424     albertel 5827:    Removes the requested bubble sheet data file, makes sure that
                   5828:    scantron_original_<filename> is never removed
                   5829: 
                   5830: 
1.423     albertel 5831: =cut
                   5832: 
1.200     albertel 5833: sub scantron_remove_file {
1.192     albertel 5834:     my ($which)=@_;
1.257     albertel 5835:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5836:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5837:     my $file='scantron_';
1.200     albertel 5838:     if ($which eq 'corrected' || $which eq 'skipped') {
                   5839: 	$file.=$which.'_';
1.192     albertel 5840:     } else {
                   5841: 	return 'refused';
                   5842:     }
1.257     albertel 5843:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 5844:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   5845: }
                   5846: 
1.423     albertel 5847: 
                   5848: =pod
                   5849: 
                   5850: =item scantron_remove_scan_data
                   5851: 
1.424     albertel 5852:    Removes all scan_data correction for the requested bubble sheet
                   5853:    data file.  (In the case that both the are doing skipped records we need
                   5854:    to remember the old skipped lines for the time being so that element
                   5855:    persists for a while.)
                   5856: 
1.423     albertel 5857: =cut
                   5858: 
1.200     albertel 5859: sub scantron_remove_scan_data {
1.257     albertel 5860:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5861:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5862:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   5863:     my @todelete;
1.257     albertel 5864:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 5865:     foreach my $key (@keys) {
                   5866: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 5867: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 5868: 		$key=~/remember_skipping/) {
                   5869: 		next;
                   5870: 	    }
1.192     albertel 5871: 	    push(@todelete,$key);
                   5872: 	}
                   5873:     }
1.200     albertel 5874:     my $result;
1.192     albertel 5875:     if (@todelete) {
1.200     albertel 5876: 	$result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
1.192     albertel 5877:     }
                   5878:     return $result;
                   5879: }
                   5880: 
1.423     albertel 5881: 
                   5882: =pod
                   5883: 
                   5884: =item scantron_getfile
                   5885: 
1.424     albertel 5886:     Fetches the requested bubble sheet data file (all 3 versions), and
                   5887:     the scan_data hash
                   5888:   
                   5889:   Arguments:
                   5890:     None
                   5891: 
                   5892:   Returns:
                   5893:     2 hash references
                   5894: 
                   5895:      - first one has 
                   5896:          orig      -
                   5897:          corrected -
                   5898:          skipped   -  each of which points to an array ref of the specified
                   5899:                       file broken up into individual lines
                   5900:          count     - number of scanlines
                   5901:  
                   5902:      - second is the scan_data hash possible keys are
1.425     albertel 5903:        ($number refers to scanline numbered $number and thus the key affects
                   5904:         only that scanline
                   5905:         $bubline refers to the specific bubble line element and the aspects
                   5906:         refers to that specific bubble line element)
                   5907: 
                   5908:        $number.user - username:domain to use
                   5909:        $number.CODE_ignore_dup 
                   5910:                     - ignore the duplicate CODE error 
                   5911:        $number.useCODE
                   5912:                     - use the CODE in the scanline as is
                   5913:        $number.no_bubble.$bubline
                   5914:                     - it is valid that there is no bubbled in bubble
                   5915:                       at $number $bubline
                   5916:        remember_skipping
                   5917:                     - a frozen hash containing keys of $number and values
                   5918:                       of either 
                   5919:                         1 - we are on a 'do skipped records pass' and plan
                   5920:                             on processing this line
                   5921:                         2 - we are on a 'do skipped records pass' and this
                   5922:                             scanline has been marked to skip yet again
1.424     albertel 5923: 
1.423     albertel 5924: =cut
                   5925: 
1.157     albertel 5926: sub scantron_getfile {
1.200     albertel 5927:     #FIXME really would prefer a scantron directory
1.257     albertel 5928:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5929:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 5930:     my $lines;
                   5931:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5932: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 5933:     my %scanlines;
                   5934:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   5935:     my $temp=$scanlines{'orig'};
                   5936:     $scanlines{'count'}=$#$temp;
                   5937: 
                   5938:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5939: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 5940:     if ($lines eq '-1') {
                   5941: 	$scanlines{'corrected'}=[];
                   5942:     } else {
                   5943: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   5944:     }
                   5945:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5946: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 5947:     if ($lines eq '-1') {
                   5948: 	$scanlines{'skipped'}=[];
                   5949:     } else {
                   5950: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   5951:     }
1.175     albertel 5952:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 5953:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   5954:     my %scan_data = @tmp;
                   5955:     return (\%scanlines,\%scan_data);
                   5956: }
                   5957: 
1.423     albertel 5958: =pod
                   5959: 
                   5960: =item lonnet_putfile
                   5961: 
1.424     albertel 5962:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   5963: 
                   5964:  Arguments:
                   5965:    $contents - data to store
                   5966:    $filename - filename to store $contents into
                   5967: 
                   5968:  Returns:
                   5969:    result value from &Apache::lonnet::finishuserfileupload
                   5970: 
1.423     albertel 5971: =cut
                   5972: 
1.157     albertel 5973: sub lonnet_putfile {
                   5974:     my ($contents,$filename)=@_;
1.257     albertel 5975:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5976:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5977:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 5978:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 5979: 
                   5980: }
                   5981: 
1.423     albertel 5982: =pod
                   5983: 
                   5984: =item scantron_putfile
                   5985: 
1.424     albertel 5986:     Stores the current version of the bubble sheet data files, and the
                   5987:     scan_data hash. (Does not modify the original version only the
                   5988:     corrected and skipped versions.
                   5989: 
                   5990:  Arguments:
                   5991:     $scanlines - hash ref that looks like the first return value from
                   5992:                  &scantron_getfile()
                   5993:     $scan_data - hash ref that looks like the second return value from
                   5994:                  &scantron_getfile()
                   5995: 
1.423     albertel 5996: =cut
                   5997: 
1.157     albertel 5998: sub scantron_putfile {
                   5999:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6000:     #FIXME really would prefer a scantron directory
1.257     albertel 6001:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6002:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6003:     if ($scanlines) {
                   6004: 	my $prefix='scantron_';
1.157     albertel 6005: # no need to update orig, shouldn't change
                   6006: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6007: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6008: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6009: 			$prefix.'corrected_'.
1.257     albertel 6010: 			$env{'form.scantron_selectfile'});
1.200     albertel 6011: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6012: 			$prefix.'skipped_'.
1.257     albertel 6013: 			$env{'form.scantron_selectfile'});
1.200     albertel 6014:     }
1.175     albertel 6015:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6016: }
                   6017: 
1.423     albertel 6018: =pod
                   6019: 
                   6020: =item scantron_get_line
                   6021: 
1.424     albertel 6022:    Returns the correct version of the scanline
                   6023: 
                   6024:  Arguments:
                   6025:     $scanlines - hash ref that looks like the first return value from
                   6026:                  &scantron_getfile()
                   6027:     $scan_data - hash ref that looks like the second return value from
                   6028:                  &scantron_getfile()
                   6029:     $i         - number of the requested line (starts at 0)
                   6030: 
                   6031:  Returns:
                   6032:    A scanline, (either the original or the corrected one if it
                   6033:    exists), or undef if the requested scanline should be
                   6034:    skipped. (Either because it's an skipped scanline, or it's an
                   6035:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6036:    pass.
                   6037: 
1.423     albertel 6038: =cut
                   6039: 
1.157     albertel 6040: sub scantron_get_line {
1.200     albertel 6041:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6042:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6043:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6044:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6045:     return $scanlines->{'orig'}[$i]; 
                   6046: }
                   6047: 
1.423     albertel 6048: =pod
                   6049: 
                   6050: =item scantron_todo_count
                   6051: 
1.424     albertel 6052:     Counts the number of scanlines that need processing.
                   6053: 
                   6054:  Arguments:
                   6055:     $scanlines - hash ref that looks like the first return value from
                   6056:                  &scantron_getfile()
                   6057:     $scan_data - hash ref that looks like the second return value from
                   6058:                  &scantron_getfile()
                   6059: 
                   6060:  Returns:
                   6061:     $count - number of scanlines to process
                   6062: 
1.423     albertel 6063: =cut
                   6064: 
1.200     albertel 6065: sub get_todo_count {
                   6066:     my ($scanlines,$scan_data)=@_;
                   6067:     my $count=0;
                   6068:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6069: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6070: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6071: 	$count++;
                   6072:     }
                   6073:     return $count;
                   6074: }
                   6075: 
1.423     albertel 6076: =pod
                   6077: 
                   6078: =item scantron_put_line
                   6079: 
1.424     albertel 6080:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6081:     data file.
                   6082: 
                   6083:  Arguments:
                   6084:     $scanlines - hash ref that looks like the first return value from
                   6085:                  &scantron_getfile()
                   6086:     $scan_data - hash ref that looks like the second return value from
                   6087:                  &scantron_getfile()
                   6088:     $i         - line number to update
                   6089:     $newline   - contents of the updated scanline
                   6090:     $skip      - if true make the line for skipping and update the
                   6091:                  'skipped' file
                   6092: 
1.423     albertel 6093: =cut
                   6094: 
1.157     albertel 6095: sub scantron_put_line {
1.200     albertel 6096:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6097:     if ($skip) {
                   6098: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6099: 	&start_skipping($scan_data,$i);
1.157     albertel 6100: 	return;
                   6101:     }
                   6102:     $scanlines->{'corrected'}[$i]=$newline;
                   6103: }
                   6104: 
1.423     albertel 6105: =pod
                   6106: 
                   6107: =item scantron_clear_skip
                   6108: 
1.424     albertel 6109:    Remove a line from the 'skipped' file
                   6110: 
                   6111:  Arguments:
                   6112:     $scanlines - hash ref that looks like the first return value from
                   6113:                  &scantron_getfile()
                   6114:     $scan_data - hash ref that looks like the second return value from
                   6115:                  &scantron_getfile()
                   6116:     $i         - line number to update
                   6117: 
1.423     albertel 6118: =cut
                   6119: 
1.376     albertel 6120: sub scantron_clear_skip {
                   6121:     my ($scanlines,$scan_data,$i)=@_;
                   6122:     if (exists($scanlines->{'skipped'}[$i])) {
                   6123: 	undef($scanlines->{'skipped'}[$i]);
                   6124: 	return 1;
                   6125:     }
                   6126:     return 0;
                   6127: }
                   6128: 
1.423     albertel 6129: =pod
                   6130: 
                   6131: =item scantron_filter_not_exam
                   6132: 
1.424     albertel 6133:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6134:    filter out resources that are not marked as 'exam' mode
                   6135: 
1.423     albertel 6136: =cut
                   6137: 
1.334     albertel 6138: sub scantron_filter_not_exam {
                   6139:     my ($curres)=@_;
                   6140:     
                   6141:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6142: 	# if the user has asked to not have either hidden
                   6143: 	# or 'randomout' controlled resources to be graded
                   6144: 	# don't include them
                   6145: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6146: 	    && $curres->randomout) {
                   6147: 	    return 0;
                   6148: 	}
                   6149: 	return 1;
                   6150:     }
                   6151:     return 0;
                   6152: }
                   6153: 
1.423     albertel 6154: =pod
                   6155: 
                   6156: =item scantron_validate_sequence
                   6157: 
1.424     albertel 6158:     Validates the selected sequence, checking for resource that are
                   6159:     not set to exam mode.
                   6160: 
1.423     albertel 6161: =cut
                   6162: 
1.334     albertel 6163: sub scantron_validate_sequence {
                   6164:     my ($r,$currentphase) = @_;
                   6165: 
                   6166:     my $navmap=Apache::lonnavmaps::navmap->new();
                   6167:     my (undef,undef,$sequence)=
                   6168: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6169: 
                   6170:     my $map=$navmap->getResourceByUrl($sequence);
                   6171: 
                   6172:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6173:                                     value="ignore" />');
                   6174:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6175: 	my @resources=
                   6176: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6177: 	if (@resources) {
1.357     banghart 6178: 	    $r->print("<p>".&mt('Some resources in the sequence currently are not set to exam mode. Grading these resources currently may not work correctly.')."</p>");
1.334     albertel 6179: 	    return (1,$currentphase);
                   6180: 	}
                   6181:     }
                   6182: 
                   6183:     return (0,$currentphase+1);
                   6184: }
                   6185: 
1.423     albertel 6186: =pod
                   6187: 
                   6188: =item scantron_validate_ID
                   6189: 
1.424     albertel 6190:    Validates all scanlines in the selected file to not have any
                   6191:    invalid or underspecified student IDs
                   6192: 
1.423     albertel 6193: =cut
                   6194: 
1.157     albertel 6195: sub scantron_validate_ID {
                   6196:     my ($r,$currentphase) = @_;
                   6197:     
                   6198:     #get student info
                   6199:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6200:     my %idmap=&username_to_idmap($classlist);
                   6201: 
                   6202:     #get scantron line setup
1.257     albertel 6203:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6204:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447   ! foxr     6205:     
        !          6206:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
1.157     albertel 6207: 
                   6208:     my %found=('ids'=>{},'usernames'=>{});
                   6209:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6210: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6211: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6212: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6213: 						 $scan_data);
                   6214: 	my $id=$$scan_record{'scantron.ID'};
                   6215: 	my $found;
                   6216: 	foreach my $checkid (keys(%idmap)) {
                   6217: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6218: 	}
                   6219: 	if ($found) {
                   6220: 	    my $username=$idmap{$found};
                   6221: 	    if ($found{'ids'}{$found}) {
                   6222: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6223: 					 $line,'duplicateID',$found);
1.194     albertel 6224: 		return(1,$currentphase);
1.157     albertel 6225: 	    } elsif ($found{'usernames'}{$username}) {
                   6226: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6227: 					 $line,'duplicateID',$username);
1.194     albertel 6228: 		return(1,$currentphase);
1.157     albertel 6229: 	    }
1.186     albertel 6230: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6231: 	    $found{'ids'}{$found}++;
                   6232: 	    $found{'usernames'}{$username}++;
                   6233: 	} else {
                   6234: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6235: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6236: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6237: 		    &scantron_get_correction($r,$i,$scan_record,
                   6238: 					     \%scantron_config,
                   6239: 					     $line,'duplicateID',$username);
1.194     albertel 6240: 		    return(1,$currentphase);
1.157     albertel 6241: 		} elsif (!defined($username)) {
                   6242: 		    &scantron_get_correction($r,$i,$scan_record,
                   6243: 					     \%scantron_config,
                   6244: 					     $line,'incorrectID');
1.194     albertel 6245: 		    return(1,$currentphase);
1.157     albertel 6246: 		}
                   6247: 		$found{'usernames'}{$username}++;
                   6248: 	    } else {
                   6249: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6250: 					 $line,'incorrectID');
1.194     albertel 6251: 		return(1,$currentphase);
1.157     albertel 6252: 	    }
                   6253: 	}
                   6254:     }
                   6255: 
                   6256:     return (0,$currentphase+1);
                   6257: }
                   6258: 
1.423     albertel 6259: =pod
                   6260: 
                   6261: =item scantron_get_correction
                   6262: 
1.424     albertel 6263:    Builds the interface screen to interact with the operator to fix a
                   6264:    specific error condition in a specific scanline
                   6265: 
                   6266:  Arguments:
                   6267:     $r           - Apache request object
                   6268:     $i           - number of the current scanline
                   6269:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   6270:     $scan_config - hash ref as returned from &get_scantron_config()
                   6271:     $line        - full contents of the current scanline
                   6272:     $error       - error condition, valid values are
                   6273:                    'incorrectCODE', 'duplicateCODE',
                   6274:                    'doublebubble', 'missingbubble',
                   6275:                    'duplicateID', 'incorrectID'
                   6276:     $arg         - extra information needed
                   6277:        For errors:
                   6278:          - duplicateID   - paper number that this studentID was seen before on
                   6279:          - duplicateCODE - array ref of the paper numbers this CODE was
                   6280:                            seen on before
                   6281:          - incorrectCODE - current incorrect CODE 
                   6282:          - doublebubble  - array ref of the bubble lines that have double
                   6283:                            bubble errors
                   6284:          - missingbubble - array ref of the bubble lines that have missing
                   6285:                            bubble errors
                   6286: 
1.423     albertel 6287: =cut
                   6288: 
1.157     albertel 6289: sub scantron_get_correction {
                   6290:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
                   6291: 
                   6292: #FIXME in the case of a duplicated ID the previous line, probaly need
                   6293: #to show both the current line and the previous one and allow skipping
                   6294: #the previous one or the current one
                   6295: 
1.161     albertel 6296:     $r->print("<p><b>An error was detected ($error)</b>");
1.333     albertel 6297:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.157     albertel 6298: 	$r->print(" for PaperID <tt>".
                   6299: 		  $$scan_record{'scantron.PaperID'}."</tt> \n");
                   6300:     } else {
                   6301: 	$r->print(" in scanline $i <pre>".
                   6302: 		  $line."</pre> \n");
                   6303:     }
1.242     albertel 6304:     my $message="<p>The ID on the form is  <tt>".
                   6305: 	$$scan_record{'scantron.ID'}."</tt><br />\n".
                   6306: 	"The name on the paper is ".
                   6307: 	$$scan_record{'scantron.LastName'}.",".
                   6308: 	$$scan_record{'scantron.FirstName'}."</p>";
                   6309: 
1.157     albertel 6310:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6311:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
                   6312:     if ($error =~ /ID$/) {
1.186     albertel 6313: 	if ($error eq 'incorrectID') {
1.157     albertel 6314: 	    $r->print("The encoded ID is not in the classlist</p>\n");
                   6315: 	} elsif ($error eq 'duplicateID') {
                   6316: 	    $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
                   6317: 	}
1.242     albertel 6318: 	$r->print($message);
1.157     albertel 6319: 	$r->print("<p>How should I handle this? <br /> \n");
                   6320: 	$r->print("\n<ul><li> ");
                   6321: 	#FIXME it would be nice if this sent back the user ID and
                   6322: 	#could do partial userID matches
                   6323: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6324: 				       'scantron_username','scantron_domain'));
                   6325: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6326: 	$r->print("\n@".
1.257     albertel 6327: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6328: 
                   6329: 	$r->print('</li>');
1.186     albertel 6330:     } elsif ($error =~ /CODE$/) {
                   6331: 	if ($error eq 'incorrectCODE') {
1.187     albertel 6332: 	    $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
1.186     albertel 6333: 	} elsif ($error eq 'duplicateCODE') {
1.194     albertel 6334: 	    $r->print("</p><p>The encoded CODE has also been used by a previous paper ".join(', ',@{$arg}).", and CODEs are supposed to be unique</p>\n");
1.186     albertel 6335: 	}
1.224     albertel 6336: 	$r->print("<p>The CODE on the form is  <tt>'".
                   6337: 		  $$scan_record{'scantron.CODE'}."'</tt><br />\n");
1.242     albertel 6338: 	$r->print($message);
1.186     albertel 6339: 	$r->print("<p>How should I handle this? <br /> \n");
1.187     albertel 6340: 	$r->print("\n<br /> ");
1.194     albertel 6341: 	my $i=0;
1.273     albertel 6342: 	if ($error eq 'incorrectCODE' 
                   6343: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6344: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6345: 	    if ($closest > 0) {
                   6346: 		foreach my $testcode (@{$closest}) {
                   6347: 		    my $checked='';
1.401     albertel 6348: 		    if (!$i) { $checked=' checked="checked" '; }
1.278     albertel 6349: 		    $r->print("<label><input type='radio' name='scantron_CODE_resolution' value='use_closest_$i' $checked /> Use the similar CODE <b><tt>".$testcode."</tt></b> instead.</label><input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
                   6350: 		    $r->print("\n<br />");
                   6351: 		    $i++;
                   6352: 		}
1.194     albertel 6353: 	    }
                   6354: 	}
1.273     albertel 6355: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.401     albertel 6356: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
1.273     albertel 6357: 	    $r->print("<label><input type='radio' name='scantron_CODE_resolution' value='use_unfound' $checked /> Use the CODE <b><tt>".$$scan_record{'scantron.CODE'}."</tt></b> that is was on the paper, ignoring the error.</label>");
                   6358: 	    $r->print("\n<br />");
                   6359: 	}
1.194     albertel 6360: 
1.188     albertel 6361: 	$r->print(<<ENDSCRIPT);
                   6362: <script type="text/javascript">
                   6363: function change_radio(field) {
1.190     albertel 6364:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6365:     var i;
                   6366:     for (i=0;i<slct.length;i++) {
                   6367:         if (slct[i].value==field) { slct[i].checked=true; }
                   6368:     }
                   6369: }
                   6370: </script>
                   6371: ENDSCRIPT
1.187     albertel 6372: 	my $href="/adm/pickcode?".
1.359     www      6373: 	   "form=".&escape("scantronupload").
                   6374: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6375: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6376: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6377: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6378: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
                   6379: 	    $r->print("<label><input type='radio' name='scantron_CODE_resolution' value='use_found' /> <a target='_blank' href='$href'>Select</a> a CODE from the list of all CODEs and use it.</label> Selected CODE is <input readonly='true' type='text' size='8' name='scantron_CODE_selectedvalue' onfocus=\"javascript:change_radio('use_found')\" onchange=\"javascript:change_radio('use_found')\" />");
                   6380: 	    $r->print("\n<br />");
                   6381: 	}
1.272     albertel 6382: 	$r->print("<label><input type='radio' name='scantron_CODE_resolution' value='use_typed' /> Use </label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" /> as the CODE.");
1.187     albertel 6383: 	$r->print("\n<br /><br />");
1.157     albertel 6384:     } elsif ($error eq 'doublebubble') {
                   6385: 	$r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
                   6386: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6387: 		  join(',',@{$arg}).'" />');
1.242     albertel 6388: 	$r->print($message);
1.157     albertel 6389: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6390: 	foreach my $question (@{$arg}) {
1.447   ! foxr     6391: 
        !          6392: 	    my $selected  = &get_response_bubbles($scan_record, $question);
1.422     foxr     6393: 	    &scantron_bubble_selector($r,$scan_config,$question,
                   6394: 				      split('',$selected));
1.157     albertel 6395: 	}
                   6396:     } elsif ($error eq 'missingbubble') {
                   6397: 	$r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
1.242     albertel 6398: 	$r->print($message);
1.157     albertel 6399: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6400: 	$r->print("Some questions have no scanned bubbles\n");
                   6401: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6402: 		  join(',',@{$arg}).'" />');
                   6403: 	foreach my $question (@{$arg}) {
1.447   ! foxr     6404: 	    my $selected = &get_response_bubbles($scan_record, $quesion);
1.157     albertel 6405: 	    &scantron_bubble_selector($r,$scan_config,$question);
                   6406: 	}
                   6407:     } else {
                   6408: 	$r->print("\n<ul>");
                   6409:     }
                   6410:     $r->print("\n</li></ul>");
                   6411: 
                   6412: }
1.423     albertel 6413: 
                   6414: =pod
                   6415: 
                   6416: =item scantron_bubble_selector
                   6417:   
                   6418:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 6419:    possibly showing the existing the selected bubbles if known
1.423     albertel 6420: 
                   6421:  Arguments:
                   6422:     $r           - Apache request object
                   6423:     $scan_config - hash from &get_scantron_config()
                   6424:     $quest       - number of the bubble line to make a corrector for
                   6425:     $selected    - array of letters of previously selected bubbles
                   6426: 
                   6427: =cut
                   6428: 
1.157     albertel 6429: sub scantron_bubble_selector {
1.447   ! foxr     6430:     my ($r,$scan_config,$quest,@selected)=@_;
1.157     albertel 6431:     my $max=$$scan_config{'Qlength'};
1.274     albertel 6432: 
                   6433:     my $scmode=$$scan_config{'Qon'};
1.447   ! foxr     6434: 
        !          6435: 
1.274     albertel 6436:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   6437: 
1.422     foxr     6438: 
1.447   ! foxr     6439:     my $lines = $bubble_lines_per_response{$quest};
        !          6440: 
1.422     foxr     6441:     my $total_lines = $lines*2;
1.157     albertel 6442:     my @alphabet=('A'..'Z');
1.422     foxr     6443:     $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
                   6444: 
                   6445:     for (my $l = 0; $l < $lines; $l++) {
                   6446: 	if ($l != 0) {
                   6447: 	    $r->print('<tr>');
                   6448: 	}
                   6449: 
                   6450: 	# FIXME:  This loop probably has to be considerably more clever for
                   6451: 	#  multiline bubbles: User can multibubble by having bubbles in
                   6452: 	#  several lines.  User can skip lines legitimately etc. etc.
                   6453: 
                   6454: 	for (my $i=0;$i<$max;$i++) {
                   6455: 	    $r->print("\n".'<td align="center">');
                   6456: 	    if ($selected[0] eq $alphabet[$i]) { 
                   6457: 		$r->print('X'); 
                   6458: 		shift(@selected) ;
                   6459: 	    } else { 
                   6460: 		$r->print('&nbsp;'); 
                   6461: 	    }
                   6462: 	    $r->print('</td>');
                   6463: 	    
                   6464: 	}
                   6465: 
                   6466: 	if ($l == 0) {
                   6467: 	    my $lspan = $total_lines * 2;   #  2 table rows per bubble line.
                   6468: 
                   6469: 	    $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
                   6470: 	      $quest.'" value="none" /> No bubble </label></td>');
                   6471: 	
                   6472: 	}
                   6473: 
                   6474: 	$r->print('</tr><tr>');
                   6475: 
                   6476: 	# FIXME: This may have to be a bit more clever for
                   6477: 	#        multiline questions (different values e.g..).
                   6478: 
                   6479: 	for (my $i=0;$i<$max;$i++) {
                   6480: 	    $r->print("\n".
                   6481: 		      '<td><label><input type="radio" name="scantron_correct_Q_'.
                   6482: 		      $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   6483: 	}
                   6484: 	$r->print('</tr>');
                   6485: 
                   6486: 	    
1.157     albertel 6487:     }
1.422     foxr     6488:     $r->print('</table>');
1.157     albertel 6489: }
                   6490: 
1.423     albertel 6491: =pod
                   6492: 
                   6493: =item num_matches
                   6494: 
1.424     albertel 6495:    Counts the number of characters that are the same between the two arguments.
                   6496: 
                   6497:  Arguments:
                   6498:    $orig - CODE from the scanline
                   6499:    $code - CODE to match against
                   6500: 
                   6501:  Returns:
                   6502:    $count - integer count of the number of same characters between the
                   6503:             two arguments
                   6504: 
1.423     albertel 6505: =cut
                   6506: 
1.194     albertel 6507: sub num_matches {
                   6508:     my ($orig,$code) = @_;
                   6509:     my @code=split(//,$code);
                   6510:     my @orig=split(//,$orig);
                   6511:     my $same=0;
                   6512:     for (my $i=0;$i<scalar(@code);$i++) {
                   6513: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   6514:     }
                   6515:     return $same;
                   6516: }
                   6517: 
1.423     albertel 6518: =pod
                   6519: 
                   6520: =item scantron_get_closely_matching_CODEs
                   6521: 
1.424     albertel 6522:    Cycles through all CODEs and finds the set that has the greatest
                   6523:    number of same characters as the provided CODE
                   6524: 
                   6525:  Arguments:
                   6526:    $allcodes - hash ref returned by &get_codes()
                   6527:    $CODE     - CODE from the current scanline
                   6528: 
                   6529:  Returns:
                   6530:    2 element list
                   6531:     - first elements is number of how closely matching the best fit is 
                   6532:       (5 means best set has 5 matching characters)
                   6533:     - second element is an arrary ref containing the set of valid CODEs
                   6534:       that best fit the passed in CODE
                   6535: 
1.423     albertel 6536: =cut
                   6537: 
1.194     albertel 6538: sub scantron_get_closely_matching_CODEs {
                   6539:     my ($allcodes,$CODE)=@_;
                   6540:     my @CODEs;
                   6541:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   6542: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   6543:     }
                   6544: 
                   6545:     return ($#CODEs,$CODEs[-1]);
                   6546: }
                   6547: 
1.423     albertel 6548: =pod
                   6549: 
                   6550: =item get_codes
                   6551: 
1.424     albertel 6552:    Builds a hash which has keys of all of the valid CODEs from the selected
                   6553:    set of remembered CODEs.
                   6554: 
                   6555:  Arguments:
                   6556:   $old_name - name of the set of remembered CODEs
                   6557:   $cdom     - domain of the course
                   6558:   $cnum     - internal course name
                   6559: 
                   6560:  Returns:
                   6561:   %allcodes - keys are the valid CODEs, values are all 1
                   6562: 
1.423     albertel 6563: =cut
                   6564: 
1.194     albertel 6565: sub get_codes {
1.280     foxr     6566:     my ($old_name, $cdom, $cnum) = @_;
                   6567:     if (!$old_name) {
                   6568: 	$old_name=$env{'form.scantron_CODElist'};
                   6569:     }
                   6570:     if (!$cdom) {
                   6571: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6572:     }
                   6573:     if (!$cnum) {
                   6574: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   6575:     }
1.278     albertel 6576:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   6577: 				    $cdom,$cnum);
                   6578:     my %allcodes;
                   6579:     if ($result{"type\0$old_name"} eq 'number') {
                   6580: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   6581:     } else {
                   6582: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   6583:     }
1.194     albertel 6584:     return %allcodes;
                   6585: }
                   6586: 
1.423     albertel 6587: =pod
                   6588: 
                   6589: =item scantron_validate_CODE
                   6590: 
1.424     albertel 6591:    Validates all scanlines in the selected file to not have any
                   6592:    invalid or underspecified CODEs and that none of the codes are
                   6593:    duplicated if this was requested.
                   6594: 
1.423     albertel 6595: =cut
                   6596: 
1.157     albertel 6597: sub scantron_validate_CODE {
                   6598:     my ($r,$currentphase) = @_;
1.257     albertel 6599:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 6600:     if ($scantron_config{'CODElocation'} &&
                   6601: 	$scantron_config{'CODEstart'} &&
                   6602: 	$scantron_config{'CODElength'}) {
1.257     albertel 6603: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 6604: 	    &FIXME_blow_up()
                   6605: 	}
                   6606:     } else {
                   6607: 	return (0,$currentphase+1);
                   6608:     }
                   6609:     
                   6610:     my %usedCODEs;
                   6611: 
1.194     albertel 6612:     my %allcodes=&get_codes();
1.186     albertel 6613: 
1.447   ! foxr     6614:     &scantron_get_maxbubble();	# parse needs the lines per response array.
        !          6615: 
1.186     albertel 6616:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6617:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6618: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 6619: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6620: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6621: 						 $scan_data);
                   6622: 	my $CODE=$$scan_record{'scantron.CODE'};
                   6623: 	my $error=0;
1.224     albertel 6624: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   6625: 	    &scantron_get_correction($r,$i,$scan_record,
                   6626: 				     \%scantron_config,
                   6627: 				     $line,'incorrectCODE',\%allcodes);
                   6628: 	    return(1,$currentphase);
                   6629: 	}
1.221     albertel 6630: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   6631: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 6632: 	    &scantron_get_correction($r,$i,$scan_record,
                   6633: 				     \%scantron_config,
1.194     albertel 6634: 				     $line,'incorrectCODE',\%allcodes);
                   6635: 	    return(1,$currentphase);
1.186     albertel 6636: 	}
1.214     albertel 6637: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 6638: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 6639: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 6640: 	    &scantron_get_correction($r,$i,$scan_record,
                   6641: 				     \%scantron_config,
1.194     albertel 6642: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   6643: 	    return(1,$currentphase);
1.186     albertel 6644: 	}
1.194     albertel 6645: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 6646:     }
1.157     albertel 6647:     return (0,$currentphase+1);
                   6648: }
                   6649: 
1.423     albertel 6650: =pod
                   6651: 
                   6652: =item scantron_validate_doublebubble
                   6653: 
1.424     albertel 6654:    Validates all scanlines in the selected file to not have any
                   6655:    bubble lines with multiple bubbles marked.
                   6656: 
1.423     albertel 6657: =cut
                   6658: 
1.157     albertel 6659: sub scantron_validate_doublebubble {
                   6660:     my ($r,$currentphase) = @_;
                   6661:     #get student info
                   6662:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6663:     my %idmap=&username_to_idmap($classlist);
                   6664: 
                   6665:     #get scantron line setup
1.257     albertel 6666:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6667:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447   ! foxr     6668: 
        !          6669:     &scantron_get_maxbubble();	# parse needs the bubble line array.
        !          6670: 
1.157     albertel 6671:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6672: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6673: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6674: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6675: 						 $scan_data);
                   6676: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   6677: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   6678: 				 'doublebubble',
                   6679: 				 $$scan_record{'scantron.doubleerror'});
                   6680:     	return (1,$currentphase);
                   6681:     }
                   6682:     return (0,$currentphase+1);
                   6683: }
                   6684: 
1.423     albertel 6685: =pod
                   6686: 
                   6687: =item scantron_get_maxbubble
                   6688: 
1.424     albertel 6689:    Returns the maximum number of bubble lines that are expected to
                   6690:    occur. Does this by walking the selected sequence rendering the
                   6691:    resource and then checking &Apache::lonxml::get_problem_counter()
                   6692:    for what the current value of the problem counter is.
                   6693: 
1.447   ! foxr     6694:    Caches the results to $env{'form.scantron_maxbubble'},
        !          6695:    $env{'form.scantron.bubble_lines.n'} and 
        !          6696:    $env{'form.scantron.first_bubble_line.n'}
        !          6697:    which are the total number of bubble, lines, the number of bubble
        !          6698:    lines for reponse n and number of the first bubble line for response n.
1.424     albertel 6699: 
1.423     albertel 6700: =cut
                   6701: 
1.330     albertel 6702: sub scantron_get_maxbubble {    
1.435     foxr     6703: 
1.257     albertel 6704:     if (defined($env{'form.scantron_maxbubble'}) &&
                   6705: 	$env{'form.scantron_maxbubble'}) {
1.447   ! foxr     6706: 	&restore_bubble_lines();
1.257     albertel 6707: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 6708:     }
1.330     albertel 6709: 
1.447   ! foxr     6710:     my (undef, undef, $sequence) =
1.257     albertel 6711: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 6712: 
1.447   ! foxr     6713:     my $navmap=Apache::lonnavmaps::navmap->new();
1.191     albertel 6714:     my $map=$navmap->getResourceByUrl($sequence);
                   6715:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 6716: 
                   6717:     &Apache::lonxml::clear_problem_counter();
                   6718: 
1.435     foxr     6719:     my $uname       = $env{'form.student'};
                   6720:     my $udom        = $env{'form.userdom'};
                   6721:     my $cid         = $env{'request.course.id'};
                   6722:     my $total_lines = 0;
                   6723:     %bubble_lines_per_response = ();
1.447   ! foxr     6724:     %first_bubble_line         = ();
1.435     foxr     6725: 
1.447   ! foxr     6726:   
        !          6727:     my $response_number = 0;
        !          6728:     my $bubble_line     = 0;
1.191     albertel 6729:     foreach my $resource (@resources) {
1.435     foxr     6730: 	my $symb = $resource->symb();
1.447   ! foxr     6731: 	&Apache::lonxml::clear_bubble_lines_for_part();
1.330     albertel 6732: 	my $result=&Apache::lonnet::ssi($resource->src(),
1.435     foxr     6733: 					('symb' => $resource->symb()),
                   6734: 					('grade_target' => 'analyze'),
                   6735: 					('grade_courseid' => $cid),
                   6736: 					('grade_domain' => $udom),
                   6737: 					('grade_username' => $uname));
1.436     albertel 6738: 	my (undef, $an) =
1.435     foxr     6739: 	    split(/_HASH_REF__/,$result, 2);
                   6740: 
                   6741: 	my %analysis = &Apache::lonnet::str2hash($an);
                   6742: 
                   6743: 
                   6744: 
                   6745: 	foreach my $part_id (@{$analysis{'parts'}}) {
1.447   ! foxr     6746: 	    my ($trash, $part) = split(/\./, $part_id);
        !          6747: 
        !          6748: 	    my $lines = $analysis{"$part_id.bubble_lines"}[0];
        !          6749: 
        !          6750: 	    # TODO - make this a persistent hash not an array.
        !          6751: 
        !          6752: 
        !          6753: 	    $first_bubble_line{$response_number}           = $bubble_line;
        !          6754: 	    $bubble_lines_per_response{$response_number}   = $lines;
        !          6755: 	    $response_number++;
        !          6756: 
        !          6757: 	    $bubble_line +=  $lines;
        !          6758: 	    $total_lines +=  $lines;
1.435     foxr     6759: 	}
                   6760: 
1.191     albertel 6761:     }
                   6762:     &Apache::lonnet::delenv('scantron\.');
1.447   ! foxr     6763: 
        !          6764:     &save_bubble_lines();
1.330     albertel 6765:     $env{'form.scantron_maxbubble'} =
1.435     foxr     6766: 	$total_lines;
1.257     albertel 6767:     return $env{'form.scantron_maxbubble'};
1.191     albertel 6768: }
                   6769: 
1.423     albertel 6770: =pod
                   6771: 
                   6772: =item scantron_validate_missingbubbles
                   6773: 
1.424     albertel 6774:    Validates all scanlines in the selected file to not have any
1.447   ! foxr     6775:     answers that don't have bubbles that have not been verified
        !          6776:     to be bubble free.
1.424     albertel 6777: 
1.423     albertel 6778: =cut
                   6779: 
1.157     albertel 6780: sub scantron_validate_missingbubbles {
                   6781:     my ($r,$currentphase) = @_;
                   6782:     #get student info
                   6783:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6784:     my %idmap=&username_to_idmap($classlist);
                   6785: 
                   6786:     #get scantron line setup
1.257     albertel 6787:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6788:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 6789:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 6790:     if (!$max_bubble) { $max_bubble=2**31; }
                   6791:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6792: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6793: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6794: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6795: 						 $scan_data);
                   6796: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   6797: 	my @to_correct;
                   6798: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
                   6799: 	    if ($missing > $max_bubble) { next; }
                   6800: 	    push(@to_correct,$missing);
                   6801: 	}
                   6802: 	if (@to_correct) {
                   6803: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6804: 				     $line,'missingbubble',\@to_correct);
                   6805: 	    return (1,$currentphase);
                   6806: 	}
                   6807: 
                   6808:     }
                   6809:     return (0,$currentphase+1);
                   6810: }
                   6811: 
1.423     albertel 6812: =pod
                   6813: 
                   6814: =item scantron_process_students
                   6815: 
                   6816:    Routine that does the actual grading of the bubble sheet information.
                   6817: 
                   6818:    The parsed scanline hash is added to %env 
                   6819: 
                   6820:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   6821:    foreach resource , with the form data of
                   6822: 
                   6823: 	'submitted'     =>'scantron' 
                   6824: 	'grade_target'  =>'grade',
                   6825: 	'grade_username'=> username of student
                   6826: 	'grade_domain'  => domain of student
                   6827: 	'grade_courseid'=> of course
                   6828: 	'grade_symb'    => symb of resource to grade
                   6829: 
                   6830:     This triggers a grading pass. The problem grading code takes care
                   6831:     of converting the bubbled letter information (now in %env) into a
                   6832:     valid submission.
                   6833: 
                   6834: =cut
                   6835: 
1.82      albertel 6836: sub scantron_process_students {
1.75      albertel 6837:     my ($r) = @_;
1.257     albertel 6838:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 6839:     my ($symb)=&get_symb($r);
1.81      albertel 6840:     if (!$symb) {return '';}
1.324     albertel 6841:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 6842: 
1.257     albertel 6843:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6844:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 6845:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6846:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 6847:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 6848:     my $map=$navmap->getResourceByUrl($sequence);
                   6849:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.140     albertel 6850: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 6851:     my $result= <<SCANTRONFORM;
1.81      albertel 6852: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   6853:   <input type="hidden" name="command" value="scantron_configphase" />
                   6854:   $default_form_data
                   6855: SCANTRONFORM
1.82      albertel 6856:     $r->print($result);
                   6857: 
                   6858:     my @delayqueue;
1.140     albertel 6859:     my %completedstudents;
                   6860:     
1.200     albertel 6861:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 6862:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 6863:  				    'Scantron Progress',$count,
1.195     albertel 6864: 				    'inline',undef,'scantronupload');
1.140     albertel 6865:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   6866: 					  'Processing first student');
                   6867:     my $start=&Time::HiRes::time();
1.158     albertel 6868:     my $i=-1;
1.200     albertel 6869:     my ($uname,$udom,$started);
1.447   ! foxr     6870: 
        !          6871:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
        !          6872: 
1.157     albertel 6873:     while ($i<$scanlines->{'count'}) {
                   6874:  	($uname,$udom)=('','');
                   6875:  	$i++;
1.200     albertel 6876:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6877:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 6878: 	if ($started) {
                   6879: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   6880: 						     'last student');
                   6881: 	}
                   6882: 	$started=1;
1.157     albertel 6883:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6884:  						 $scan_data);
                   6885:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   6886:  					      \%idmap,$i)) {
                   6887:   	    &scantron_add_delay(\@delayqueue,$line,
                   6888:  				'Unable to find a student that matches',1);
                   6889:  	    next;
                   6890:   	}
                   6891:  	if (exists $completedstudents{$uname}) {
                   6892:  	    &scantron_add_delay(\@delayqueue,$line,
                   6893:  				'Student '.$uname.' has multiple sheets',2);
                   6894:  	    next;
                   6895:  	}
                   6896:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 6897: 
                   6898: 	&Apache::lonxml::clear_problem_counter();
1.157     albertel 6899:   	&Apache::lonnet::appenv(%$scan_record);
1.376     albertel 6900: 
                   6901: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   6902: 	    &scantron_putfile($scanlines,$scan_data);
                   6903: 	}
1.161     albertel 6904: 	
                   6905: 	my $i=0;
1.83      albertel 6906: 	foreach my $resource (@resources) {
1.85      albertel 6907: 	    $i++;
1.193     albertel 6908: 	    my %form=('submitted'     =>'scantron',
                   6909: 		      'grade_target'  =>'grade',
                   6910: 		      'grade_username'=>$uname,
                   6911: 		      'grade_domain'  =>$udom,
1.257     albertel 6912: 		      'grade_courseid'=>$env{'request.course.id'},
1.193     albertel 6913: 		      'grade_symb'    =>$resource->symb());
1.383     albertel 6914: 	    if (exists($scan_record->{'scantron.CODE'})
                   6915: 		&& 
                   6916: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
1.193     albertel 6917: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
1.224     albertel 6918: 	    } else {
                   6919: 		$form{'CODE'}='';
1.193     albertel 6920: 	    }
                   6921: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
1.227     albertel 6922: 	    if ($result ne '') {
                   6923: 	    }
1.213     albertel 6924: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
1.83      albertel 6925: 	}
1.140     albertel 6926: 	$completedstudents{$uname}={'line'=>$line};
1.213     albertel 6927: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 6928:     } continue {
1.330     albertel 6929: 	&Apache::lonxml::clear_problem_counter();
1.83      albertel 6930: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 6931:     }
1.140     albertel 6932:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.172     albertel 6933: #    my $lasttime = &Time::HiRes::time()-$start;
                   6934: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 6935: 
1.200     albertel 6936:     $r->print("</form>");
1.324     albertel 6937:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 6938:     return '';
1.75      albertel 6939: }
1.157     albertel 6940: 
1.423     albertel 6941: =pod
                   6942: 
                   6943: =item scantron_upload_scantron_data
                   6944: 
                   6945:     Creates the screen for adding a new bubble sheet data file to a course.
                   6946: 
                   6947: =cut
                   6948: 
1.157     albertel 6949: sub scantron_upload_scantron_data {
                   6950:     my ($r)=@_;
1.257     albertel 6951:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 6952:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 6953: 							  'domainid',
                   6954: 							  'coursename');
1.257     albertel 6955:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 6956: 						   'domainid');
1.324     albertel 6957:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.157     albertel 6958:     $r->print(<<UPLOAD);
                   6959: <script type="text/javascript" language="javascript">
                   6960:     function checkUpload(formname) {
                   6961: 	if (formname.upfile.value == "") {
                   6962: 	    alert("Please use the browse button to select a file from your local directory.");
                   6963: 	    return false;
                   6964: 	}
                   6965: 	formname.submit();
                   6966:     }
                   6967: </script>
                   6968: 
                   6969: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
1.162     albertel 6970: $default_form_data
1.181     albertel 6971: <table>
                   6972: <tr><td>$select_link </td></tr>
                   6973: <tr><td>Course ID:   </td><td><input name='courseid' type='text' />  </td></tr>
                   6974: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
                   6975: <tr><td>Domain:      </td><td>$domsel                                </td></tr>
                   6976: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
                   6977: </table>
1.157     albertel 6978: <input name='command' value='scantronupload_save' type='hidden' />
                   6979: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   6980: </form>
                   6981: UPLOAD
                   6982:     return '';
                   6983: }
                   6984: 
1.423     albertel 6985: =pod
                   6986: 
                   6987: =item scantron_upload_scantron_data_save
                   6988: 
                   6989:    Adds a provided bubble information data file to the course if user
                   6990:    has the correct privileges to do so.  
                   6991: 
                   6992: =cut
                   6993: 
1.157     albertel 6994: sub scantron_upload_scantron_data_save {
                   6995:     my($r)=@_;
1.324     albertel 6996:     my ($symb)=&get_symb($r,1);
1.182     albertel 6997:     my $doanotherupload=
                   6998: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   6999: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
                   7000: 	'<input type="submit" name="submit" value="Do Another Upload" />'."\n".
                   7001: 	'</form>'."\n";
1.257     albertel 7002:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7003: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7004: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.162     albertel 7005: 	$r->print("You are not allowed to upload Scantron data to the requested course.<br />");
1.182     albertel 7006: 	if ($symb) {
1.324     albertel 7007: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 7008: 	} else {
                   7009: 	    $r->print($doanotherupload);
                   7010: 	}
1.162     albertel 7011: 	return '';
                   7012:     }
1.257     albertel 7013:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.211     ng       7014:     $r->print("Doing upload to ".$coursedata{'description'}." <br />");
1.257     albertel 7015:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 7016:     #FIXME
                   7017:     #copied from lonnet::userfileupload()
                   7018:     #make that function able to target a specified course
                   7019:     # Replace Windows backslashes by forward slashes
                   7020:     $fname=~s/\\/\//g;
                   7021:     # Get rid of everything but the actual filename
                   7022:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   7023:     # Replace spaces by underscores
                   7024:     $fname=~s/\s+/\_/g;
                   7025:     # Replace all other weird characters by nothing
                   7026:     $fname=~s/[^\w\.\-]//g;
                   7027:     # See if there is anything left
                   7028:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       7029:     my $uploadedfile=$fname;
1.157     albertel 7030:     $fname='scantron_orig_'.$fname;
1.257     albertel 7031:     if (length($env{'form.upfile'}) < 2) {
1.398     albertel 7032: 	$r->print("<span class=\"LC_error\">Error:</span> The file you attempted to upload, <tt>".&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</tt>, contained no information. Please check that you entered the correct filename.");
1.183     albertel 7033:     } else {
1.275     albertel 7034: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 7035: 	if ($result =~ m|^/uploaded/|) {
1.398     albertel 7036: 	    $r->print("<span class=\"LC_success\">Success:</span> Successfully uploaded ".(length($env{'form.upfile'})-1)." bytes of data into location <tt>".$result."</tt>");
1.210     albertel 7037: 	} else {
1.398     albertel 7038: 	    $r->print("<span class=\"LC_error\">Error:</span> An error (".$result.") occurred when attempting to upload the file, <tt>".&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</tt>");
1.183     albertel 7039: 	}
                   7040:     }
1.174     albertel 7041:     if ($symb) {
1.209     ng       7042: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 7043:     } else {
1.182     albertel 7044: 	$r->print($doanotherupload);
1.174     albertel 7045:     }
1.157     albertel 7046:     return '';
                   7047: }
                   7048: 
1.423     albertel 7049: =pod
                   7050: 
                   7051: =item valid_file
                   7052: 
1.424     albertel 7053:    Validates that the requested bubble data file exists in the course.
1.423     albertel 7054: 
                   7055: =cut
                   7056: 
1.202     albertel 7057: sub valid_file {
                   7058:     my ($requested_file)=@_;
                   7059:     foreach my $filename (sort(&scantron_filenames())) {
                   7060: 	if ($requested_file eq $filename) { return 1; }
                   7061:     }
                   7062:     return 0;
                   7063: }
                   7064: 
1.423     albertel 7065: =pod
                   7066: 
                   7067: =item scantron_download_scantron_data
                   7068: 
                   7069:    Shows a list of the three internal files (original, corrected,
                   7070:    skipped) for a specific bubble sheet data file that exists in the
                   7071:    course.
                   7072: 
                   7073: =cut
                   7074: 
1.202     albertel 7075: sub scantron_download_scantron_data {
                   7076:     my ($r)=@_;
1.324     albertel 7077:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 7078:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7079:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7080:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 7081:     if (! &valid_file($file)) {
                   7082: 	$r->print(<<ERROR);
                   7083: 	<p>
                   7084: 	    The requested file name was invalid.
                   7085:         </p>
                   7086: ERROR
1.324     albertel 7087: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7088: 	return;
                   7089:     }
                   7090:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   7091:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   7092:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   7093:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   7094:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   7095:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
                   7096:     $r->print(<<DOWNLOAD);
                   7097:     <p>
                   7098: 	<a href="$orig">Original</a> file as uploaded by the scantron office.
                   7099:     </p>
                   7100:     <p>
                   7101: 	<a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
                   7102:     </p>
                   7103:     <p>
                   7104: 	<a href="$skipped">Skipped</a>, a file of records that were skipped.
                   7105:     </p>
                   7106: DOWNLOAD
1.324     albertel 7107:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7108:     return '';
                   7109: }
1.157     albertel 7110: 
1.423     albertel 7111: =pod
                   7112: 
                   7113: =back
                   7114: 
                   7115: =cut
                   7116: 
1.75      albertel 7117: #-------- end of section for handling grading scantron forms -------
                   7118: #
                   7119: #-------------------------------------------------------------------
                   7120: 
1.72      ng       7121: #-------------------------- Menu interface -------------------------
                   7122: #
                   7123: #--- Show a Grading Menu button - Calls the next routine ---
                   7124: sub show_grading_menu_form {
1.324     albertel 7125:     my ($symb)=@_;
1.125     ng       7126:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 7127: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 7128: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       7129: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
                   7130: 	'<input type="submit" name="submit" value="Grading Menu" />'."\n".
                   7131: 	'</form>'."\n";
                   7132:     return $result;
                   7133: }
                   7134: 
1.77      ng       7135: # -- Retrieve choices for grading form
                   7136: sub savedState {
                   7137:     my %savedState = ();
1.257     albertel 7138:     if ($env{'form.saveState'}) {
                   7139: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       7140: 	    my ($key,$value) = split(/=/,$_,2);
                   7141: 	    $savedState{$key} = $value;
                   7142: 	}
                   7143:     }
                   7144:     return \%savedState;
                   7145: }
1.76      ng       7146: 
1.443     banghart 7147: sub grading_menu {
                   7148:     my ($request) = @_;
                   7149:     my ($symb)=&get_symb($request);
                   7150:     if (!$symb) {return '';}
                   7151:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   7152:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   7153: 
                   7154:     #
                   7155:     # Define menu data
1.444     banghart 7156:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   7157:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   7158:     $request->print($table);
1.443     banghart 7159:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   7160:                   'handgrade'=>$hdgrade,
                   7161:                   'probTitle'=>$probTitle,
                   7162:                   'command'=>'submit_options',
                   7163:                   'saveState'=>"",
                   7164:                   'gradingMenu'=>1,
                   7165:                   'showgrading'=>"yes");
                   7166:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7167:     my @menu = ({ url => $url,
                   7168:                      name => &mt('Manual Grading/View Submissions'),
                   7169:                      short_description => 
                   7170:     &mt('Start the process of hand grading submissions.'),
                   7171:                  });
                   7172:     $fields{'command'} = 'csvform';
                   7173:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7174:     push (@menu, { url => $url,
                   7175:                    name => &mt('Upload Scores'),
                   7176:                    short_description => 
                   7177:             &mt('Specify a file containing the class scores for current resource.')});
                   7178:     $fields{'command'} = 'processclicker';
                   7179:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7180:     push (@menu, { url => $url,
                   7181:                    name => &mt('Process Clicker'),
                   7182:                    short_description => 
                   7183:             &mt('Specify a file containing the clicker information for this resource.')});
                   7184:     $fields{'command'} = 'scantron_selectphase';
                   7185:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7186:     push (@menu, { url => $url,
                   7187:                    name => &mt('Grade Scantron Forms'),
                   7188:                    short_description => 
                   7189:             &mt('')});
                   7190:     $fields{'command'} = 'verify';
                   7191:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.445     banghart 7192:     push (@menu, { url => "",
                   7193:                    jscript => ' onClick="javascript:checkChoice2(document.forms.gradingMenu,\'5\',\'verify\')" ',
1.443     banghart 7194:                    name => &mt('Verify Receipt'),
                   7195:                    short_description => 
                   7196:             &mt('')});
                   7197:     $fields{'command'} = 'manage';
                   7198:     $url = &Apache::lonhtmlcommon::build_url('/adm/helper/resettimes.helper',\%fields);
                   7199:     push (@menu, { url => $url,
                   7200:                    name => &mt('Manage Access Times'),
                   7201:                    short_description => 
                   7202:             &mt('')});
                   7203:     $fields{'command'} = 'view';
                   7204:     $url = &Apache::lonhtmlcommon::build_url('/adm/pickcode',\%fields);
                   7205:     push (@menu, { url => $url,
                   7206:                    name => &mt('View Saved CODEs'),
                   7207:                    short_description => 
                   7208:             &mt('')});
                   7209: 
                   7210:     #
                   7211:     # Create the menu
                   7212:     my $Str;
1.444     banghart 7213:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 7214:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   7215:     $Str .= '<input type="hidden" name="command" value="" />'.
                   7216:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   7217: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   7218: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" ue="" />'."\n".
                   7219: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   7220: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   7221: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7222: 
1.443     banghart 7223:     foreach my $menudata (@menu) {
1.445     banghart 7224:         if ($menudata->{'name'} ne &mt('Verify Receipt')) {
                   7225:             $Str .='    <h3><a '.
                   7226:                 $menudata->{'jscript'}.
                   7227:                 ' href="'.
                   7228:                 $menudata->{'url'}.'" >'.
                   7229:                 $menudata->{'name'}."</a></h3>\n";
                   7230:         } else {
                   7231:             $Str .='    <h3><a '.
                   7232:                 $menudata->{'jscript'}.
1.446     banghart 7233:                 ' href="javascript:checkChoice2(document.forms.gradingMenu,\'5\',\'verify\')" >'.
1.445     banghart 7234:                 $menudata->{'name'}."</a></h3>\n";
1.446     banghart 7235:             $Str .= ('&nbsp;'x8).
                   7236:                     ' receipt: '.&Apache::lonnet::recprefix($env{'request.course.id'}).
1.445     banghart 7237:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
1.444     banghart 7238:         }
1.443     banghart 7239:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
                   7240:             "\n";
                   7241:     }
                   7242:     $Str .="</dl>\n";
1.444     banghart 7243:     $Str .="</form>\n";
1.443     banghart 7244:     $request->print(<<GRADINGMENUJS);
                   7245: <script type="text/javascript" language="javascript">
                   7246:     function checkChoice(formname,val,cmdx) {
                   7247: 	if (val <= 2) {
                   7248: 	    var cmd = radioSelection(formname.radioChoice);
                   7249: 	    var cmdsave = cmd;
                   7250: 	} else {
                   7251: 	    cmd = cmdx;
                   7252: 	    cmdsave = 'submission';
                   7253: 	}
                   7254: 	formname.command.value = cmd;
                   7255: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
                   7256: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
                   7257: 	if (val < 5) formname.submit();
                   7258: 	if (val == 5) {
                   7259: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   7260: 	    formname.submit();
                   7261: 	}
                   7262: 	if (val < 7) formname.submit();
                   7263:     }
1.445     banghart 7264:     function checkChoice2(formname,val,cmdx) {
                   7265: 	if (val <= 2) {
                   7266: 	    var cmd = radioSelection(formname.radioChoice);
                   7267: 	    var cmdsave = cmd;
                   7268: 	} else {
                   7269: 	    cmd = cmdx;
                   7270: 	    cmdsave = 'submission';
                   7271: 	}
                   7272: 	formname.command.value = cmd;
                   7273: 	if (val < 5) formname.submit();
                   7274: 	if (val == 5) {
                   7275: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   7276: 	    formname.submit();
                   7277: 	}
                   7278: 	if (val < 7) formname.submit();
                   7279:     }
1.443     banghart 7280: 
                   7281:     function checkReceiptNo(formname,nospace) {
                   7282: 	var receiptNo = formname.receipt.value;
                   7283: 	var checkOpt = false;
                   7284: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   7285: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   7286: 	if (checkOpt) {
                   7287: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   7288: 	    formname.receipt.value = "";
                   7289: 	    formname.receipt.focus();
                   7290: 	    return false;
                   7291: 	}
                   7292: 	return true;
                   7293:     }
                   7294: </script>
                   7295: GRADINGMENUJS
                   7296:     &commonJSfunctions($request);
                   7297:     my $result='<h3>&nbsp;<span class="LC_info">Manual Grading/View Submission</span></h3>';
                   7298:     $result.=$table;
                   7299:     my (undef,$sections) = &getclasslist('all','0');
                   7300:     my $savedState = &savedState();
                   7301:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
                   7302:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
                   7303:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
                   7304:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
                   7305: 
                   7306:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   7307: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   7308: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   7309: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" ue="" />'."\n".
                   7310: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   7311: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   7312: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7313: 
                   7314:     $result.='<table width="100%" border="0"><tr><td bgcolor=#777777>'."\n".
                   7315: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
                   7316: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
                   7317: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
                   7318: 
                   7319:     $result.='<table width="100%" border="0">';
                   7320:     $result.='<tr bgcolor="#ffffe6" valign="top">'."\n";
                   7321:     $result.='<td><b>'.&mt('Sections').'</b></td>';
                   7322: #    $result.='<td>Groups</td>';
                   7323:     $result.='<td><b>'.&mt('Access Status').'</td>'."\n";
                   7324:     $result.='</tr>';
                   7325:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
                   7326: 	'&nbsp;<select name="section" multiple="multiple" size="3">'."\n";
                   7327:     if (ref($sections)) {
                   7328: 	foreach (sort (@$sections)) {
                   7329: 	    $result.='<option value="'.$_.'" '.
                   7330: 		($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
                   7331: 	}
                   7332:     }
                   7333:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
                   7334:     return $Str;    
                   7335: }
                   7336: 
                   7337: 
                   7338: #--- Displays the submissions first page -------
                   7339: sub submit_options {
1.72      ng       7340:     my ($request) = @_;
1.324     albertel 7341:     my ($symb)=&get_symb($request);
1.72      ng       7342:     if (!$symb) {return '';}
1.76      ng       7343:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       7344: 
                   7345:     $request->print(<<GRADINGMENUJS);
                   7346: <script type="text/javascript" language="javascript">
1.116     ng       7347:     function checkChoice(formname,val,cmdx) {
                   7348: 	if (val <= 2) {
                   7349: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       7350: 	    var cmdsave = cmd;
1.116     ng       7351: 	} else {
                   7352: 	    cmd = cmdx;
1.118     ng       7353: 	    cmdsave = 'submission';
1.116     ng       7354: 	}
                   7355: 	formname.command.value = cmd;
1.118     ng       7356: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 7357: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       7358: 	if (val < 5) formname.submit();
                   7359: 	if (val == 5) {
1.72      ng       7360: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   7361: 	    formname.submit();
                   7362: 	}
1.238     albertel 7363: 	if (val < 7) formname.submit();
1.72      ng       7364:     }
                   7365: 
                   7366:     function checkReceiptNo(formname,nospace) {
                   7367: 	var receiptNo = formname.receipt.value;
                   7368: 	var checkOpt = false;
                   7369: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   7370: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   7371: 	if (checkOpt) {
                   7372: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   7373: 	    formname.receipt.value = "";
                   7374: 	    formname.receipt.focus();
                   7375: 	    return false;
                   7376: 	}
                   7377: 	return true;
                   7378:     }
                   7379: </script>
                   7380: GRADINGMENUJS
1.118     ng       7381:     &commonJSfunctions($request);
1.398     albertel 7382:     my $result='<h3>&nbsp;<span class="LC_info">Manual Grading/View Submission</span></h3>';
1.324     albertel 7383:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.118     ng       7384:     $result.=$table;
1.76      ng       7385:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       7386:     my $savedState = &savedState();
1.118     ng       7387:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       7388:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       7389:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       7390:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       7391: 
                   7392:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 7393: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       7394: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   7395: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       7396: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       7397: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       7398: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       7399: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7400: 
1.446     banghart 7401:     $result.='<table border="0"><tr><td bgcolor=#777777>'."\n".
                   7402: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n".
1.72      ng       7403: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
1.116     ng       7404: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
                   7405: 
1.326     albertel 7406:     $result.='<table width="100%" border="0">';
1.442     banghart 7407:     $result.='<tr bgcolor="#ffffe6" valign="top">'."\n";
                   7408:     $result.='<td><b>'.&mt('Sections').'</b></td>';
1.446     banghart 7409:     $result.='<td><b>'.&mt('Groups').'</b></td>';
1.442     banghart 7410:     $result.='<td><b>'.&mt('Access Status').'</td>'."\n";
                   7411:     $result.='</tr>';
1.116     ng       7412:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
1.442     banghart 7413: 	'&nbsp;<select name="section" multiple="multiple" size="3">'."\n";
1.116     ng       7414:     if (ref($sections)) {
1.155     albertel 7415: 	foreach (sort (@$sections)) {
                   7416: 	    $result.='<option value="'.$_.'" '.
1.401     albertel 7417: 		($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
1.155     albertel 7418: 	}
1.116     ng       7419:     }
1.401     albertel 7420:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.446     banghart 7421:     $result.= '</td><td>'."\n";
                   7422:     $result.= &Apache::lonstatistics::GroupSelect('group','multiple',3);
1.442     banghart 7423:     $result.='</td><td>'."\n";
                   7424:     $result.=&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,3,undef,'mult');
1.72      ng       7425: 
1.116     ng       7426:     $result.='</td></tr>';
                   7427: 
1.442     banghart 7428:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="3"><label>'.
1.118     ng       7429: 	'<input type="radio" name="radioChoice" value="submission" '.
1.401     albertel 7430: 	($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
1.288     albertel 7431: 	'</label> <select name="submitonly">'.
1.145     albertel 7432: 	'<option value="yes" '.
1.401     albertel 7433: 	($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>'.
1.301     albertel 7434: 	'<option value="queued" '.
1.401     albertel 7435: 	($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>'.
1.145     albertel 7436: 	'<option value="graded" '.
1.401     albertel 7437: 	($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>'.
1.156     albertel 7438: 	'<option value="incorrect" '.
1.401     albertel 7439: 	($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>'.
1.145     albertel 7440: 	'<option value="all" '.
1.401     albertel 7441: 	($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option></select></td></tr>'."\n";
1.72      ng       7442: 
1.442     banghart 7443:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
1.288     albertel 7444: 	'<label><input type="radio" name="radioChoice" value="viewgrades" '.
1.401     albertel 7445: 	($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
1.288     albertel 7446: 	'<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
1.72      ng       7447: 
1.442     banghart 7448:     $result.='<tr bgcolor="#ffffe6" valign="top"><td colspan="2">'.
1.288     albertel 7449: 	'<label><input type="radio" name="radioChoice" value="pickStudentPage" '.
1.401     albertel 7450: 	($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
1.288     albertel 7451: 	'The <b>complete</b> set/page/sequence: For one student</label></td></tr>'."\n";
1.46      ng       7452: 
1.442     banghart 7453:     $result.='<tr bgcolor="#ffffe6"><td colspan="2"><br />'.
1.126     ng       7454: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
1.116     ng       7455: 	'</td></tr></table>'."\n";
                   7456: 
1.446     banghart 7457:     $result.='</td>'; #<td valign="top">';
1.116     ng       7458: 
1.446     banghart 7459: #    $result.='<table width="100%" border="0">';
                   7460: #    $result.='<tr bgcolor="#ffffe6"><td>'.
                   7461: #	'<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
                   7462: #	' '.&mt('scores from file').' </td></tr>'."\n";
                   7463: #
                   7464: #    $result.='<tr bgcolor="#ffffe6"><td>'.
                   7465: #        '<input type="button" onClick="javascript:checkChoice(this.form,\'6\',\'processclicker\');" value="'.&mt('Process').'" />'.
                   7466: #        ' '.&mt('clicker file').' </td></tr>'."\n";
                   7467: #
                   7468: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7469: #	'<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
                   7470: #	'" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
                   7471: #
                   7472: #    if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
                   7473: #	$result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
                   7474: #	    '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
                   7475: #	    ' '.&mt('receipt').': '.
                   7476: #	    &Apache::lonnet::recprefix($env{'request.course.id'}).
                   7477: #	    '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
                   7478: #	    '</td></tr>'."\n";
                   7479: #    } 
                   7480: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7481: #	'<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
                   7482: #	'" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
                   7483: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7484: #	'<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
                   7485: #	'" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
                   7486: #
                   7487: #    $result.='</table>'."\n".'</td>';
                   7488:     $result.= '</tr></table>'."\n".
1.401     albertel 7489: 	'</td></tr></table></form>'."\n";
1.44      ng       7490:     return $result;
1.2       albertel 7491: }
                   7492: 
1.285     albertel 7493: sub reset_perm {
                   7494:     undef(%perm);
                   7495: }
                   7496: 
                   7497: sub init_perm {
                   7498:     &reset_perm();
1.300     albertel 7499:     foreach my $test_perm ('vgr','mgr','opa') {
                   7500: 
                   7501: 	my $scope = $env{'request.course.id'};
                   7502: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   7503: 
                   7504: 	    $scope .= '/'.$env{'request.course.sec'};
                   7505: 	    if ( $perm{$test_perm}=
                   7506: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   7507: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   7508: 	    } else {
                   7509: 		delete($perm{$test_perm});
                   7510: 	    }
1.285     albertel 7511: 	}
                   7512:     }
                   7513: }
                   7514: 
1.400     www      7515: sub gather_clicker_ids {
1.408     albertel 7516:     my %clicker_ids;
1.400     www      7517: 
                   7518:     my $classlist = &Apache::loncoursedata::get_classlist();
                   7519: 
                   7520:     # Set up a couple variables.
1.407     albertel 7521:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   7522:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      7523:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      7524: 
1.407     albertel 7525:     foreach my $student (keys(%$classlist)) {
1.438     www      7526:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 7527:         my $username = $classlist->{$student}->[$username_idx];
                   7528:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      7529:         my $clickers =
1.408     albertel 7530: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      7531:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      7532:             $id=~s/^[\#0]+//;
1.421     www      7533:             $id=~s/[\-\:]//g;
1.407     albertel 7534:             if (exists($clicker_ids{$id})) {
1.408     albertel 7535: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      7536:             } else {
1.408     albertel 7537: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      7538:             }
                   7539:         }
                   7540:     }
1.407     albertel 7541:     return %clicker_ids;
1.400     www      7542: }
                   7543: 
1.402     www      7544: sub gather_adv_clicker_ids {
1.408     albertel 7545:     my %clicker_ids;
1.402     www      7546:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7547:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7548:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 7549:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      7550:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   7551:             my ($puname,$pudom)=split(/\:/,$person);
                   7552:             my $clickers =
1.408     albertel 7553: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      7554:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      7555: 		$id=~s/^[\#0]+//;
1.421     www      7556:                 $id=~s/[\-\:]//g;
1.408     albertel 7557: 		if (exists($clicker_ids{$id})) {
                   7558: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   7559: 		} else {
                   7560: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   7561: 		}
1.405     www      7562:             }
1.402     www      7563:         }
                   7564:     }
1.407     albertel 7565:     return %clicker_ids;
1.402     www      7566: }
                   7567: 
1.413     www      7568: sub clicker_grading_parameters {
                   7569:     return ('gradingmechanism' => 'scalar',
                   7570:             'upfiletype' => 'scalar',
                   7571:             'specificid' => 'scalar',
                   7572:             'pcorrect' => 'scalar',
                   7573:             'pincorrect' => 'scalar');
                   7574: }
                   7575: 
1.400     www      7576: sub process_clicker {
                   7577:     my ($r)=@_;
                   7578:     my ($symb)=&get_symb($r);
                   7579:     if (!$symb) {return '';}
                   7580:     my $result=&checkforfile_js();
                   7581:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   7582:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   7583:     $result.=$table;
                   7584:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   7585:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
                   7586:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
                   7587:         '.</b></td></tr>'."\n";
                   7588:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      7589: # Attempt to restore parameters from last session, set defaults if not present
                   7590:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7591:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   7592:                                                  \%Saveable_Parameters);
                   7593:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   7594:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   7595:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   7596:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   7597: 
                   7598:     my %checked;
                   7599:     foreach my $gradingmechanism ('attendance','personnel','specific') {
                   7600:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
                   7601:           $checked{$gradingmechanism}="checked='checked'";
                   7602:        }
                   7603:     }
                   7604: 
1.400     www      7605:     my $upload=&mt("Upload File");
                   7606:     my $type=&mt("Type");
1.402     www      7607:     my $attendance=&mt("Award points just for participation");
                   7608:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      7609:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.402     www      7610:     my $pcorrect=&mt("Percentage points for correct solution");
                   7611:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      7612:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      7613: 						   ('iclicker' => 'i>clicker',
                   7614:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 7615:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      7616:     $result.=<<ENDUPFORM;
1.402     www      7617: <script type="text/javascript">
                   7618: function sanitycheck() {
                   7619: // Accept only integer percentages
                   7620:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   7621:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   7622: // Find out grading choice
                   7623:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7624:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   7625:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   7626:       }
                   7627:    }
                   7628: // By default, new choice equals user selection
                   7629:    newgradingchoice=gradingchoice;
                   7630: // Not good to give more points for false answers than correct ones
                   7631:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   7632:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   7633:    }
                   7634: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   7635:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   7636:       document.forms.gradesupload.pcorrect.value=100;
                   7637:       document.forms.gradesupload.pincorrect.value=100;
                   7638:    }
                   7639: // If the values are different, cannot be attendance only
                   7640:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   7641:        (gradingchoice=='attendance')) {
                   7642:        newgradingchoice='personnel';
                   7643:    }
                   7644: // Change grading choice to new one
                   7645:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7646:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   7647:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   7648:       } else {
                   7649:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   7650:       }
                   7651:    }
                   7652: // Remember the old state
                   7653:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   7654: }
                   7655: </script>
1.400     www      7656: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   7657: <input type="hidden" name="symb" value="$symb" />
                   7658: <input type="hidden" name="command" value="processclickerfile" />
                   7659: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7660: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   7661: <input type="file" name="upfile" size="50" />
                   7662: <br /><label>$type: $selectform</label>
1.413     www      7663: <br /><label>$attendance: <input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" /></label>
                   7664: <br /><label>$personnel: <input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" /></label>
                   7665: <br /><label>$specific: <input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" /></label>
1.414     www      7666: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.413     www      7667: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
                   7668: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
                   7669: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
1.400     www      7670: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
                   7671: </form>
                   7672: ENDUPFORM
                   7673:     $result.='</td></tr></table>'."\n".
                   7674:              '</td></tr></table><br /><br />'."\n";
                   7675:     $result.=&show_grading_menu_form($symb);
                   7676:     return $result;
                   7677: }
                   7678: 
                   7679: sub process_clicker_file {
                   7680:     my ($r)=@_;
                   7681:     my ($symb)=&get_symb($r);
                   7682:     if (!$symb) {return '';}
1.413     www      7683: 
                   7684:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7685:     &Apache::loncommon::store_course_settings('grades_clicker',
                   7686:                                               \%Saveable_Parameters);
                   7687: 
1.400     www      7688:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      7689:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 7690: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   7691: 	return $result.&show_grading_menu_form($symb);
1.404     www      7692:     }
1.407     albertel 7693:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 7694:     my %correct_ids;
1.404     www      7695:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 7696: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      7697:     }
                   7698:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      7699: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   7700: 	   $correct_id=~tr/a-z/A-Z/;
                   7701: 	   $correct_id=~s/\s//gs;
                   7702: 	   $correct_id=~s/^[\#0]+//;
1.421     www      7703:            $correct_id=~s/[\-\:]//g;
1.414     www      7704:            if ($correct_id) {
                   7705: 	      $correct_ids{$correct_id}='specified';
                   7706:            }
                   7707:         }
1.400     www      7708:     }
1.404     www      7709:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 7710: 	$result.=&mt('Score based on attendance only');
1.404     www      7711:     } else {
1.408     albertel 7712: 	my $number=0;
1.411     www      7713: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 7714: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      7715: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 7716: 	    if ($correct_ids{$id} eq 'specified') {
                   7717: 		$result.=&mt('specified');
                   7718: 	    } else {
                   7719: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   7720: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   7721: 	    }
                   7722: 	    $number++;
                   7723: 	}
1.411     www      7724:         $result.="</p>\n";
1.408     albertel 7725: 	if ($number==0) {
                   7726: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   7727: 	    return $result.&show_grading_menu_form($symb);
                   7728: 	}
1.404     www      7729:     }
1.405     www      7730:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 7731:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   7732: 		     '<span class="LC_error">',
                   7733: 		     '</span>',
                   7734: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      7735:         return $result.&show_grading_menu_form($symb);
                   7736:     }
1.410     www      7737: 
                   7738: # Were able to get all the info needed, now analyze the file
                   7739: 
1.411     www      7740:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 7741:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      7742:     my $heading=&mt('Scanning clicker file');
                   7743:     $result.=(<<ENDHEADER);
                   7744: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7745: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7746: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7747: <form method="post" action="/adm/grades" name="clickeranalysis">
                   7748: <input type="hidden" name="symb" value="$symb" />
                   7749: <input type="hidden" name="command" value="assignclickergrades" />
                   7750: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7751: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      7752: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   7753: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   7754: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      7755: ENDHEADER
1.408     albertel 7756:     my %responses;
                   7757:     my @questiontitles;
1.405     www      7758:     my $errormsg='';
                   7759:     my $number=0;
                   7760:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 7761: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      7762:     }
1.419     www      7763:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   7764:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   7765:     }
1.411     www      7766:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   7767:              '<input type="hidden" name="number" value="'.$number.'" />'.
1.443     banghart 7768:              &mt('Awarding [_1] percent for corrion(s)',$number).'<br />'.
                   7769:              '<input type="hidden" name="number" value="'.$number.'" />'.
1.411     www      7770:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   7771:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   7772:              '<br />';
1.414     www      7773: # Remember Question Titles
                   7774: # FIXME: Possibly need delimiter other than ":"
                   7775:     for (my $i=0;$i<$number;$i++) {
                   7776:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   7777:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   7778:     }
1.411     www      7779:     my $correct_count=0;
                   7780:     my $student_count=0;
                   7781:     my $unknown_count=0;
1.414     www      7782: # Match answers with usernames
                   7783: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 7784:     foreach my $id (keys(%responses)) {
1.410     www      7785:        if ($correct_ids{$id}) {
1.414     www      7786:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      7787:           $correct_count++;
1.410     www      7788:        } elsif ($clicker_ids{$id}) {
1.437     www      7789:           if ($clicker_ids{$id}=~/\,/) {
                   7790: # More than one user with the same clicker!
                   7791:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   7792:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7793:                            "<select name='multi".$id."'>";
                   7794:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   7795:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   7796:              }
                   7797:              $result.='</select>';
                   7798:              $unknown_count++;
                   7799:           } else {
                   7800: # Good: found one and only one user with the right clicker
                   7801:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   7802:              $student_count++;
                   7803:           }
1.410     www      7804:        } else {
1.411     www      7805:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   7806:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7807:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   7808:                    "\n".&mt("Domain").": ".
                   7809:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   7810:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   7811:           $unknown_count++;
1.410     www      7812:        }
1.405     www      7813:     }
1.412     www      7814:     $result.='<hr />'.
                   7815:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
                   7816:     if ($env{'form.gradingmechanism'} ne 'attendance') {
                   7817:        if ($correct_count==0) {
                   7818:           $errormsg.="Found no correct answers answers for grading!";
                   7819:        } elsif ($correct_count>1) {
1.414     www      7820:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      7821:        }
                   7822:     }
1.428     www      7823:     if ($number<1) {
                   7824:        $errormsg.="Found no questions.";
                   7825:     }
1.412     www      7826:     if ($errormsg) {
                   7827:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   7828:     } else {
                   7829:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   7830:     }
                   7831:     $result.='</form></td></tr></table>'."\n".
1.410     www      7832:              '</td></tr></table><br /><br />'."\n";
1.404     www      7833:     return $result.&show_grading_menu_form($symb);
1.400     www      7834: }
                   7835: 
1.405     www      7836: sub iclicker_eval {
1.406     www      7837:     my ($questiontitles,$responses)=@_;
1.405     www      7838:     my $number=0;
                   7839:     my $errormsg='';
                   7840:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      7841:         my %components=&Apache::loncommon::record_sep($line);
                   7842:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 7843: 	if ($entries[0] eq 'Question') {
                   7844: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   7845: 		$$questiontitles[$number]=$entries[$i];
                   7846: 		$number++;
                   7847: 	    }
                   7848: 	}
                   7849: 	if ($entries[0]=~/^\#/) {
                   7850: 	    my $id=$entries[0];
                   7851: 	    my @idresponses;
                   7852: 	    $id=~s/^[\#0]+//;
                   7853: 	    for (my $i=0;$i<$number;$i++) {
                   7854: 		my $idx=3+$i*6;
                   7855: 		push(@idresponses,$entries[$idx]);
                   7856: 	    }
                   7857: 	    $$responses{$id}=join(',',@idresponses);
                   7858: 	}
1.405     www      7859:     }
                   7860:     return ($errormsg,$number);
                   7861: }
                   7862: 
1.419     www      7863: sub interwrite_eval {
                   7864:     my ($questiontitles,$responses)=@_;
                   7865:     my $number=0;
                   7866:     my $errormsg='';
1.420     www      7867:     my $skipline=1;
                   7868:     my $questionnumber=0;
                   7869:     my %idresponses=();
1.419     www      7870:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   7871:         my %components=&Apache::loncommon::record_sep($line);
                   7872:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      7873:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   7874:         if ($entries[1] eq 'Response') { $skipline=1; }
                   7875:         next if $skipline;
                   7876:         if ($entries[0]!=$questionnumber) {
                   7877:            $questionnumber=$entries[0];
                   7878:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   7879:            $number++;
1.419     www      7880:         }
1.420     www      7881:         my $id=$entries[4];
                   7882:         $id=~s/^[\#0]+//;
1.421     www      7883:         $id=~s/^v\d*\://i;
                   7884:         $id=~s/[\-\:]//g;
1.420     www      7885:         $idresponses{$id}[$number]=$entries[6];
                   7886:     }
                   7887:     foreach my $id (keys %idresponses) {
                   7888:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   7889:        $$responses{$id}=~s/^\s*\,//;
1.419     www      7890:     }
                   7891:     return ($errormsg,$number);
                   7892: }
                   7893: 
1.414     www      7894: sub assign_clicker_grades {
                   7895:     my ($r)=@_;
                   7896:     my ($symb)=&get_symb($r);
                   7897:     if (!$symb) {return '';}
1.416     www      7898: # See which part we are saving to
                   7899:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
                   7900: # FIXME: This should probably look for the first handgradeable part
                   7901:     my $part=$$partlist[0];
                   7902: # Start screen output
1.414     www      7903:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      7904: 
1.414     www      7905:     my $heading=&mt('Assigning grades based on clicker file');
                   7906:     $result.=(<<ENDHEADER);
                   7907: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7908: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7909: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7910: ENDHEADER
                   7911: # Get correct result
                   7912: # FIXME: Possibly need delimiter other than ":"
                   7913:     my @correct=();
1.415     www      7914:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   7915:     my $number=$env{'form.number'};
                   7916:     if ($gradingmechanism ne 'attendance') {
1.414     www      7917:        foreach my $key (keys(%env)) {
                   7918:           if ($key=~/^form\.correct\:/) {
                   7919:              my @input=split(/\,/,$env{$key});
                   7920:              for (my $i=0;$i<=$#input;$i++) {
                   7921:                  if (($correct[$i]) && ($input[$i]) &&
                   7922:                      ($correct[$i] ne $input[$i])) {
                   7923:                     $result.='<br /><span class="LC_warning">'.
                   7924:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   7925:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   7926:                  } elsif ($input[$i]) {
                   7927:                     $correct[$i]=$input[$i];
                   7928:                  }
                   7929:              }
                   7930:           }
                   7931:        }
1.415     www      7932:        for (my $i=0;$i<$number;$i++) {
1.414     www      7933:           if (!$correct[$i]) {
                   7934:              $result.='<br /><span class="LC_error">'.
                   7935:                       &mt('No correct result given for question "[_1]"!',
                   7936:                           $env{'form.question:'.$i}).'</span>';
                   7937:           }
                   7938:        }
                   7939:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   7940:     }
                   7941: # Start grading
1.415     www      7942:     my $pcorrect=$env{'form.pcorrect'};
                   7943:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      7944:     my $storecount=0;
1.415     www      7945:     foreach my $key (keys(%env)) {
1.420     www      7946:        my $user='';
1.415     www      7947:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      7948:           $user=$1;
                   7949:        }
                   7950:        if ($key=~/^form\.unknown\:(.*)$/) {
                   7951:           my $id=$1;
                   7952:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   7953:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      7954:           } elsif ($env{'form.multi'.$id}) {
                   7955:              $user=$env{'form.multi'.$id};
1.420     www      7956:           }
                   7957:        }
                   7958:        if ($user) { 
1.415     www      7959:           my @answer=split(/\,/,$env{$key});
                   7960:           my $sum=0;
                   7961:           for (my $i=0;$i<$number;$i++) {
                   7962:              if ($answer[$i]) {
                   7963:                 if ($gradingmechanism eq 'attendance') {
                   7964:                    $sum+=$pcorrect;
                   7965:                 } else {
                   7966:                    if ($answer[$i] eq $correct[$i]) {
                   7967:                       $sum+=$pcorrect;
                   7968:                    } else {
                   7969:                       $sum+=$pincorrect;
                   7970:                    }
                   7971:                 }
                   7972:              }
                   7973:           }
1.416     www      7974:           my $ave=$sum/(100*$number);
                   7975: # Store
                   7976:           my ($username,$domain)=split(/\:/,$user);
                   7977:           my %grades=();
                   7978:           $grades{"resource.$part.solved"}='correct_by_override';
                   7979:           $grades{"resource.$part.awarded"}=$ave;
                   7980:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   7981:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   7982:                                                  $env{'request.course.id'},
                   7983:                                                  $domain,$username);
                   7984:           if ($returncode ne 'ok') {
                   7985:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   7986:           } else {
                   7987:              $storecount++;
                   7988:           }
1.415     www      7989:        }
                   7990:     }
                   7991: # We are done
1.416     www      7992:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
                   7993:              '</td></tr></table>'."\n".
1.414     www      7994:              '</td></tr></table><br /><br />'."\n";
                   7995:     return $result.&show_grading_menu_form($symb);
                   7996: }
                   7997: 
1.1       albertel 7998: sub handler {
1.41      ng       7999:     my $request=$_[0];
1.447   ! foxr     8000: 
1.434     albertel 8001:     &reset_caches();
1.257     albertel 8002:     if ($env{'browser.mathml'}) {
1.141     www      8003: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       8004:     } else {
1.141     www      8005: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       8006:     }
                   8007:     $request->send_http_header;
1.44      ng       8008:     return '' if $request->header_only;
1.41      ng       8009:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 8010:     my $symb=&get_symb($request,1);
1.160     albertel 8011:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   8012:     my $command=$commands[0];
1.447   ! foxr     8013: 
1.160     albertel 8014:     if ($#commands > 0) {
                   8015: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   8016:     }
1.447   ! foxr     8017: 
        !          8018: 
1.353     albertel 8019:     $request->print(&Apache::loncommon::start_page('Grading'));
1.324     albertel 8020:     if ($symb eq '' && $command eq '') {
1.257     albertel 8021: 	if ($env{'user.adv'}) {
                   8022: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   8023: 		($env{'form.codethree'})) {
                   8024: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   8025: 		    $env{'form.codethree'};
1.41      ng       8026: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   8027: 		    &Apache::lonnet::checkin($token);
                   8028: 		if ($tsymb) {
1.137     albertel 8029: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       8030: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.99      albertel 8031: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
                   8032: 					  ('grade_username' => $tuname,
                   8033: 					   'grade_domain' => $tudom,
                   8034: 					   'grade_courseid' => $tcrsid,
                   8035: 					   'grade_symb' => $tsymb)));
1.41      ng       8036: 		    } else {
1.45      ng       8037: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 8038: 		    }
1.41      ng       8039: 		} else {
1.45      ng       8040: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       8041: 		}
1.14      www      8042: 	    } else {
1.41      ng       8043: 		$request->print(&Apache::lonxml::tokeninputfield());
                   8044: 	    }
                   8045: 	}
                   8046:     } else {
1.285     albertel 8047: 	&init_perm();
1.104     albertel 8048: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 8049: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 8050: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       8051: 	    &pickStudentPage($request);
1.103     albertel 8052: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       8053: 	    &displayPage($request);
1.104     albertel 8054: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       8055: 	    &updateGradeByPage($request);
1.104     albertel 8056: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       8057: 	    &processGroup($request);
1.104     albertel 8058: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 8059: 	    $request->print(&grading_menu($request));
                   8060: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   8061: 	    $request->print(&submit_options($request));
1.104     albertel 8062: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       8063: 	    $request->print(&viewgrades($request));
1.104     albertel 8064: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       8065: 	    $request->print(&processHandGrade($request));
1.106     albertel 8066: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       8067: 	    $request->print(&editgrades($request));
1.106     albertel 8068: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       8069: 	    $request->print(&verifyreceipt($request));
1.400     www      8070:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   8071:             $request->print(&process_clicker($request));
                   8072:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   8073:             $request->print(&process_clicker_file($request));
1.414     www      8074:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   8075:             $request->print(&assign_clicker_grades($request));
1.106     albertel 8076: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       8077: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 8078: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       8079: 	    $request->print(&csvupload($request));
1.106     albertel 8080: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       8081: 	    $request->print(&csvuploadmap($request));
1.246     albertel 8082: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 8083: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 8084: 		$request->print(&csvuploadoptions($request));
1.41      ng       8085: 	    } else {
1.257     albertel 8086: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   8087: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       8088: 		} else {
1.257     albertel 8089: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       8090: 		}
                   8091: 		$request->print(&csvuploadmap($request));
                   8092: 	    }
1.246     albertel 8093: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   8094: 	    $request->print(&csvuploadassign($request));
1.106     albertel 8095: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.447   ! foxr     8096: 	    &Apache::lonnet::logthis("Selecting pyhase");
1.75      albertel 8097: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 8098:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   8099:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 8100: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   8101: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 8102: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 8103: 	    $request->print(&scantron_process_students($request));
1.157     albertel 8104:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 8105:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   8106: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 8107:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 8108:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 8109:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   8110: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 8111:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 8112:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 8113: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 8114:  	    $request->print(&scantron_download_scantron_data($request));
1.106     albertel 8115: 	} elsif ($command) {
1.157     albertel 8116: 	    $request->print("Access Denied ($command)");
1.26      albertel 8117: 	}
1.2       albertel 8118:     }
1.353     albertel 8119:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 8120:     &reset_caches();
1.44      ng       8121:     return '';
                   8122: }
                   8123: 
1.1       albertel 8124: 1;
                   8125: 
1.13      albertel 8126: __END__;

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>