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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.574.2.12! raeburn     4: # $Id: grades.pm,v 1.574.2.11 2010/04/14 16:34:54 raeburn 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: 
1.529     jms        29: 
                     30: 
1.1       albertel   31: package Apache::grades;
                     32: use strict;
                     33: use Apache::style;
                     34: use Apache::lonxml;
                     35: use Apache::lonnet;
1.3       albertel   36: use Apache::loncommon;
1.112     ng         37: use Apache::lonhtmlcommon;
1.68      ng         38: use Apache::lonnavmaps;
1.1       albertel   39: use Apache::lonhomework;
1.456     banghart   40: use Apache::lonpickcode;
1.55      matthew    41: use Apache::loncoursedata;
1.362     albertel   42: use Apache::lonmsg();
1.1       albertel   43: use Apache::Constants qw(:common);
1.167     sakharuk   44: use Apache::lonlocal;
1.386     raeburn    45: use Apache::lonenc;
1.170     albertel   46: use String::Similarity;
1.359     www        47: use LONCAPA;
                     48: 
1.315     bowersj2   49: use POSIX qw(floor);
1.87      www        50: 
1.435     foxr       51: 
1.513     foxr       52: 
1.435     foxr       53: my %perm=();
1.447     foxr       54: 
1.513     foxr       55: #  These variables are used to recover from ssi errors
                     56: 
                     57: my $ssi_retries = 5;
                     58: my $ssi_error;
                     59: my $ssi_error_resource;
                     60: my $ssi_error_message;
                     61: 
                     62: 
                     63: sub ssi_with_retries {
                     64:     my ($resource, $retries, %form) = @_;
                     65:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     66:     if ($response->is_error) {
                     67: 	$ssi_error          = 1;
                     68: 	$ssi_error_resource = $resource;
                     69: 	$ssi_error_message  = $response->code . " " . $response->message;
                     70:     }
                     71: 
                     72:     return $content;
                     73: 
                     74: }
                     75: #
                     76: #  Prodcuces an ssi retry failure error message to the user:
                     77: #
                     78: 
                     79: sub ssi_print_error {
                     80:     my ($r) = @_;
1.516     raeburn    81:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     82:     $r->print('
                     83: <br />
                     84: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     85: <p>
                     86: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     87: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     88: '.&mt('Error:').' '.$ssi_error_message.'
                     89: </p>
                     90: <p>'.
                     91: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
                     92: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                     93: '</p>');
                     94:     return;
1.513     foxr       95: }
                     96: 
1.44      ng         97: #
1.146     albertel   98: # --- Retrieve the parts from the metadata file.---
1.44      ng         99: sub getpartlist {
1.574.2.7  raeburn   100:     my ($symb,$errorref) = @_;
1.439     albertel  101: 
                    102:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.574.2.7  raeburn   103:     unless (ref($navmap)) {
                    104:         if (ref($errorref)) { 
                    105:             $$errorref = 'navmap';
                    106:             return;
                    107:         }
                    108:     }
1.439     albertel  109:     my $res      = $navmap->getBySymb($symb);
                    110:     my $partlist = $res->parts();
                    111:     my $url      = $res->src();
                    112:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    113: 
1.146     albertel  114:     my @stores;
1.439     albertel  115:     foreach my $part (@{ $partlist }) {
1.146     albertel  116: 	foreach my $key (@metakeys) {
                    117: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    118: 	}
                    119:     }
                    120:     return @stores;
1.2       albertel  121: }
                    122: 
1.44      ng        123: # --- Get the symbolic name of a problem and the url
1.324     albertel  124: sub get_symb {
1.173     albertel  125:     my ($request,$silent) = @_;
1.257     albertel  126:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                    127:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
1.173     albertel  128:     if ($symb eq '') { 
                    129: 	if (!$silent) {
                    130: 	    $request->print("Unable to handle ambiguous references:$url:.");
                    131: 	    return ();
                    132: 	}
                    133:     }
1.418     albertel  134:     &Apache::lonenc::check_decrypt(\$symb);
1.324     albertel  135:     return ($symb);
1.32      ng        136: }
                    137: 
1.129     ng        138: #--- Format fullname, username:domain if different for display
                    139: #--- Use anywhere where the student names are listed
                    140: sub nameUserString {
                    141:     my ($type,$fullname,$uname,$udom) = @_;
                    142:     if ($type eq 'header') {
1.485     albertel  143: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        144:     } else {
1.398     albertel  145: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    146: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        147:     }
                    148: }
                    149: 
1.44      ng        150: #--- Get the partlist and the response type for a given problem. ---
                    151: #--- Indicate if a response type is coded handgraded or not. ---
1.39      ng        152: sub response_type {
1.574.2.7  raeburn   153:     my ($symb,$response_error) = @_;
1.377     albertel  154: 
                    155:     my $navmap = Apache::lonnavmaps::navmap->new();
1.574.2.7  raeburn   156:     unless (ref($navmap)) {
                    157:         if (ref($response_error)) {
                    158:             $$response_error = 1;
                    159:         }
                    160:         return;
                    161:     }
1.377     albertel  162:     my $res = $navmap->getBySymb($symb);
                    163:     my $partlist = $res->parts();
1.392     albertel  164:     my %vPart = 
                    165: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  166:     my (%response_types,%handgrade);
                    167:     foreach my $part (@{ $partlist }) {
1.392     albertel  168: 	next if (%vPart && !exists($vPart{$part}));
                    169: 
1.377     albertel  170: 	my @types = $res->responseType($part);
                    171: 	my @ids = $res->responseIds($part);
                    172: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    173: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    174: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    175: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    176: 				     '.handgrade',$symb);
1.41      ng        177: 	}
                    178:     }
1.377     albertel  179:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        180: }
                    181: 
1.375     albertel  182: sub flatten_responseType {
                    183:     my ($responseType) = @_;
                    184:     my @part_response_id =
                    185: 	map { 
                    186: 	    my $part = $_;
                    187: 	    map {
                    188: 		[$part,$_]
                    189: 		} sort(keys(%{ $responseType->{$part} }));
                    190: 	} sort(keys(%$responseType));
                    191:     return @part_response_id;
                    192: }
                    193: 
1.207     albertel  194: sub get_display_part {
1.324     albertel  195:     my ($partID,$symb)=@_;
1.207     albertel  196:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    197:     if (defined($display) and $display ne '') {
1.398     albertel  198: 	$display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
1.207     albertel  199:     } else {
                    200: 	$display=$partID;
                    201:     }
                    202:     return $display;
                    203: }
1.269     raeburn   204: 
1.118     ng        205: #--- Show resource title
                    206: #--- and parts and response type
                    207: sub showResourceInfo {
1.574.2.7  raeburn   208:     my ($symb,$probTitle,$checkboxes,$res_error) = @_;
1.154     albertel  209:     my $col=3;
                    210:     if ($checkboxes) { $col=4; }
1.398     albertel  211:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
1.574.2.7  raeburn   212:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
                    213:     if (ref($res_error)) {
                    214:         if ($$res_error) {
                    215:             return;
                    216:         }
                    217:     }
1.398     albertel  218:     $result .='<table border="0">';
1.126     ng        219:     my %resptype = ();
1.122     ng        220:     my $hdgrade='no';
1.154     albertel  221:     my %partsseen;
1.524     raeburn   222:     foreach my $partID (sort(keys(%$responseType))) {
                    223: 	foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
1.375     albertel  224: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
                    225: 	    my $responsetype = $responseType->{$partID}->{$resID};
                    226: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
                    227: 	    $result.='<tr>';
                    228: 	    if ($checkboxes) {
                    229: 		if (exists($partsseen{$partID})) {
                    230: 		    $result.="<td>&nbsp;</td>";
                    231: 		} else {
1.401     albertel  232: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
1.375     albertel  233: 		}
                    234: 		$partsseen{$partID}=1;
1.154     albertel  235: 	    }
1.375     albertel  236: 	    my $display_part=&get_display_part($partID,$symb);
1.539     riegler   237: 	    $result.='<td><b>'.&mt('Part').': </b>'.$display_part.
                    238:                 ' <span class="LC_internal_info">'.$resID.'</span></td>'.
                    239: 		'<td><b>'.&mt('Type').': </b>'.$responsetype.'</td></tr>';
1.485     albertel  240: #	    '<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td></tr>';
1.154     albertel  241: 	}
1.118     ng        242:     }
                    243:     $result.='</table>'."\n";
1.147     albertel  244:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
1.118     ng        245: }
                    246: 
1.434     albertel  247: sub reset_caches {
                    248:     &reset_analyze_cache();
                    249:     &reset_perm();
                    250: }
                    251: 
                    252: {
                    253:     my %analyze_cache;
1.557     raeburn   254:     my %analyze_cache_formkeys;
1.148     albertel  255: 
1.434     albertel  256:     sub reset_analyze_cache {
                    257: 	undef(%analyze_cache);
1.557     raeburn   258:         undef(%analyze_cache_formkeys);
1.434     albertel  259:     }
                    260: 
                    261:     sub get_analyze {
1.557     raeburn   262: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash)=@_;
1.434     albertel  263: 	my $key = "$symb\0$uname\0$udom";
1.557     raeburn   264: 	if (exists($analyze_cache{$key})) {
                    265:             my $getupdate = 0;
                    266:             if (ref($add_to_hash) eq 'HASH') {
                    267:                 foreach my $item (keys(%{$add_to_hash})) {
                    268:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    269:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    270:                             $getupdate = 1;
                    271:                             last;
                    272:                         }
                    273:                     } else {
                    274:                         $getupdate = 1;
                    275:                     }
                    276:                 }
                    277:             }
                    278:             if (!$getupdate) {
                    279:                 return $analyze_cache{$key};
                    280:             }
                    281:         }
1.434     albertel  282: 
                    283: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    284: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   285:         my %form = ('grade_target'      => 'analyze',
                    286:                     'grade_domain'      => $udom,
                    287:                     'grade_symb'        => $symb,
                    288:                     'grade_courseid'    =>  $env{'request.course.id'},
                    289:                     'grade_username'    => $uname,
                    290:                     'grade_noincrement' => $no_increment);
                    291:         if (ref($add_to_hash)) {
                    292:             %form = (%form,%{$add_to_hash});
                    293:         } 
                    294: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  295: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    296: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   297:         if (ref($add_to_hash) eq 'HASH') {
                    298:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    299:         } else {
                    300:             $analyze_cache_formkeys{$key} = {};
                    301:         }
1.434     albertel  302: 	return $analyze_cache{$key} = \%analyze;
                    303:     }
                    304: 
                    305:     sub get_order {
1.525     raeburn   306: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
                    307: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
1.434     albertel  308: 	return $analyze->{"$partid.$respid.shown"};
                    309:     }
                    310: 
                    311:     sub get_radiobutton_correct_foil {
                    312: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    313: 	my $analyze = &get_analyze($symb,$uname,$udom);
1.555     raeburn   314:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
                    315:         if (ref($foils) eq 'ARRAY') {
                    316: 	    foreach my $foil (@{$foils}) {
                    317: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    318: 		    return $foil;
                    319: 	        }
1.434     albertel  320: 	    }
                    321: 	}
                    322:     }
1.554     raeburn   323: 
                    324:     sub scantron_partids_tograde {
1.557     raeburn   325:         my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
1.554     raeburn   326:         my (%analysis,@parts);
                    327:         if (ref($resource)) {
                    328:             my $symb = $resource->symb();
1.557     raeburn   329:             my $add_to_form;
                    330:             if ($check_for_randomlist) {
                    331:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    332:             }
                    333:             my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
1.554     raeburn   334:             if (ref($analyze) eq 'HASH') {
                    335:                 %analysis = %{$analyze};
                    336:             }
                    337:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    338:                 foreach my $part (@{$analysis{'parts'}}) {
                    339:                     my ($id,$respid) = split(/\./,$part);
                    340:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    341:                         push(@parts,$part);
                    342:                     }
                    343:                 }
                    344:             }
                    345:         }
                    346:         return (\%analysis,\@parts);
                    347:     }
                    348: 
1.148     albertel  349: }
1.434     albertel  350: 
1.118     ng        351: #--- Clean response type for display
1.335     albertel  352: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    353: #        response types only.
1.118     ng        354: sub cleanRecord {
1.336     albertel  355:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
                    356: 	$uname,$udom) = @_;
1.398     albertel  357:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  358:     if ($response =~ /^(option|rank)$/) {
                    359: 	my %answer=&Apache::lonnet::str2hash($answer);
                    360: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    361: 	my ($toprow,$bottomrow);
                    362: 	foreach my $foil (@$order) {
                    363: 	    if ($grading{$foil} == 1) {
                    364: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    365: 	    } else {
                    366: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    367: 	    }
1.398     albertel  368: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  369: 	}
                    370: 	return '<blockquote><table border="1">'.
1.466     albertel  371: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    372: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  373: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    374:     } elsif ($response eq 'match') {
                    375: 	my %answer=&Apache::lonnet::str2hash($answer);
                    376: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    377: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    378: 	my ($toprow,$middlerow,$bottomrow);
                    379: 	foreach my $foil (@$order) {
                    380: 	    my $item=shift(@items);
                    381: 	    if ($grading{$foil} == 1) {
                    382: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  383: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  384: 	    } else {
                    385: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  386: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  387: 	    }
1.398     albertel  388: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        389: 	}
1.126     ng        390: 	return '<blockquote><table border="1">'.
1.466     albertel  391: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    392: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  393: 	    $middlerow.'</tr>'.
1.466     albertel  394: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  395: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    396:     } elsif ($response eq 'radiobutton') {
                    397: 	my %answer=&Apache::lonnet::str2hash($answer);
                    398: 	my ($toprow,$bottomrow);
1.434     albertel  399: 	my $correct = 
                    400: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
                    401: 	foreach my $foil (@$order) {
1.148     albertel  402: 	    if (exists($answer{$foil})) {
1.434     albertel  403: 		if ($foil eq $correct) {
1.466     albertel  404: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  405: 		} else {
1.466     albertel  406: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  407: 		}
                    408: 	    } else {
1.466     albertel  409: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  410: 	    }
1.398     albertel  411: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  412: 	}
                    413: 	return '<blockquote><table border="1">'.
1.466     albertel  414: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    415: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  416: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    417:     } elsif ($response eq 'essay') {
1.257     albertel  418: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        419: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  420: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    421: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        422: 
1.257     albertel  423: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    424: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    425: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    426: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    427: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    428: 	    $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        429: 	}
1.166     albertel  430: 	$answer =~ s-\n-<br />-g;
                    431: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  432:     } elsif ( $response eq 'organic') {
                    433: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    434: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    435: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    436: 	return $result;
1.335     albertel  437:     } elsif ( $response eq 'Task') {
                    438: 	if ( $answer eq 'SUBMITTED') {
                    439: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  440: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  441: 	    return $result;
                    442: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    443: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    444: 			       keys(%{$record}));
                    445: 	    return join('<br />',($version,@matches));
                    446: 			       
                    447: 			       
                    448: 	} else {
                    449: 	    my $result =
                    450: 		'<p>'
                    451: 		.&mt('Overall result: [_1]',
                    452: 		     $record->{$version."resource.$respid.$partid.status"})
                    453: 		.'</p>';
                    454: 	    
                    455: 	    $result .= '<ul>';
                    456: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    457: 			     keys(%{$record}));
                    458: 	    foreach my $grade (sort(@grade)) {
                    459: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    460: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    461: 				     $dim, $record->{$grade}).
                    462: 			  '</li>';
                    463: 	    }
                    464: 	    $result.='</ul>';
                    465: 	    return $result;
                    466: 	}
1.440     albertel  467:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    468: 	$answer = 
                    469: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    470: 							      $answer);
1.122     ng        471:     }
1.118     ng        472:     return $answer;
                    473: }
                    474: 
                    475: #-- A couple of common js functions
                    476: sub commonJSfunctions {
                    477:     my $request = shift;
                    478:     $request->print(<<COMMONJSFUNCTIONS);
                    479: <script type="text/javascript" language="javascript">
                    480:     function radioSelection(radioButton) {
                    481: 	var selection=null;
                    482: 	if (radioButton.length > 1) {
                    483: 	    for (var i=0; i<radioButton.length; i++) {
                    484: 		if (radioButton[i].checked) {
                    485: 		    return radioButton[i].value;
                    486: 		}
                    487: 	    }
                    488: 	} else {
                    489: 	    if (radioButton.checked) return radioButton.value;
                    490: 	}
                    491: 	return selection;
                    492:     }
                    493: 
                    494:     function pullDownSelection(selectOne) {
                    495: 	var selection="";
                    496: 	if (selectOne.length > 1) {
                    497: 	    for (var i=0; i<selectOne.length; i++) {
                    498: 		if (selectOne[i].selected) {
                    499: 		    return selectOne[i].value;
                    500: 		}
                    501: 	    }
                    502: 	} else {
1.138     albertel  503:             // only one value it must be the selected one
                    504: 	    return selectOne.value;
1.118     ng        505: 	}
                    506:     }
                    507: </script>
                    508: COMMONJSFUNCTIONS
                    509: }
                    510: 
1.44      ng        511: #--- Dumps the class list with usernames,list of sections,
                    512: #--- section, ids and fullnames for each user.
                    513: sub getclasslist {
1.449     banghart  514:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  515:     my @getsec;
1.450     banghart  516:     my @getgroup;
1.442     banghart  517:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  518:     if (!ref($getsec)) {
                    519: 	if ($getsec ne '' && $getsec ne 'all') {
                    520: 	    @getsec=($getsec);
                    521: 	}
                    522:     } else {
                    523: 	@getsec=@{$getsec};
                    524:     }
                    525:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  526:     if (!ref($getgroup)) {
                    527: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    528: 	    @getgroup=($getgroup);
                    529: 	}
                    530:     } else {
                    531: 	@getgroup=@{$getgroup};
                    532:     }
                    533:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  534: 
1.449     banghart  535:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  536:     # Bail out if we were unable to get the classlist
1.56      matthew   537:     return if (! defined($classlist));
1.449     banghart  538:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   539:     #
                    540:     my %sections;
                    541:     my %fullnames;
1.205     matthew   542:     foreach my $student (keys(%$classlist)) {
                    543:         my $end      = 
                    544:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    545:         my $start    = 
                    546:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    547:         my $id       = 
                    548:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    549:         my $section  = 
                    550:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    551:         my $fullname = 
                    552:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    553:         my $status   = 
                    554:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  555:         my $group   = 
                    556:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        557: 	# filter students according to status selected
1.442     banghart  558: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    559: 	    if (!($stu_status =~ $status)) {
1.450     banghart  560: 		delete($classlist->{$student});
1.76      ng        561: 		next;
                    562: 	    }
                    563: 	}
1.450     banghart  564: 	# filter students according to groups selected
1.453     banghart  565: 	my @stu_groups = split(/,/,$group);
1.450     banghart  566: 	if (@getgroup) {
                    567: 	    my $exclude = 1;
1.454     banghart  568: 	    foreach my $grp (@getgroup) {
                    569: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  570: 	            if ($stu_group eq $grp) {
                    571: 	                $exclude = 0;
                    572:     	            } 
1.450     banghart  573: 	        }
1.453     banghart  574:     	        if (($grp eq 'none') && !$group) {
                    575:         	        $exclude = 0;
                    576:         	}
1.450     banghart  577: 	    }
                    578: 	    if ($exclude) {
                    579: 	        delete($classlist->{$student});
                    580: 	    }
                    581: 	}
1.205     matthew   582: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  583: 	if (&canview($section)) {
1.291     albertel  584: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  585: 		$sections{$section}++;
1.450     banghart  586: 		if ($classlist->{$student}) {
                    587: 		    $fullnames{$student}=$fullname;
                    588: 		}
1.103     albertel  589: 	    } else {
1.205     matthew   590: 		delete($classlist->{$student});
1.103     albertel  591: 	    }
                    592: 	} else {
1.205     matthew   593: 	    delete($classlist->{$student});
1.103     albertel  594: 	}
1.44      ng        595:     }
                    596:     my %seen = ();
1.56      matthew   597:     my @sections = sort(keys(%sections));
                    598:     return ($classlist,\@sections,\%fullnames);
1.44      ng        599: }
                    600: 
1.103     albertel  601: sub canmodify {
                    602:     my ($sec)=@_;
                    603:     if ($perm{'mgr'}) {
                    604: 	if (!defined($perm{'mgr_section'})) {
                    605: 	    # can modify whole class
                    606: 	    return 1;
                    607: 	} else {
                    608: 	    if ($sec eq $perm{'mgr_section'}) {
                    609: 		#can modify the requested section
                    610: 		return 1;
                    611: 	    } else {
                    612: 		# can't modify the request section
                    613: 		return 0;
                    614: 	    }
                    615: 	}
                    616:     }
                    617:     #can't modify
                    618:     return 0;
                    619: }
                    620: 
                    621: sub canview {
                    622:     my ($sec)=@_;
                    623:     if ($perm{'vgr'}) {
                    624: 	if (!defined($perm{'vgr_section'})) {
                    625: 	    # can modify whole class
                    626: 	    return 1;
                    627: 	} else {
                    628: 	    if ($sec eq $perm{'vgr_section'}) {
                    629: 		#can modify the requested section
                    630: 		return 1;
                    631: 	    } else {
                    632: 		# can't modify the request section
                    633: 		return 0;
                    634: 	    }
                    635: 	}
                    636:     }
                    637:     #can't modify
                    638:     return 0;
                    639: }
                    640: 
1.44      ng        641: #--- Retrieve the grade status of a student for all the parts
                    642: sub student_gradeStatus {
1.324     albertel  643:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  644:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        645:     my %partstatus = ();
                    646:     foreach (@$partlist) {
1.128     ng        647: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        648: 	$status              = 'nothing' if ($status eq '');
                    649: 	$partstatus{$_}      = $status;
                    650: 	my $subkey           = "resource.$_.submitted_by";
                    651: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    652:     }
                    653:     return %partstatus;
                    654: }
                    655: 
1.45      ng        656: # hidden form and javascript that calls the form
                    657: # Use by verifyscript and viewgrades
                    658: # Shows a student's view of problem and submission
                    659: sub jscriptNform {
1.324     albertel  660:     my ($symb) = @_;
1.442     banghart  661:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.45      ng        662:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
                    663: 	'    function viewOneStudent(user,domain) {'."\n".
                    664: 	'	document.onestudent.student.value = user;'."\n".
                    665: 	'	document.onestudent.userdom.value = domain;'."\n".
                    666: 	'	document.onestudent.submit();'."\n".
                    667: 	'    }'."\n".
                    668: 	'</script>'."\n";
                    669:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  670: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  671: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    672: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1.442     banghart  673: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        674: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    675: 	'<input type="hidden" name="student" value="" />'."\n".
                    676: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    677: 	'</form>'."\n";
                    678:     return $jscript;
                    679: }
1.39      ng        680: 
1.447     foxr      681: 
                    682: 
1.315     bowersj2  683: # Given the score (as a number [0-1] and the weight) what is the final
                    684: # point value? This function will round to the nearest tenth, third,
                    685: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  686: sub compute_points {
1.315     bowersj2  687:     my ($score, $weight) = @_;
                    688:     
                    689:     my $tolerance = .00001;
                    690:     my $points = $score * $weight;
                    691: 
                    692:     # Check for nearness to 1/x.
                    693:     my $check_for_nearness = sub {
                    694:         my ($factor) = @_;
                    695:         my $num = ($points * $factor) + $tolerance;
                    696:         my $floored_num = floor($num);
1.316     albertel  697:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  698:             return $floored_num / $factor;
                    699:         }
                    700:         return $points;
                    701:     };
                    702: 
                    703:     $points = $check_for_nearness->(10);
                    704:     $points = $check_for_nearness->(3);
                    705:     $points = $check_for_nearness->(4);
                    706:     
                    707:     return $points;
                    708: }
                    709: 
1.44      ng        710: #------------------ End of general use routines --------------------
1.87      www       711: 
                    712: #
                    713: # Find most similar essay
                    714: #
                    715: 
                    716: sub most_similar {
1.426     albertel  717:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       718: 
                    719: # ignore spaces and punctuation
                    720: 
                    721:     $uessay=~s/\W+/ /gs;
                    722: 
1.282     www       723: # ignore empty submissions (occuring when only files are sent)
                    724: 
                    725:     unless ($uessay=~/\w+/) { return ''; }
                    726: 
1.87      www       727: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       728:     my $limit=0.6;
1.87      www       729:     my $sname='';
                    730:     my $sdom='';
                    731:     my $scrsid='';
                    732:     my $sessay='';
                    733: # go through all essays ...
1.426     albertel  734:     foreach my $tkey (keys(%$old_essays)) {
                    735: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       736: # ... except the same student
1.426     albertel  737:         next if (($tname eq $uname) && ($tdom eq $udom));
                    738: 	my $tessay=$old_essays->{$tkey};
                    739: 	$tessay=~s/\W+/ /gs;
1.87      www       740: # String similarity gives up if not even limit
1.426     albertel  741: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       742: # Found one
1.426     albertel  743: 	if ($tsimilar>$limit) {
                    744: 	    $limit=$tsimilar;
                    745: 	    $sname=$tname;
                    746: 	    $sdom=$tdom;
                    747: 	    $scrsid=$tcrsid;
                    748: 	    $sessay=$old_essays->{$tkey};
                    749: 	}
1.87      www       750:     }
1.88      www       751:     if ($limit>0.6) {
1.87      www       752:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    753:     } else {
                    754:        return ('','','','',0);
                    755:     }
                    756: }
                    757: 
1.44      ng        758: #-------------------------------------------------------------------
                    759: 
                    760: #------------------------------------ Receipt Verification Routines
1.45      ng        761: #
1.44      ng        762: #--- Check whether a receipt number is valid.---
                    763: sub verifyreceipt {
                    764:     my $request  = shift;
                    765: 
1.257     albertel  766:     my $courseid = $env{'request.course.id'};
1.184     www       767:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  768: 	$env{'form.receipt'};
1.44      ng        769:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  770:     my ($symb)   = &get_symb($request);
1.44      ng        771: 
1.487     albertel  772:     my $title.=
                    773: 	'<h3><span class="LC_info">'.
1.574.2.10  raeburn   774: 	&mt('Verifying Receipt No. [_1]',$receipt).
1.487     albertel  775: 	'</span></h3>'."\n".
                    776: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
                    777: 	'</h4>'."\n";
1.44      ng        778: 
                    779:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   780:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  781:     
                    782:     my $receiptparts=0;
1.390     albertel  783:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    784: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  785:     my $parts=['0'];
1.574.2.7  raeburn   786:     if ($receiptparts) {
                    787:         my $res_error; 
                    788:         ($parts)=&response_type($symb,\$res_error);
                    789:         if ($res_error) {
                    790:             return &navmap_errormsg();
                    791:         } 
                    792:     }
1.486     albertel  793:     
                    794:     my $header = 
                    795: 	&Apache::loncommon::start_data_table().
                    796: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  797: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    798: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    799: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  800:     if ($receiptparts) {
1.487     albertel  801: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  802:     }
                    803:     $header.=
                    804: 	&Apache::loncommon::end_data_table_header_row();
                    805: 
1.294     albertel  806:     foreach (sort 
                    807: 	     {
                    808: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    809: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    810: 		 }
                    811: 		 return $a cmp $b;
                    812: 	     } (keys(%$fullname))) {
1.44      ng        813: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  814: 	foreach my $part (@$parts) {
                    815: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  816: 		$contents.=
                    817: 		    &Apache::loncommon::start_data_table_row().
                    818: 		    '<td>&nbsp;'."\n".
1.177     albertel  819: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  820: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  821: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    822: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    823: 		if ($receiptparts) {
                    824: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    825: 		}
1.486     albertel  826: 		$contents.= 
                    827: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  828: 		
                    829: 		$matches++;
                    830: 	    }
1.44      ng        831: 	}
                    832:     }
                    833:     if ($matches == 0) {
1.574.2.10  raeburn   834: 	$string = $title.&mt('No match found for the above receipt number.');
1.44      ng        835:     } else {
1.324     albertel  836: 	$string = &jscriptNform($symb).$title.
1.487     albertel  837: 	    '<p>'.
1.574.2.10  raeburn   838: 	    &mt('The above receipt number matches the following [numerate,_1,student].',$matches).
1.487     albertel  839: 	    '</p>'.
1.486     albertel  840: 	    $header.
                    841: 	    $contents.
                    842: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        843:     }
1.324     albertel  844:     return $string.&show_grading_menu_form($symb);
1.44      ng        845: }
                    846: 
                    847: #--- This is called by a number of programs.
                    848: #--- Called from the Grading Menu - View/Grade an individual student
                    849: #--- Also called directly when one clicks on the subm button 
                    850: #    on the problem page.
1.30      ng        851: sub listStudents {
1.41      ng        852:     my ($request) = shift;
1.49      albertel  853: 
1.324     albertel  854:     my ($symb) = &get_symb($request);
1.257     albertel  855:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    856:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    857:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  858:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.257     albertel  859:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
1.548     bisitz    860:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
1.257     albertel  861:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    862: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  863: 
1.548     bisitz    864:     my $result='<h3><span class="LC_info">&nbsp;'
                    865: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
1.485     albertel  866: 	.'</span></h3>';
1.118     ng        867: 
1.324     albertel  868:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  869: 
1.559     raeburn   870:     my %lt = &Apache::lonlocal::texthash (
                    871: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    872: 		'single'   => 'Please select the student before clicking on the Next button.',
                    873: 	     );
1.45      ng        874:     $request->print(<<LISTJAVASCRIPT);
                    875: <script type="text/javascript" language="javascript">
1.110     ng        876:     function checkSelect(checkBox) {
                    877: 	var ctr=0;
                    878: 	var sense="";
                    879: 	if (checkBox.length > 1) {
                    880: 	    for (var i=0; i<checkBox.length; i++) {
                    881: 		if (checkBox[i].checked) {
                    882: 		    ctr++;
                    883: 		}
                    884: 	    }
1.485     albertel  885: 	    sense = '$lt{'multiple'}';
1.110     ng        886: 	} else {
                    887: 	    if (checkBox.checked) {
                    888: 		ctr = 1;
                    889: 	    }
1.485     albertel  890: 	    sense = '$lt{'single'}';
1.110     ng        891: 	}
                    892: 	if (ctr == 0) {
1.485     albertel  893: 	    alert(sense);
1.110     ng        894: 	    return false;
                    895: 	}
                    896: 	document.gradesub.submit();
                    897:     }
                    898: 
                    899:     function reLoadList(formname) {
1.112     ng        900: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        901: 	formname.command.value = 'submission';
                    902: 	formname.submit();
                    903:     }
1.45      ng        904: </script>
                    905: LISTJAVASCRIPT
                    906: 
1.118     ng        907:     &commonJSfunctions($request);
1.41      ng        908:     $request->print($result);
1.39      ng        909: 
1.401     albertel  910:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    911:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  912:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.485     albertel  913: 	"\n".$table;
                    914: 	
1.561     bisitz    915:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    916:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    917:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    918:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    919:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    920:                   .&Apache::lonhtmlcommon::row_closure();
                    921:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    922:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    923:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    924:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    925:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  926: 
                    927:     my $submission_options;
1.257     albertel  928:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.485     albertel  929: 	$submission_options.=
                    930: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
1.49      albertel  931:     }
1.442     banghart  932:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    933:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  934:     $env{'form.Status'} = $saveStatus;
1.485     albertel  935:     $submission_options.=
                    936: 	'<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.&mt('last submission only').' </label>'."\n".
                    937: 	'<label><input type="radio" name="lastSub" value="last" /> '.&mt('last submission &amp; parts info').' </label>'."\n".
                    938: 	'<label><input type="radio" name="lastSub" value="datesub" /> '.&mt('by dates and submissions').' </label>'."\n".
                    939: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').'</label>';
1.561     bisitz    940:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
                    941:                   .$submission_options
                    942:                   .&Apache::lonhtmlcommon::row_closure();
                    943: 
                    944:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                    945:                   .'<select name="increment">'
                    946:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                    947:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                    948:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                    949:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                    950:                   .'</select>'
                    951:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  952: 
                    953:     $gradeTable .= 
1.432     banghart  954:         &build_section_inputs().
1.45      ng        955: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  956: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    957: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    958: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    959: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel  960: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        961: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    962: 
1.257     albertel  963:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.561     bisitz    964: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng        965:     } else {
1.561     bisitz    966:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                    967:                       .&Apache::lonhtmlcommon::StatusOptions(
                    968:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                    969:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng        970:     }
1.112     ng        971: 
1.561     bisitz    972:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                    973:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                    974:                   .&Apache::lonhtmlcommon::row_closure(1)
                    975:                   .&Apache::lonhtmlcommon::end_pick_box();
                    976: 
                    977:     $gradeTable .= '<p>'
                    978:                   .&mt('To '.lc($viewgrade)." a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.")."\n"
                    979:                   .'<input type="hidden" name="command" value="processGroup" />'
                    980:                   .'</p>';
1.249     albertel  981: 
                    982: # checkall buttons
                    983:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        984:     $gradeTable.='<input type="button" '."\n".
1.45      ng        985: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1.539     riegler   986: 	'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel  987:     $gradeTable.=&check_buttons();
1.450     banghart  988:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  989:     $gradeTable.= &Apache::loncommon::start_data_table().
                    990: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        991:     my $loop = 0;
                    992:     while ($loop < 2) {
1.485     albertel  993: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    994: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.301     albertel  995: 	if ($env{'form.showgrading'} eq 'yes' 
                    996: 	    && $submitonly ne 'queued'
                    997: 	    && $submitonly ne 'all') {
1.485     albertel  998: 	    foreach my $part (sort(@$partlist)) {
                    999: 		my $display_part=
                   1000: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   1001: 		$gradeTable.=
                   1002: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       1003: 	    }
1.301     albertel 1004: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 1005: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       1006: 	}
                   1007: 	$loop++;
1.126     ng       1008: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       1009:     }
1.474     albertel 1010:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       1011: 
1.45      ng       1012:     my $ctr = 0;
1.294     albertel 1013:     foreach my $student (sort 
                   1014: 			 {
                   1015: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1016: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1017: 			     }
                   1018: 			     return $a cmp $b;
                   1019: 			 }
                   1020: 			 (keys(%$fullname))) {
1.41      ng       1021: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1022: 
1.110     ng       1023: 	my %status = ();
1.301     albertel 1024: 
                   1025: 	if ($submitonly eq 'queued') {
                   1026: 	    my %queue_status = 
                   1027: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1028: 							$udom,$uname);
                   1029: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1030: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1031: 	}
                   1032: 
                   1033: 	if ($env{'form.showgrading'} eq 'yes' 
                   1034: 	    && $submitonly ne 'queued'
                   1035: 	    && $submitonly ne 'all') {
1.324     albertel 1036: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1037: 	    my $submitted = 0;
1.164     albertel 1038: 	    my $graded = 0;
1.248     albertel 1039: 	    my $incorrect = 0;
1.110     ng       1040: 	    foreach (keys(%status)) {
1.145     albertel 1041: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1042: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1043: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1044: 		
1.110     ng       1045: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1046: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1047: 		    $submitted = 0;
1.150     albertel 1048: 		    my ($part)=split(/\./,$partid);
1.110     ng       1049: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1050: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1051: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1052: 		}
1.41      ng       1053: 	    }
1.248     albertel 1054: 	    
1.156     albertel 1055: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1056: 				     $submitonly eq 'incorrect' ||
                   1057: 				     $submitonly eq 'graded'));
1.248     albertel 1058: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1059: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1060: 	}
1.34      ng       1061: 
1.45      ng       1062: 	$ctr++;
1.249     albertel 1063: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1064:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1065: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1066: 	    if ($ctr%2 ==1) {
                   1067: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1068: 	    }
1.126     ng       1069: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1070:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1071:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1072: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1073: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1074: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1075: 
1.257     albertel 1076: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.524     raeburn  1077: 		foreach (sort(keys(%status))) {
1.485     albertel 1078: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1079: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1080: 		}
1.41      ng       1081: 	    }
1.126     ng       1082: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1083: 	    if ($ctr%2 ==0) {
                   1084: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1085: 	    }
1.41      ng       1086: 	}
                   1087:     }
1.110     ng       1088:     if ($ctr%2 ==1) {
1.126     ng       1089: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel 1090: 	    if ($env{'form.showgrading'} eq 'yes' 
                   1091: 		&& $submitonly ne 'queued'
                   1092: 		&& $submitonly ne 'all') {
1.110     ng       1093: 		foreach (@$partlist) {
                   1094: 		    $gradeTable.='<td>&nbsp;</td>';
                   1095: 		}
1.301     albertel 1096: 	    } elsif ($submitonly eq 'queued') {
                   1097: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1098: 	    }
1.474     albertel 1099: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1100:     }
                   1101: 
1.474     albertel 1102:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.45      ng       1103: 	'<input type="button" '.
                   1104: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1.539     riegler  1105: 	'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1106:     if ($ctr == 0) {
1.96      albertel 1107: 	my $num_students=(scalar(keys(%$fullname)));
                   1108: 	if ($num_students eq 0) {
1.485     albertel 1109: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1110: 	} else {
1.171     albertel 1111: 	    my $submissions='submissions';
                   1112: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1113: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1114: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1115: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485     albertel 1116: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
                   1117: 		    $num_students).
                   1118: 		'</span><br />';
1.96      albertel 1119: 	}
1.46      ng       1120:     } elsif ($ctr == 1) {
1.474     albertel 1121: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1122:     }
1.324     albertel 1123:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1124:     $request->print($gradeTable);
1.44      ng       1125:     return '';
1.10      ng       1126: }
                   1127: 
1.44      ng       1128: #---- Called from the listStudents routine
1.249     albertel 1129: 
                   1130: sub check_script {
                   1131:     my ($form, $type)=@_;
                   1132:     my $chkallscript='<script type="text/javascript">
                   1133:     function checkall() {
                   1134:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1135:             ele = document.forms.'.$form.'.elements[i];
                   1136:             if (ele.name == "'.$type.'") {
                   1137:             document.forms.'.$form.'.elements[i].checked=true;
                   1138:                                        }
                   1139:         }
                   1140:     }
                   1141: 
                   1142:     function checksec() {
                   1143:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1144:             ele = document.forms.'.$form.'.elements[i];
                   1145:            string = document.forms.'.$form.'.chksec.value;
                   1146:            if
                   1147:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1148:               document.forms.'.$form.'.elements[i].checked=true;
                   1149:             }
                   1150:         }
                   1151:     }
                   1152: 
                   1153: 
                   1154:     function uncheckall() {
                   1155:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1156:             ele = document.forms.'.$form.'.elements[i];
                   1157:             if (ele.name == "'.$type.'") {
                   1158:             document.forms.'.$form.'.elements[i].checked=false;
                   1159:                                        }
                   1160:         }
                   1161:     }
                   1162: 
                   1163: </script>'."\n";
                   1164:     return $chkallscript;
                   1165: }
                   1166: 
                   1167: sub check_buttons {
1.485     albertel 1168:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1169:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1170:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1171:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1172:     return $buttons;
                   1173: }
                   1174: 
1.44      ng       1175: #     Displays the submissions for one student or a group of students
1.34      ng       1176: sub processGroup {
1.41      ng       1177:     my ($request)  = shift;
                   1178:     my $ctr        = 0;
1.155     albertel 1179:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1180:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1181: 
1.396     banghart 1182:     foreach my $student (@stuchecked) {
                   1183: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1184: 	$env{'form.student'}        = $uname;
                   1185: 	$env{'form.userdom'}        = $udom;
                   1186: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1187: 	&submission($request,$ctr,$total);
                   1188: 	$ctr++;
                   1189:     }
                   1190:     return '';
1.35      ng       1191: }
1.34      ng       1192: 
1.44      ng       1193: #------------------------------------------------------------------------------------
                   1194: #
                   1195: #-------------------------- Next few routines handles grading by student, essentially
                   1196: #                           handles essay response type problem/part
                   1197: #
                   1198: #--- Javascript to handle the submission page functionality ---
                   1199: sub sub_page_js {
                   1200:     my $request = shift;
1.539     riegler  1201: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.44      ng       1202:     $request->print(<<SUBJAVASCRIPT);
                   1203: <script type="text/javascript" language="javascript">
1.71      ng       1204:     function updateRadio(formname,id,weight) {
1.125     ng       1205: 	var gradeBox = formname["GD_BOX"+id];
                   1206: 	var radioButton = formname["RADVAL"+id];
                   1207: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1208: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1209: 	gradeBox.value = pts;
                   1210: 	var resetbox = false;
                   1211: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1212: 	    alert("$alertmsg"+pts);
1.71      ng       1213: 	    for (var i=0; i<radioButton.length; i++) {
                   1214: 		if (radioButton[i].checked) {
                   1215: 		    gradeBox.value = i;
                   1216: 		    resetbox = true;
                   1217: 		}
                   1218: 	    }
                   1219: 	    if (!resetbox) {
                   1220: 		formtextbox.value = "";
                   1221: 	    }
                   1222: 	    return;
1.44      ng       1223: 	}
1.71      ng       1224: 
                   1225: 	if (pts > weight) {
                   1226: 	    var resp = confirm("You entered a value ("+pts+
                   1227: 			       ") greater than the weight for the part. Accept?");
                   1228: 	    if (resp == false) {
1.125     ng       1229: 		gradeBox.value = oldpts;
1.71      ng       1230: 		return;
                   1231: 	    }
1.44      ng       1232: 	}
1.13      albertel 1233: 
1.71      ng       1234: 	for (var i=0; i<radioButton.length; i++) {
                   1235: 	    radioButton[i].checked=false;
                   1236: 	    if (pts == i && pts != "") {
                   1237: 		radioButton[i].checked=true;
                   1238: 	    }
                   1239: 	}
                   1240: 	updateSelect(formname,id);
1.125     ng       1241: 	formname["stores"+id].value = "0";
1.41      ng       1242:     }
1.5       albertel 1243: 
1.72      ng       1244:     function writeBox(formname,id,pts) {
1.125     ng       1245: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1246: 	if (checkSolved(formname,id) == 'update') {
                   1247: 	    gradeBox.value = pts;
                   1248: 	} else {
1.125     ng       1249: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1250: 	    gradeBox.value = oldpts;
1.125     ng       1251: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1252: 	    for (var i=0; i<radioButton.length; i++) {
                   1253: 		radioButton[i].checked=false;
1.72      ng       1254: 		if (i == oldpts) {
1.71      ng       1255: 		    radioButton[i].checked=true;
                   1256: 		}
                   1257: 	    }
1.41      ng       1258: 	}
1.125     ng       1259: 	formname["stores"+id].value = "0";
1.71      ng       1260: 	updateSelect(formname,id);
                   1261: 	return;
1.41      ng       1262:     }
1.44      ng       1263: 
1.71      ng       1264:     function clearRadBox(formname,id) {
                   1265: 	if (checkSolved(formname,id) == 'noupdate') {
                   1266: 	    updateSelect(formname,id);
                   1267: 	    return;
                   1268: 	}
1.125     ng       1269: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1270: 	for (var i=0; i<gradeSelect.length; i++) {
                   1271: 	    if (gradeSelect[i].selected) {
                   1272: 		var selectx=i;
                   1273: 	    }
                   1274: 	}
1.125     ng       1275: 	var stores = formname["stores"+id];
1.71      ng       1276: 	if (selectx == stores.value) { return };
1.125     ng       1277: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1278: 	gradeBox.value = "";
1.125     ng       1279: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1280: 	for (var i=0; i<radioButton.length; i++) {
                   1281: 	    radioButton[i].checked=false;
                   1282: 	}
                   1283: 	stores.value = selectx;
                   1284:     }
1.5       albertel 1285: 
1.71      ng       1286:     function checkSolved(formname,id) {
1.125     ng       1287: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1288: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1289: 	    if (!reply) {return "noupdate";}
1.120     ng       1290: 	    formname.overRideScore.value = 'yes';
1.41      ng       1291: 	}
1.71      ng       1292: 	return "update";
1.13      albertel 1293:     }
1.71      ng       1294: 
                   1295:     function updateSelect(formname,id) {
1.125     ng       1296: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1297: 	return;
1.41      ng       1298:     }
1.33      ng       1299: 
1.121     ng       1300: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1301:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1302: 	formname.gradeOpt.value = val;
1.71      ng       1303: 	if (val == "Save & Next") {
                   1304: 	    for (i=0;i<=total;i++) {
                   1305: 		for (j=0;j<parttot;j++) {
1.125     ng       1306: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1307: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1308: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1309: 			if (points == "") {
1.125     ng       1310: 			    var name = formname["name"+i].value;
1.129     ng       1311: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1312: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1313: 					       ", part "+partid+". Continue?");
1.71      ng       1314: 			    if (resp == false) {
1.125     ng       1315: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1316: 				return false;
                   1317: 			    }
                   1318: 			}
                   1319: 		    }
                   1320: 		    
                   1321: 		}
                   1322: 	    }
                   1323: 	    
                   1324: 	}
1.121     ng       1325: 	if (val == "Grade Student") {
                   1326: 	    formname.showgrading.value = "yes";
                   1327: 	    if (formname.Status.value == "") {
                   1328: 		formname.Status.value = "Active";
                   1329: 	    }
                   1330: 	    formname.studentNo.value = total;
                   1331: 	}
1.120     ng       1332: 	formname.submit();
                   1333:     }
                   1334: 
1.71      ng       1335: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1336:     function checkSubmitPage(formname,total) {
                   1337: 	noscore = new Array(100);
                   1338: 	var ptr = 0;
                   1339: 	for (i=1;i<total;i++) {
1.125     ng       1340: 	    var partid = formname["q_"+i].value;
1.127     ng       1341: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1342: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1343: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1344: 		if (points == "" && status != "correct_by_student") {
                   1345: 		    noscore[ptr] = i;
                   1346: 		    ptr++;
                   1347: 		}
                   1348: 	    }
                   1349: 	}
                   1350: 	if (ptr != 0) {
                   1351: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1352: 	    var prolist = "";
                   1353: 	    if (ptr == 1) {
                   1354: 		prolist = noscore[0];
                   1355: 	    } else {
                   1356: 		var i = 0;
                   1357: 		while (i < ptr-1) {
                   1358: 		    prolist += noscore[i]+", ";
                   1359: 		    i++;
                   1360: 		}
                   1361: 		prolist += "and "+noscore[i];
                   1362: 	    }
                   1363: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1364: 	    if (resp == false) {
                   1365: 		return false;
                   1366: 	    }
                   1367: 	}
1.45      ng       1368: 
1.71      ng       1369: 	formname.submit();
                   1370:     }
                   1371: </script>
                   1372: SUBJAVASCRIPT
                   1373: }
1.45      ng       1374: 
1.71      ng       1375: #--- javascript for essay type problem --
                   1376: sub sub_page_kw_js {
                   1377:     my $request = shift;
1.80      ng       1378:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1379:     &commonJSfunctions($request);
1.350     albertel 1380: 
1.351     albertel 1381:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1382:     <script text="text/javascript">
                   1383:     function checkInput() {
                   1384:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1385:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1386:       var usrctr = document.msgcenter.usrctr.value;
                   1387:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1388:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1389: 
                   1390:       var msgchk = "";
                   1391:       if (document.msgcenter.subchk.checked) {
                   1392:          msgchk = "msgsub,";
                   1393:       }
                   1394:       var includemsg = 0;
                   1395:       for (var i=1; i<=nmsg; i++) {
                   1396:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1397:           var frmmsg = document.msgcenter["msg"+i];
                   1398:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1399:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1400:           showflg.value = "1";
                   1401:           var chkbox = document.msgcenter["msgn"+i];
                   1402:           if (chkbox.checked) {
                   1403:              msgchk += "savemsg"+i+",";
                   1404:              includemsg = 1;
                   1405:           }
                   1406:       }
                   1407:       if (document.msgcenter.newmsgchk.checked) {
                   1408:          msgchk += "newmsg"+usrctr;
                   1409:          includemsg = 1;
                   1410:       }
                   1411:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1412:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1413:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1414:       includemsg.value = msgchk;
                   1415: 
                   1416:       self.close()
                   1417: 
                   1418:     }
                   1419:     </script>
                   1420: INNERJS
                   1421: 
1.351     albertel 1422:     my $inner_js_highlight_central=<<INNERJS;
                   1423:  <script type="text/javascript">
                   1424:     function updateChoice(flag) {
                   1425:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1426:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1427:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1428:       opener.document.SCORE.refresh.value = "on";
                   1429:       if (opener.document.SCORE.keywords.value!=""){
                   1430:          opener.document.SCORE.submit();
                   1431:       }
                   1432:       self.close()
                   1433:     }
                   1434: </script>
                   1435: INNERJS
                   1436: 
                   1437:     my $start_page_msg_central = 
                   1438:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1439: 				       {'js_ready'  => 1,
                   1440: 					'only_body' => 1,
                   1441: 					'bgcolor'   =>'#FFFFFF',});
                   1442:     my $end_page_msg_central = 
                   1443: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1444: 
                   1445: 
                   1446:     my $start_page_highlight_central = 
                   1447:         &Apache::loncommon::start_page('Highlight Central',
                   1448: 				       $inner_js_highlight_central,
1.350     albertel 1449: 				       {'js_ready'  => 1,
                   1450: 					'only_body' => 1,
                   1451: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1452:     my $end_page_highlight_central = 
1.350     albertel 1453: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1454: 
1.219     www      1455:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1456:     $docopen=~s/^document\.//;
1.539     riegler  1457:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
1.71      ng       1458:     $request->print(<<SUBJAVASCRIPT);
                   1459: <script type="text/javascript" language="javascript">
1.45      ng       1460: 
1.44      ng       1461: //===================== Show list of keywords ====================
1.122     ng       1462:   function keywords(formname) {
                   1463:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1464:     if (nret==null) return;
1.122     ng       1465:     formname.keywords.value = nret;
1.44      ng       1466: 
1.122     ng       1467:     if (formname.keywords.value != "") {
1.128     ng       1468: 	formname.refresh.value = "on";
1.122     ng       1469: 	formname.submit();
1.44      ng       1470:     }
                   1471:     return;
                   1472:   }
                   1473: 
                   1474: //===================== Script to view submitted by ==================
                   1475:   function viewSubmitter(submitter) {
                   1476:     document.SCORE.refresh.value = "on";
                   1477:     document.SCORE.NCT.value = "1";
                   1478:     document.SCORE.unamedom0.value = submitter;
                   1479:     document.SCORE.submit();
                   1480:     return;
                   1481:   }
                   1482: 
                   1483: //===================== Script to add keyword(s) ==================
                   1484:   function getSel() {
                   1485:     if (document.getSelection) txt = document.getSelection();
                   1486:     else if (document.selection) txt = document.selection.createRange().text;
                   1487:     else return;
                   1488:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1489:     if (cleantxt=="") {
1.539     riegler  1490: 	alert("$alertmsg");
1.44      ng       1491: 	return;
                   1492:     }
                   1493:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1494:     if (nret==null) return;
1.127     ng       1495:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1496:     if (document.SCORE.keywords.value != "") {
1.127     ng       1497: 	document.SCORE.refresh.value = "on";
1.44      ng       1498: 	document.SCORE.submit();
                   1499:     }
                   1500:     return;
                   1501:   }
                   1502: 
                   1503: //====================== Script for composing message ==============
1.80      ng       1504:    // preload images
                   1505:    img1 = new Image();
                   1506:    img1.src = "$iconpath/mailbkgrd.gif";
                   1507:    img2 = new Image();
                   1508:    img2.src = "$iconpath/mailto.gif";
                   1509: 
1.44      ng       1510:   function msgCenter(msgform,usrctr,fullname) {
                   1511:     var Nmsg  = msgform.savemsgN.value;
                   1512:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1513:     var subject = msgform.msgsub.value;
1.127     ng       1514:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1515:     re = /msgsub/;
                   1516:     var shwsel = "";
                   1517:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1518:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1519:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1520:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1521: 	var testmsg = "savemsg"+i+",";
                   1522: 	re = new RegExp(testmsg,"g");
1.44      ng       1523: 	shwsel = "";
                   1524: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1525: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1526: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1527: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1528: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1529:     }
1.125     ng       1530:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1531:     shwsel = "";
                   1532:     re = /newmsg/;
                   1533:     if (re.test(msgchk)) { shwsel = "checked" }
                   1534:     newMsg(newmsg,shwsel);
                   1535:     msgTail(); 
                   1536:     return;
                   1537:   }
                   1538: 
1.123     ng       1539:   function checkEntities(strx) {
                   1540:     if (strx.length == 0) return strx;
                   1541:     var orgStr = ["&", "<", ">", '"']; 
                   1542:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1543:     var counter = 0;
                   1544:     while (counter < 4) {
                   1545: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1546: 	counter++;
                   1547:     }
                   1548:     return strx;
                   1549:   }
                   1550: 
                   1551:   function strReplace(strx, orgStr, newStr) {
                   1552:     return strx.split(orgStr).join(newStr);
                   1553:   }
                   1554: 
1.44      ng       1555:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1556:     var height = 70*Nmsg+250;
1.44      ng       1557:     var scrollbar = "no";
                   1558:     if (height > 600) {
                   1559: 	height = 600;
                   1560: 	scrollbar = "yes";
                   1561:     }
1.118     ng       1562:     var xpos = (screen.width-600)/2;
                   1563:     xpos = (xpos < 0) ? '0' : xpos;
                   1564:     var ypos = (screen.height-height)/2-30;
                   1565:     ypos = (ypos < 0) ? '0' : ypos;
                   1566: 
1.206     albertel 1567:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1568:     pWin.focus();
                   1569:     pDoc = pWin.document;
1.219     www      1570:     pDoc.$docopen;
1.351     albertel 1571:     pDoc.write('$start_page_msg_central');
1.76      ng       1572: 
                   1573:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1574:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.465     albertel 1575:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1576: 
1.564     bisitz   1577:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1578:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1579:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1.44      ng       1580: }
                   1581:     function displaySubject(msg,shwsel) {
1.76      ng       1582:     pDoc = pWin.document;
                   1583:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1584:     pDoc.write("<td>Subject<\\/td>");
                   1585:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1586:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1587: }
                   1588: 
1.72      ng       1589:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1590:     pDoc = pWin.document;
                   1591:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1592:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1593:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1594:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1595: }
                   1596: 
                   1597:   function newMsg(newmsg,shwsel) {
1.76      ng       1598:     pDoc = pWin.document;
                   1599:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1600:     pDoc.write("<td align=\\"center\\">New<\\/td>");
                   1601:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1602:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1603: }
                   1604: 
                   1605:   function msgTail() {
1.76      ng       1606:     pDoc = pWin.document;
1.465     albertel 1607:     pDoc.write("<\\/table>");
                   1608:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.76      ng       1609:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
1.326     albertel 1610:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.465     albertel 1611:     pDoc.write("<\\/form>");
1.351     albertel 1612:     pDoc.write('$end_page_msg_central');
1.128     ng       1613:     pDoc.close();
1.44      ng       1614: }
                   1615: 
                   1616: //====================== Script for keyword highlight options ==============
                   1617:   function kwhighlight() {
                   1618:     var kwclr    = document.SCORE.kwclr.value;
                   1619:     var kwsize   = document.SCORE.kwsize.value;
                   1620:     var kwstyle  = document.SCORE.kwstyle.value;
                   1621:     var redsel = "";
                   1622:     var grnsel = "";
                   1623:     var blusel = "";
                   1624:     if (kwclr=="red")   {var redsel="checked"};
                   1625:     if (kwclr=="green") {var grnsel="checked"};
                   1626:     if (kwclr=="blue")  {var blusel="checked"};
                   1627:     var sznsel = "";
                   1628:     var sz1sel = "";
                   1629:     var sz2sel = "";
                   1630:     if (kwsize=="0")  {var sznsel="checked"};
                   1631:     if (kwsize=="+1") {var sz1sel="checked"};
                   1632:     if (kwsize=="+2") {var sz2sel="checked"};
                   1633:     var synsel = "";
                   1634:     var syisel = "";
                   1635:     var sybsel = "";
                   1636:     if (kwstyle=="")    {var synsel="checked"};
                   1637:     if (kwstyle=="<i>") {var syisel="checked"};
                   1638:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1639:     highlightCentral();
                   1640:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1641:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1642:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1643:     highlightend();
                   1644:     return;
                   1645:   }
                   1646: 
                   1647:   function highlightCentral() {
1.76      ng       1648: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1649:     var xpos = (screen.width-400)/2;
                   1650:     xpos = (xpos < 0) ? '0' : xpos;
                   1651:     var ypos = (screen.height-330)/2-30;
                   1652:     ypos = (ypos < 0) ? '0' : ypos;
                   1653: 
1.206     albertel 1654:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1655:     hwdWin.focus();
                   1656:     var hDoc = hwdWin.document;
1.219     www      1657:     hDoc.$docopen;
1.351     albertel 1658:     hDoc.write('$start_page_highlight_central');
1.76      ng       1659:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.465     albertel 1660:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1.76      ng       1661: 
1.564     bisitz   1662:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1663:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1664:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1665:   }
                   1666: 
                   1667:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1668:     var hDoc = hwdWin.document;
                   1669:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1670:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1671:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1672:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1673:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1674:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1675:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1676:     hDoc.write("<\\/tr>");
1.44      ng       1677:   }
                   1678: 
                   1679:   function highlightend() { 
1.76      ng       1680:     var hDoc = hwdWin.document;
1.465     albertel 1681:     hDoc.write("<\\/table>");
                   1682:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.76      ng       1683:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
1.326     albertel 1684:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.465     albertel 1685:     hDoc.write("<\\/form>");
1.351     albertel 1686:     hDoc.write('$end_page_highlight_central');
1.128     ng       1687:     hDoc.close();
1.44      ng       1688:   }
                   1689: 
                   1690: </script>
                   1691: SUBJAVASCRIPT
                   1692: }
                   1693: 
1.349     albertel 1694: sub get_increment {
1.348     bowersj2 1695:     my $increment = $env{'form.increment'};
                   1696:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1697:         $increment != .1) {
                   1698:         $increment = 1;
                   1699:     }
                   1700:     return $increment;
                   1701: }
                   1702: 
1.71      ng       1703: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1704: sub gradeBox {
1.322     albertel 1705:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1706:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1707: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1708:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1709:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1710:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1711:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1712:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1713: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1714:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1715:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1716:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1717: 				       [$partid]);
                   1718:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1719:     if ($last_resets{$partid}) {
                   1720:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1721:     }
1.485     albertel 1722:     $result.='<table border="0"><tr>';
1.71      ng       1723:     my $ctr = 0;
1.348     bowersj2 1724:     my $thisweight = 0;
1.349     albertel 1725:     my $increment = &get_increment();
1.485     albertel 1726: 
                   1727:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1728:     while ($thisweight<=$wgt) {
1.532     bisitz   1729: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.71      ng       1730: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1731: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1732: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1733: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1734:         $thisweight += $increment;
1.71      ng       1735: 	$ctr++;
                   1736:     }
1.485     albertel 1737:     $radio.='</tr></table>';
                   1738: 
                   1739:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1740: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
                   1741: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
                   1742: 	$wgt.')" /></td>'."\n";
1.485     albertel 1743:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1744: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.540     riegler  1745: 	' </td><td><b>'.&mt('Grade Status').':</b>'."\n";
1.485     albertel 1746:     $line.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.71      ng       1747: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
                   1748:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1749: 	$line.='<option></option>'.
                   1750: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1751:     } else {
1.485     albertel 1752: 	$line.='<option selected="selected"></option>'.
                   1753: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1754:     }
1.485     albertel 1755:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1756: 
                   1757:     $result .= 
1.574.2.4  raeburn  1758: 	    '<td><b>'.&mt('Part').':</b></td><td>'.$display_part.'</td><td><b>'.&mt('Points').':</b></td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1.485     albertel 1759:     $result.='</tr></table>'."\n";
1.71      ng       1760:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1761: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1762: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1763: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1764:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1765:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1766:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1767:         $aggtries.'" />'."\n";
1.574.2.7  raeburn  1768:     my $res_error;
                   1769:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
                   1770:     if ($res_error) {
                   1771:         return &navmap_errormsg();
                   1772:     }
1.318     banghart 1773:     return $result;
                   1774: }
1.322     albertel 1775: 
                   1776: sub handback_box {
1.574.2.7  raeburn  1777:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
                   1778:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
1.323     banghart 1779:     my (@respids);
1.574.2.7  raeburn  1780:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 1781:     foreach my $part_response_id (@part_response_id) {
                   1782:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1783:         if ($part eq $partid) {
1.375     albertel 1784:             push(@respids,$resp);
1.323     banghart 1785:         }
                   1786:     }
1.318     banghart 1787:     my $result;
1.323     banghart 1788:     foreach my $respid (@respids) {
1.322     albertel 1789: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1790: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1791: 	next if (!@$files);
                   1792: 	my $file_counter = 1;
1.313     banghart 1793: 	foreach my $file (@$files) {
1.368     banghart 1794: 	    if ($file =~ /\/portfolio\//) {
                   1795:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1796:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1797:     	        $file_disp = "$name.$ext";
                   1798:     	        $file = $file_path.$file_disp;
                   1799:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1800:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1801:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1802:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.485     albertel 1803:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
1.368     banghart 1804:     	        $file_counter++;
                   1805: 	    }
1.322     albertel 1806: 	}
1.313     banghart 1807:     }
1.318     banghart 1808:     return $result;    
1.71      ng       1809: }
1.44      ng       1810: 
1.58      albertel 1811: sub show_problem {
1.382     albertel 1812:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1813:     my $rendered;
1.382     albertel 1814:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1815:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1816:     if ($mode eq 'both' or $mode eq 'text') {
                   1817: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1818: 						       $env{'request.course.id'},
                   1819: 						       undef,\%form);
1.144     albertel 1820:     }
1.58      albertel 1821:     if ($removeform) {
                   1822: 	$rendered=~s|<form(.*?)>||g;
                   1823: 	$rendered=~s|</form>||g;
1.374     albertel 1824: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1825:     }
1.144     albertel 1826:     my $companswer;
                   1827:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1828: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1829: 	$companswer=
                   1830: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1831: 						    $env{'request.course.id'},
                   1832: 						    %form);
1.144     albertel 1833:     }
1.58      albertel 1834:     if ($removeform) {
                   1835: 	$companswer=~s|<form(.*?)>||g;
                   1836: 	$companswer=~s|</form>||g;
1.144     albertel 1837: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1838:     }
1.468     albertel 1839:     $rendered=
                   1840: 	'<div class="LC_grade_show_problem_header">'.
                   1841: 	&mt('View of the problem').
                   1842: 	'</div><div class="LC_grade_show_problem_problem">'.
                   1843: 	$rendered.
                   1844: 	'</div>';
                   1845:     $companswer=
                   1846: 	'<div class="LC_grade_show_problem_header">'.
                   1847: 	&mt('Correct answer').
                   1848: 	'</div><div class="LC_grade_show_problem_problem">'.
                   1849: 	$companswer.
                   1850: 	'</div>';
                   1851:     my $result;
1.144     albertel 1852:     if ($mode eq 'both') {
1.468     albertel 1853: 	$result=$rendered.$companswer;
1.144     albertel 1854:     } elsif ($mode eq 'text') {
1.468     albertel 1855: 	$result=$rendered;
1.144     albertel 1856:     } elsif ($mode eq 'answer') {
1.468     albertel 1857: 	$result=$companswer;
1.144     albertel 1858:     }
1.468     albertel 1859:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
1.71      ng       1860:     return $result;
1.58      albertel 1861: }
1.397     albertel 1862: 
1.396     banghart 1863: sub files_exist {
                   1864:     my ($r, $symb) = @_;
                   1865:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1866: 
1.396     banghart 1867:     foreach my $student (@students) {
                   1868:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1869:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1870: 					      $udom,$uname);
1.396     banghart 1871:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1872:         foreach my $submission (@$string) {
                   1873:             my ($partid,$respid) =
                   1874: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1875:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1876: 					   \%record);
                   1877:             return 1 if (@$files);
1.396     banghart 1878:         }
                   1879:     }
1.397     albertel 1880:     return 0;
1.396     banghart 1881: }
1.397     albertel 1882: 
1.394     banghart 1883: sub download_all_link {
                   1884:     my ($r,$symb) = @_;
1.395     albertel 1885:     my $all_students = 
                   1886: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1887: 
                   1888:     my $parts =
                   1889: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1890: 
1.394     banghart 1891:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1892:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1893:                              'cgi.'.$identifier.'.symb' => $symb,
                   1894:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1895:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1896: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1897:     return
                   1898: }
1.395     albertel 1899: 
1.432     banghart 1900: sub build_section_inputs {
                   1901:     my $section_inputs;
                   1902:     if ($env{'form.section'} eq '') {
                   1903:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1904:     } else {
                   1905:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1906:         foreach my $section (@sections) {
1.432     banghart 1907:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1908:         }
                   1909:     }
                   1910:     return $section_inputs;
                   1911: }
                   1912: 
1.44      ng       1913: # --------------------------- show submissions of a student, option to grade 
                   1914: sub submission {
                   1915:     my ($request,$counter,$total) = @_;
1.257     albertel 1916:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1917:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1918:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1919:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.324     albertel 1920:     my $symb = &get_symb($request); 
                   1921:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1922: 
                   1923:     if (!&canview($usec)) {
1.398     albertel 1924: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1925: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1926: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1927: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1928: 	return;
                   1929:     }
                   1930: 
1.257     albertel 1931:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1932:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1933:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1934:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1935:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1936: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1937: 	'/check.gif" height="16" border="0" />';
1.41      ng       1938: 
1.426     albertel 1939:     my %old_essays;
1.41      ng       1940:     # header info
                   1941:     if ($counter == 0) {
                   1942: 	&sub_page_js($request);
1.257     albertel 1943: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1944: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1945: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1946: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1947: 	    &download_all_link($request, $symb);
                   1948: 	}
1.485     albertel 1949: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
                   1950: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
1.118     ng       1951: 
1.44      ng       1952: 	# option to display problem, only once else it cause problems 
                   1953:         # with the form later since the problem has a form.
1.257     albertel 1954: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1955: 	    my $mode;
1.257     albertel 1956: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1957: 		$mode='both';
1.257     albertel 1958: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1959: 		$mode='text';
1.257     albertel 1960: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1961: 		$mode='answer';
                   1962: 	    }
1.329     albertel 1963: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1964: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1965: 	}
1.441     www      1966: 
1.44      ng       1967: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1968:         # if this subroutine has been called once.
1.41      ng       1969: 	my %keyhash = ();
1.257     albertel 1970: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1971: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1972: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1973: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1974: 
1.257     albertel 1975: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1976: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1977: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1978: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1979: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1980: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1981: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1982: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1983: 	}
1.257     albertel 1984: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1985: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1986: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1987: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1988: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 1989: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1990: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1991: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1992: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1993: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1994: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1995: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1996: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1997: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1998: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1999: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 2000: 			&build_section_inputs().
1.326     albertel 2001: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   2002: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       2003: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2004: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   2005: 	if ($env{'form.handgrade'} eq 'yes') {
                   2006: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2007: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2008: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2009: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2010: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2011: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2012: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2013: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2014: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2015: 	    }
1.123     ng       2016: 	}
1.41      ng       2017: 	
                   2018: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2019: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2020: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2021: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2022: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2023: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2024: 		'" />'."\n".
                   2025: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2026: 	    $cts++;
                   2027: 	}
                   2028: 	$request->print($prnmsg);
1.32      ng       2029: 
1.257     albertel 2030: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      2031: #
                   2032: # Print out the keyword options line
                   2033: #
1.41      ng       2034: 	    $request->print(<<KEYWORDS);
1.38      ng       2035: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 2036: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.38      ng       2037: <a href="#" onMouseDown="javascript:getSel(); return false"
                   2038:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 2039: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       2040: KEYWORDS
1.88      www      2041: #
                   2042: # Load the other essays for similarity check
                   2043: #
1.324     albertel 2044:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2045: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2046: 	    $apath=&escape($apath);
1.88      www      2047: 	    $apath=~s/\W/\_/gs;
1.426     albertel 2048: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       2049:         }
                   2050:     }
1.44      ng       2051: 
1.441     www      2052: # This is where output for one specific student would start
1.468     albertel 2053:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
1.441     www      2054:     $request->print("\n\n".
1.468     albertel 2055:                     '<div class="LC_grade_show_user '.$add_class.'">'.
                   2056: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
                   2057: 		    '<div class="LC_grade_show_user_body">'."\n");
1.441     www      2058: 
1.257     albertel 2059:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2060: 	my $mode;
1.257     albertel 2061: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2062: 	    $mode='both';
1.257     albertel 2063: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2064: 	    $mode='text';
1.257     albertel 2065: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2066: 	    $mode='answer';
                   2067: 	}
1.329     albertel 2068: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2069: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2070:     }
1.144     albertel 2071: 
1.257     albertel 2072:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.574.2.7  raeburn  2073:     my $res_error;
                   2074:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2075:     if ($res_error) {
                   2076:         $request->print(&navmap_errormsg());
                   2077:         return;
                   2078:     }
1.41      ng       2079: 
1.44      ng       2080:     # Display student info
1.41      ng       2081:     $request->print(($counter == 0 ? '' : '<br />'));
1.468     albertel 2082:     my $result='<div class="LC_grade_submissions">';
                   2083:     
                   2084:     $result.='<div class="LC_grade_submissions_header">';
                   2085:     $result.= &mt('Submissions');
1.45      ng       2086:     $result.='<input type="hidden" name="name'.$counter.
1.257     albertel 2087: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
1.469     albertel 2088:     if ($env{'form.handgrade'} eq 'no') {
                   2089: 	$result.='<span class="LC_grade_check_note">'.
                   2090: 	    &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
                   2091: 
                   2092:     }
                   2093: 
                   2094: 
1.41      ng       2095: 
1.118     ng       2096:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2097:     my $fullname;
                   2098:     my $col_fullnames = [];
1.257     albertel 2099:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 2100: 	(my $sub_result,$fullname,$col_fullnames)=
                   2101: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2102: 				 $counter);
                   2103: 	$result.=$sub_result;
1.41      ng       2104:     }
1.44      ng       2105:     $request->print($result."\n");
1.468     albertel 2106:     $request->print('</div>'."\n");
1.44      ng       2107:     # print student answer/submission
                   2108:     # Options are (1) Handgaded submission only
                   2109:     #             (2) Last submission, includes submission that is not handgraded 
                   2110:     #                  (for multi-response type part)
                   2111:     #             (3) Last submission plus the parts info
                   2112:     #             (4) The whole record for this student
1.257     albertel 2113:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2114: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2115: 	
                   2116: 	my $lastsubonly;
                   2117: 
1.151     albertel 2118: 	if ($$timestamp eq '') {
1.468     albertel 2119: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
1.151     albertel 2120: 	} else {
1.468     albertel 2121: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
                   2122: 
1.151     albertel 2123: 	    my %seenparts;
1.375     albertel 2124: 	    my @part_response_id = &flatten_responseType($responseType);
                   2125: 	    foreach my $part (@part_response_id) {
1.393     albertel 2126: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2127: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2128: 
1.375     albertel 2129: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2130: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2131: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2132: 		    if (exists($seenparts{$partid})) { next; }
                   2133: 		    $seenparts{$partid}=1;
1.207     albertel 2134: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2135: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2136: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2137: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2138: 			'\');" target="_self">'.
1.257     albertel 2139: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2140: 		    $request->print($submitby);
                   2141: 		    next;
                   2142: 		}
                   2143: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2144: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.468     albertel 2145: 		    $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
1.398     albertel 2146: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
                   2147: 			' )</span>&nbsp; &nbsp;'.
1.539     riegler  2148: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2149: 		    next;
                   2150: 		}
1.468     albertel 2151: 		foreach my $submission (@$string) {
                   2152: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2153: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.468     albertel 2154: 		    my ($ressub,$subval) = split(/:/,$submission,2);
1.151     albertel 2155: 		    # Similarity check
                   2156: 		    my $similar='';
1.257     albertel 2157: 		    if($env{'form.checkPlag'}){
1.151     albertel 2158: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2159: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2160: 			if ($osim) {
                   2161: 			    $osim=int($osim*100.0);
1.426     albertel 2162: 			    my %old_course_desc = 
                   2163: 				&Apache::lonnet::coursedescription($ocrsid,
                   2164: 								   {'one_time' => 1});
                   2165: 
                   2166: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
1.574     bisitz   2167: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
1.426     albertel 2168: 				    $osim,
1.574     bisitz   2169: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
1.426     albertel 2170: 				    $old_course_desc{'description'},
1.427     albertel 2171: 				    $old_course_desc{'num'},
1.426     albertel 2172: 				    $old_course_desc{'domain'}).
1.398     albertel 2173: 				'</span></h3><blockquote><i>'.
1.151     albertel 2174: 				&keywords_highlight($oessay).
                   2175: 				'</i></blockquote><hr />';
                   2176: 			}
1.150     albertel 2177: 		    }
1.151     albertel 2178: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2179: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2180: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2181: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2182: 			my $display_part=&get_display_part($partid,$symb);
1.468     albertel 2183: 			$lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
1.403     albertel 2184: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
1.398     albertel 2185: 			    ' )</span>&nbsp; &nbsp;';
1.313     banghart 2186: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2187: 			if (@$files) {
1.544     raeburn  2188: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
1.303     banghart 2189: 			    my $file_counter = 0;
1.313     banghart 2190: 			    foreach my $file (@$files) {
1.468     albertel 2191: 			        $file_counter++;
1.232     albertel 2192: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.564     bisitz   2193: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
1.232     albertel 2194: 			    }
1.236     albertel 2195: 			    $lastsubonly.='<br />';
1.41      ng       2196: 			}
1.468     albertel 2197: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
1.151     albertel 2198: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
1.555     raeburn  2199: 					 $respid,\%record,$order,undef,$uname,$udom);
1.151     albertel 2200: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2201: 			$lastsubonly.='</div>';
1.41      ng       2202: 		    }
                   2203: 		}
                   2204: 	    }
1.468     albertel 2205: 	    $lastsubonly.='</div>'."\n";
1.151     albertel 2206: 	}
                   2207: 	$request->print($lastsubonly);
1.468     albertel 2208:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2209: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2210: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2211:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2212: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2213: 								 $env{'request.course.id'},
1.44      ng       2214: 								 $last,'.submission',
                   2215: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2216:     }
1.120     ng       2217: 
1.121     ng       2218:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2219: 	.$udom.'" />'."\n");
1.44      ng       2220:     # return if view submission with no grading option
1.257     albertel 2221:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2222: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       2223: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2224: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2225: 	$toGrade.='</div>'."\n";
1.257     albertel 2226: 	if (($env{'form.command'} eq 'submission') || 
                   2227: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2228: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2229: 	}
1.180     albertel 2230: 	$request->print($toGrade);
1.41      ng       2231: 	return;
1.180     albertel 2232:     } else {
1.468     albertel 2233: 	$request->print('</div>'."\n");
1.41      ng       2234:     }
1.33      ng       2235: 
1.121     ng       2236:     # essay grading message center
1.257     albertel 2237:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2238: 	my $result='<div class="LC_grade_message_center">';
                   2239:     
                   2240: 	$result.='<div class="LC_grade_message_center_header">'.
                   2241: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2242: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2243: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2244: 	if (scalar(@$col_fullnames) > 0) {
                   2245: 	    my $lastone = pop(@$col_fullnames);
                   2246: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2247: 	}
                   2248: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2249: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2250: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2251: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2252: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2253: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2254: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2255: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2256: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2257: 	    '<br />&nbsp;('.
1.468     albertel 2258: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2259: 	$result.='</div></div>';
1.121     ng       2260: 	$request->print($result);
1.118     ng       2261:     }
1.41      ng       2262: 
                   2263:     my %seen = ();
                   2264:     my @partlist;
1.129     ng       2265:     my @gradePartRespid;
1.375     albertel 2266:     my @part_response_id = &flatten_responseType($responseType);
1.468     albertel 2267:     $request->print('<div class="LC_grade_assign">'.
                   2268: 		    
                   2269: 		    '<div class="LC_grade_assign_header">'.
                   2270: 		    &mt('Assign Grades').'</div>'.
                   2271: 		    '<div class="LC_grade_assign_body">');
1.375     albertel 2272:     foreach my $part_response_id (@part_response_id) {
                   2273:     	my ($partid,$respid) = @{ $part_response_id };
                   2274: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2275: 	next if ($seen{$partid} > 0);
1.41      ng       2276: 	$seen{$partid}++;
1.393     albertel 2277: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2278: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2279: 	push(@partlist,$partid);
                   2280: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2281: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2282:     }
1.468     albertel 2283:     $request->print('</div></div>');
                   2284: 
                   2285:     $request->print('<div class="LC_grade_info_links">');
                   2286:     if ($perm{'vgr'}) {
                   2287: 	$request->print(
                   2288: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   2289: 						   $uname,$udom,'check'));
                   2290:     }
                   2291:     if ($perm{'opa'}) {
                   2292: 	$request->print(
                   2293: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   2294: 					 $uname,$udom,$symb,'check'));
                   2295:     }
                   2296:     $request->print('</div>');
                   2297: 
1.45      ng       2298:     $result='<input type="hidden" name="partlist'.$counter.
                   2299: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2300:     $result.='<input type="hidden" name="gradePartRespid'.
                   2301: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2302:     my $ctr = 0;
                   2303:     while ($ctr < scalar(@partlist)) {
                   2304: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2305: 	    $partlist[$ctr].'" />'."\n";
                   2306: 	$ctr++;
                   2307:     }
1.468     albertel 2308:     $request->print($result.''."\n");
1.41      ng       2309: 
1.441     www      2310: # Done with printing info for one student
                   2311: 
1.468     albertel 2312:     $request->print('</div>');#LC_grade_show_user_body
                   2313:     $request->print('</div>');#LC_grade_show_user
1.441     www      2314: 
                   2315: 
1.41      ng       2316:     # print end of form
                   2317:     if ($counter == $total) {
1.297     www      2318: 	my $endform='<table border="0"><tr><td>'."\n";
1.485     albertel 2319: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.119     ng       2320: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2321: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2322: 	my $ntstu ='<select name="NTSTU">'.
                   2323: 	    '<option>1</option><option>2</option>'.
                   2324: 	    '<option>3</option><option>5</option>'.
                   2325: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2326: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2327: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.574.2.2  raeburn  2328:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2329: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.417     albertel 2330: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2331: 	    '<input type="button" value="'.&mt('Next').'" '.
1.417     albertel 2332: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.485     albertel 2333: 	$endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
1.349     albertel 2334:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2335:             "' name='increment' />";
1.485     albertel 2336: 	$endform.='</td></tr></table></form>';
1.324     albertel 2337: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2338: 	$request->print($endform);
                   2339:     }
                   2340:     return '';
1.38      ng       2341: }
                   2342: 
1.464     albertel 2343: sub check_collaborators {
                   2344:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2345:     my ($result,@col_fullnames);
                   2346:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2347:     foreach my $part (keys(%$handgrade)) {
                   2348: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2349: 					'.maxcollaborators',
                   2350: 					$symb,$udom,$uname);
                   2351: 	next if ($ncol <= 0);
                   2352: 	$part =~ s/\_/\./g;
                   2353: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2354: 	my (@good_collaborators, @bad_collaborators);
                   2355: 	foreach my $possible_collaborator
                   2356: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
                   2357: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2358: 	    next if ($possible_collaborator eq '');
                   2359: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
                   2360: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2361: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2362: 	    # Doing this grep allows 'fuzzy' specification
                   2363: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2364: 			       keys(%$classlist));
                   2365: 	    if (! scalar(@matches)) {
                   2366: 		push(@bad_collaborators, $possible_collaborator);
                   2367: 	    } else {
                   2368: 		push(@good_collaborators, @matches);
                   2369: 	    }
                   2370: 	}
                   2371: 	if (scalar(@good_collaborators) != 0) {
1.466     albertel 2372: 	    $result.='<br />'.&mt('Collaborators: ');
1.464     albertel 2373: 	    foreach my $name (@good_collaborators) {
                   2374: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2375: 		push(@col_fullnames, $givenn.' '.$lastname);
                   2376: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
                   2377: 	    }
                   2378: 	    $result.='<br />'."\n";
1.466     albertel 2379: 	    my ($part)=split(/\./,$part);
1.464     albertel 2380: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2381: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2382: 		"\n";
                   2383: 	}
                   2384: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2385: 	    $result.='<div class="LC_warning">';
1.464     albertel 2386: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2387: 	    $result .= '</div>';
                   2388: 	}         
                   2389: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2390: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2391: 	    $result .= &mt('This student has submitted too many '.
                   2392: 		'collaborators.  Maximum is [_1].',$ncol);
                   2393: 	    $result .= '</div>';
                   2394: 	}
                   2395:     }
                   2396:     return ($result,$fullname,\@col_fullnames);
                   2397: }
                   2398: 
1.44      ng       2399: #--- Retrieve the last submission for all the parts
1.38      ng       2400: sub get_last_submission {
1.119     ng       2401:     my ($returnhash)=@_;
1.46      ng       2402:     my (@string,$timestamp);
1.119     ng       2403:     if ($$returnhash{'version'}) {
1.46      ng       2404: 	my %lasthash=();
                   2405: 	my ($version);
1.119     ng       2406: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2407: 	    foreach my $key (sort(split(/\:/,
                   2408: 					$$returnhash{$version.':keys'}))) {
                   2409: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2410: 		$timestamp = 
1.545     raeburn  2411: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2412: 	    }
                   2413: 	}
1.397     albertel 2414: 	foreach my $key (keys(%lasthash)) {
                   2415: 	    next if ($key !~ /\.submission$/);
                   2416: 
                   2417: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2418: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2419: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.397     albertel 2420: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
1.41      ng       2421: 	}
                   2422:     }
1.397     albertel 2423:     if (!@string) {
                   2424: 	$string[0] =
1.539     riegler  2425: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2426:     }
                   2427:     return (\@string,\$timestamp);
1.38      ng       2428: }
1.35      ng       2429: 
1.44      ng       2430: #--- High light keywords, with style choosen by user.
1.38      ng       2431: sub keywords_highlight {
1.44      ng       2432:     my $string    = shift;
1.257     albertel 2433:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2434:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2435:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2436:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2437:     foreach my $keyword (@keylist) {
                   2438: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2439:     }
                   2440:     return $string;
1.38      ng       2441: }
1.36      ng       2442: 
1.44      ng       2443: #--- Called from submission routine
1.38      ng       2444: sub processHandGrade {
1.41      ng       2445:     my ($request) = shift;
1.324     albertel 2446:     my $symb   = &get_symb($request);
                   2447:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2448:     my $button = $env{'form.gradeOpt'};
                   2449:     my $ngrade = $env{'form.NCT'};
                   2450:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2451:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2452:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2453: 
1.44      ng       2454:     if ($button eq 'Save & Next') {
                   2455: 	my $ctr = 0;
                   2456: 	while ($ctr < $ngrade) {
1.257     albertel 2457: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2458: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2459: 	    if ($errorflag eq 'no_score') {
                   2460: 		$ctr++;
                   2461: 		next;
                   2462: 	    }
1.104     albertel 2463: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2464: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2465: 		$ctr++;
                   2466: 		next;
                   2467: 	    }
1.257     albertel 2468: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2469: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2470: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2471:             my ($feedurl,$showsymb) =
                   2472: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2473: 	    my $messagetail;
1.62      albertel 2474: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2475: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2476: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2477: 		$subject.=' ['.$restitle.']';
1.44      ng       2478: 		my (@msgnum) = split(/,/,$includemsg);
                   2479: 		foreach (@msgnum) {
1.257     albertel 2480: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2481: 		}
1.80      ng       2482: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2483: 		if ($env{'form.withgrades'.$ctr}) {
                   2484: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2485: 		    $messagetail = " for <a href=\"".
1.418     albertel 2486: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2487: 		}
                   2488: 		$msgstatus = 
                   2489:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2490: 						     $message.$messagetail,
1.418     albertel 2491:                                                      undef,$feedurl,undef,
1.386     raeburn  2492:                                                      undef,undef,$showsymb,
                   2493:                                                      $restitle);
1.574     bisitz   2494: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.296     www      2495: 				$msgstatus);
1.44      ng       2496: 	    }
1.257     albertel 2497: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2498: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2499: 		foreach my $collabstr (@collabstrs) {
                   2500: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2501: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2502: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2503: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2504: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2505: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2506: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2507: 			    next;
1.418     albertel 2508: 			} elsif ($message ne '') {
                   2509: 			    my ($baseurl,$showsymb) = 
                   2510: 				&get_feedurl_and_symb($symb,$collaborator,
                   2511: 						      $udom);
                   2512: 			    if ($env{'form.withgrades'.$ctr}) {
                   2513: 				$messagetail = " for <a href=\"".
1.386     raeburn  2514:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2515: 			    }
1.418     albertel 2516: 			    $msgstatus = 
                   2517: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2518: 			}
1.44      ng       2519: 		    }
                   2520: 		}
                   2521: 	    }
                   2522: 	    $ctr++;
                   2523: 	}
                   2524:     }
                   2525: 
1.257     albertel 2526:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2527: 	# Keywords sorted in alphabatical order
1.257     albertel 2528: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2529: 	my %keyhash = ();
1.257     albertel 2530: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2531: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2532: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2533: 	$env{'form.keywords'} = join(' ',@keywords);
                   2534: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2535: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2536: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2537: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2538: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2539: 
                   2540: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2541: 	# New messages are saved in env for the next student.
1.119     ng       2542: 	# All messages are saved in nohist_handgrade.db
                   2543: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2544: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2545: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2546: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2547: 		$idx++;
                   2548: 	    }
                   2549: 	    $ctr++;
1.41      ng       2550: 	}
1.119     ng       2551: 	$ctr = 0;
                   2552: 	while ($ctr < $ngrade) {
1.257     albertel 2553: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2554: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2555: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2556: 		$idx++;
                   2557: 	    }
                   2558: 	    $ctr++;
1.41      ng       2559: 	}
1.257     albertel 2560: 	$env{'form.savemsgN'} = --$idx;
                   2561: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2562: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2563: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2564:     }
1.44      ng       2565:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2566:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2567:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2568: 	my ($ctr,$total) = (0,0);
                   2569: 	while ($ctr < $ngrade) {
1.257     albertel 2570: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2571: 	    $ctr++;
                   2572: 	}
1.257     albertel 2573: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2574: 	$ctr = 0;
                   2575: 	while ($ctr < $total) {
1.257     albertel 2576: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2577: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2578: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2579: 	    &submission($request,$ctr,$total-1);
1.41      ng       2580: 	    $ctr++;
                   2581: 	}
                   2582: 	return '';
                   2583:     }
1.36      ng       2584: 
1.121     ng       2585: # Go directly to grade student - from submission or link from chart page
1.120     ng       2586:     if ($button eq 'Grade Student') {
1.324     albertel 2587: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2588: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2589: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2590: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2591: 	&submission($request,0,0);
                   2592: 	return '';
                   2593:     }
                   2594: 
1.44      ng       2595:     # Get the next/previous one or group of students
1.257     albertel 2596:     my $firststu = $env{'form.unamedom0'};
                   2597:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2598:     my $ctr = 2;
1.41      ng       2599:     while ($laststu eq '') {
1.257     albertel 2600: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2601: 	$ctr++;
                   2602: 	$laststu = $firststu if ($ctr > $ngrade);
                   2603:     }
1.44      ng       2604: 
1.41      ng       2605:     my (@parsedlist,@nextlist);
                   2606:     my ($nextflg) = 0;
1.524     raeburn  2607:     foreach my $item (sort 
1.294     albertel 2608: 	     {
                   2609: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2610: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2611: 		 }
                   2612: 		 return $a cmp $b;
                   2613: 	     } (keys(%$fullname))) {
1.41      ng       2614: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2615: 	    push(@parsedlist,$item);
1.41      ng       2616: 	}
1.524     raeburn  2617: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2618: 	if ($button eq 'Previous') {
1.524     raeburn  2619: 	    last if ($item eq $firststu);
                   2620: 	    push(@parsedlist,$item);
1.41      ng       2621: 	}
                   2622:     }
                   2623:     $ctr = 0;
                   2624:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.574.2.7  raeburn  2625:     my $res_error;
                   2626:     my ($partlist) = &response_type($symb,\$res_error);
                   2627:     if ($res_error) {
                   2628:         $request->print(&navmap_errormsg());
                   2629:         return;
                   2630:     }
1.41      ng       2631:     foreach my $student (@parsedlist) {
1.257     albertel 2632: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2633: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2634: 	
                   2635: 	if ($submitonly eq 'queued') {
                   2636: 	    my %queue_status = 
                   2637: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2638: 							$udom,$uname);
                   2639: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2640: 	}
                   2641: 
1.156     albertel 2642: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2643: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2644: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2645: 	    my $submitted = 0;
1.248     albertel 2646: 	    my $ungraded = 0;
                   2647: 	    my $incorrect = 0;
1.524     raeburn  2648: 	    foreach my $item (keys(%status)) {
                   2649: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2650: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2651: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2652: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2653: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2654: 		    $submitted = 0;
                   2655: 		}
1.41      ng       2656: 	    }
1.156     albertel 2657: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2658: 				     $submitonly eq 'incorrect' ||
                   2659: 				     $submitonly eq 'graded'));
1.248     albertel 2660: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2661: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2662: 	}
1.524     raeburn  2663: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2664: 	last if ($ctr == $ntstu);
1.41      ng       2665: 	$ctr++;
                   2666:     }
1.36      ng       2667: 
1.41      ng       2668:     $ctr = 0;
                   2669:     my $total = scalar(@nextlist)-1;
1.39      ng       2670: 
1.524     raeburn  2671:     foreach (sort(@nextlist)) {
1.41      ng       2672: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2673: 	$env{'form.student'}  = $uname;
                   2674: 	$env{'form.userdom'}  = $udom;
                   2675: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2676: 	&submission($request,$ctr,$total);
                   2677: 	$ctr++;
                   2678:     }
                   2679:     if ($total < 0) {
1.485     albertel 2680: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
                   2681: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
                   2682: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.324     albertel 2683: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2684: 	$request->print($the_end);
                   2685:     }
                   2686:     return '';
1.38      ng       2687: }
1.36      ng       2688: 
1.44      ng       2689: #---- Save the score and award for each student, if changed
1.38      ng       2690: sub saveHandGrade {
1.324     albertel 2691:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2692:     my @version_parts;
1.104     albertel 2693:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2694: 					   $env{'request.course.id'});
1.104     albertel 2695:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2696:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2697:     my @parts_graded;
1.77      ng       2698:     my %newrecord  = ();
                   2699:     my ($pts,$wgt) = ('','');
1.269     raeburn  2700:     my %aggregate = ();
                   2701:     my $aggregateflag = 0;
1.301     albertel 2702:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2703:     foreach my $new_part (@parts) {
1.337     banghart 2704: 	#collaborator ($submi may vary for different parts
1.259     banghart 2705: 	if ($submitter && $new_part ne $part) { next; }
                   2706: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2707: 	if ($dropMenu eq 'excused') {
1.259     banghart 2708: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2709: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2710: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2711: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2712: 		}
1.364     banghart 2713: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2714: 	    }
1.125     ng       2715: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2716: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2717: 	    foreach my $key (keys(%record)) {
1.259     banghart 2718: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2719: 	    }
1.259     banghart 2720: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2721: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2722:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2723: 
                   2724:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2725: 					       [$new_part]);
                   2726:             my $aggtries =$totaltries;
1.269     raeburn  2727:             if ($last_resets{$new_part}) {
1.270     albertel 2728:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2729: 					   $new_part);
1.269     raeburn  2730:             }
1.270     albertel 2731: 
                   2732:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2733:             if ($aggtries > 0) {
1.327     albertel 2734:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2735:                 $aggregateflag = 1;
                   2736:             }
1.125     ng       2737: 	} elsif ($dropMenu eq '') {
1.259     banghart 2738: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2739: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2740: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2741: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2742: 		next;
                   2743: 	    }
1.259     banghart 2744: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2745: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2746: 	    my $partial= $pts/$wgt;
1.259     banghart 2747: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2748: 		#do not update score for part if not changed.
1.346     banghart 2749:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2750: 		next;
1.251     banghart 2751: 	    } else {
1.524     raeburn  2752: 	        push(@parts_graded,$new_part);
1.153     albertel 2753: 	    }
1.259     banghart 2754: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2755: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2756: 	    }
1.259     banghart 2757: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2758: 	    if ($partial == 0) {
1.153     albertel 2759: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2760: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2761: 		}
1.41      ng       2762: 	    } else {
1.153     albertel 2763: 		if ($record{$reckey} ne 'correct_by_override') {
                   2764: 		    $newrecord{$reckey} = 'correct_by_override';
                   2765: 		}
                   2766: 	    }	    
                   2767: 	    if ($submitter && 
1.259     banghart 2768: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2769: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2770: 	    }
1.259     banghart 2771: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2772: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2773: 	}
1.259     banghart 2774: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2775: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2776: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2777: 	        $dropMenu eq 'reset status')
                   2778: 	   {
1.524     raeburn  2779: 	    push(@version_parts,$new_part);
1.259     banghart 2780: 	}
1.41      ng       2781:     }
1.301     albertel 2782:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2783:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2784: 
1.344     albertel 2785:     if (%newrecord) {
                   2786:         if (@version_parts) {
1.364     banghart 2787:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2788:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2789: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2790: 	    foreach my $new_part (@version_parts) {
                   2791: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2792: 				$new_part,\%newrecord);
                   2793: 	    }
1.259     banghart 2794:         }
1.44      ng       2795: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2796: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2797: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2798: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2799:     }
1.269     raeburn  2800:     if ($aggregateflag) {
                   2801:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2802: 			      $cdom,$cnum);
1.269     raeburn  2803:     }
1.301     albertel 2804:     return ('',$pts,$wgt);
1.36      ng       2805: }
1.322     albertel 2806: 
1.380     albertel 2807: sub check_and_remove_from_queue {
                   2808:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2809:     my @ungraded_parts;
                   2810:     foreach my $part (@{$parts}) {
                   2811: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2812: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2813: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2814: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2815: 		) {
                   2816: 	    push(@ungraded_parts, $part);
                   2817: 	}
                   2818:     }
                   2819:     if ( !@ungraded_parts ) {
                   2820: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2821: 					       $cnum,$domain,$stuname);
                   2822:     }
                   2823: }
                   2824: 
1.337     banghart 2825: sub handback_files {
                   2826:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2827:     my $portfolio_root = '/userfiles/portfolio';
1.574.2.7  raeburn  2828:     my $res_error;
                   2829:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2830:     if ($res_error) {
                   2831:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   2832:         return;
                   2833:     }
1.375     albertel 2834:     my @part_response_id = &flatten_responseType($responseType);
                   2835:     foreach my $part_response_id (@part_response_id) {
                   2836:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2837: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2838:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2839:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2840:                 my $file_counter = 1;
1.367     albertel 2841: 		my $file_msg;
1.337     banghart 2842:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2843:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2844:                     my ($directory,$answer_file) = 
                   2845:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2846:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2847: 		        &file_name_version_ext($answer_file);
1.355     banghart 2848: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  2849:                     my $getpropath = 1;
                   2850: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
1.338     banghart 2851: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2852:                     # fix file name
                   2853:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2854:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2855:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2856:             	                                $save_file_name);
1.337     banghart 2857:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  2858:                         $request->print('<br /><span class="LC_error">'.
                   2859:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
                   2860:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
                   2861:                                         '</span>');
1.356     banghart 2862:                     } else {
1.360     banghart 2863:                         # mark the file as read only
                   2864:                         my @files = ($save_file_name);
1.372     albertel 2865:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2866:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2867: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2868: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2869: 			}
                   2870:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2871: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2872: 
1.337     banghart 2873:                     }
                   2874:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2875:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2876:                     $file_counter++;
                   2877:                 }
1.367     albertel 2878: 		my $subject = "File Handed Back by Instructor ";
                   2879: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2880: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2881: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2882: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2883: 		my ($feedurl,$showsymb) = 
                   2884: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2885:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2886: 		my $msgstatus = 
                   2887:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2888: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2889:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2890:             }
                   2891:         }
1.338     banghart 2892:     return;
1.337     banghart 2893: }
                   2894: 
1.418     albertel 2895: sub get_feedurl_and_symb {
                   2896:     my ($symb,$uname,$udom) = @_;
                   2897:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2898:     $url = &Apache::lonnet::clutter($url);
                   2899:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2900: 					$symb,$udom,$uname);
                   2901:     if ($encrypturl =~ /^yes$/i) {
                   2902: 	&Apache::lonenc::encrypted(\$url,1);
                   2903: 	&Apache::lonenc::encrypted(\$symb,1);
                   2904:     }
                   2905:     return ($url,$symb);
                   2906: }
                   2907: 
1.313     banghart 2908: sub get_submitted_files {
                   2909:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2910:     my @files;
                   2911:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2912:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2913:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2914:     	    push(@files,$file_url.$file);
                   2915:         }
                   2916:     }
                   2917:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2918:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2919:     }
                   2920:     return (\@files);
                   2921: }
1.322     albertel 2922: 
1.269     raeburn  2923: # ----------- Provides number of tries since last reset.
                   2924: sub get_num_tries {
                   2925:     my ($record,$last_reset,$part) = @_;
                   2926:     my $timestamp = '';
                   2927:     my $num_tries = 0;
                   2928:     if ($$record{'version'}) {
                   2929:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2930:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2931:                 $timestamp = $$record{$version.':timestamp'};
                   2932:                 if ($timestamp > $last_reset) {
                   2933:                     $num_tries ++;
                   2934:                 } else {
                   2935:                     last;
                   2936:                 }
                   2937:             }
                   2938:         }
                   2939:     }
                   2940:     return $num_tries;
                   2941: }
                   2942: 
                   2943: # ----------- Determine decrements required in aggregate totals 
                   2944: sub decrement_aggs {
                   2945:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2946:     my %decrement = (
                   2947:                         attempts => 0,
                   2948:                         users => 0,
                   2949:                         correct => 0
                   2950:                     );
                   2951:     $decrement{'attempts'} = $aggtries;
                   2952:     if ($solvedstatus =~ /^correct/) {
                   2953:         $decrement{'correct'} = 1;
                   2954:     }
                   2955:     if ($aggtries == $totaltries) {
                   2956:         $decrement{'users'} = 1;
                   2957:     }
1.524     raeburn  2958:     foreach my $type (keys(%decrement)) {
1.269     raeburn  2959:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2960:     }
                   2961:     return;
                   2962: }
                   2963: 
                   2964: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2965: sub get_last_resets {
1.270     albertel 2966:     my ($symb,$courseid,$partids) =@_;
                   2967:     my %last_resets;
1.269     raeburn  2968:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2969:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2970:     my @keys;
                   2971:     foreach my $part (@{$partids}) {
                   2972: 	push(@keys,"$symb\0$part\0resettime");
                   2973:     }
                   2974:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2975: 				     $cdom,$cname);
                   2976:     foreach my $part (@{$partids}) {
                   2977: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2978:     }
1.270     albertel 2979:     return %last_resets;
1.269     raeburn  2980: }
                   2981: 
1.251     banghart 2982: # ----------- Handles creating versions for portfolio files as answers
                   2983: sub version_portfiles {
1.343     banghart 2984:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2985:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2986:     my @returned_keys;
1.255     banghart 2987:     my $parts = join('|', @$parts_graded);
1.517     raeburn  2988:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 2989:     foreach my $key (keys(%$record)) {
1.259     banghart 2990:         my $new_portfiles;
1.263     banghart 2991:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2992:             my @versioned_portfiles;
1.367     albertel 2993:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2994:             foreach my $file (@portfiles) {
1.306     banghart 2995:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2996:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2997: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2998: 		    &file_name_version_ext($answer_file);
1.517     raeburn  2999:                 my $getpropath = 1;    
                   3000:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 3001:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 3002:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3003:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3004:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3005:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3006:                         [$directory.$new_answer],
1.306     banghart 3007:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3008:                 }
1.252     banghart 3009:             }
1.343     banghart 3010:             $$record{$key} = join(',',@versioned_portfiles);
                   3011:             push(@returned_keys,$key);
1.251     banghart 3012:         }
                   3013:     } 
1.343     banghart 3014:     return (@returned_keys);   
1.305     banghart 3015: }
                   3016: 
1.307     banghart 3017: sub get_next_version {
1.341     banghart 3018:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3019:     my $version;
                   3020:     foreach my $row (@$dir_list) {
                   3021:         my ($file) = split(/\&/,$row,2);
                   3022:         my ($file_name,$file_version,$file_ext) =
                   3023: 	    &file_name_version_ext($file);
                   3024:         if (($file_name eq $answer_name) && 
                   3025: 	    ($file_ext eq $answer_ext)) {
                   3026:                 # gets here if filename and extension match, regardless of version
                   3027:                 if ($file_version ne '') {
                   3028:                 # a versioned file is found  so save it for later
                   3029:                 if ($file_version > $version) {
                   3030: 		    $version = $file_version;
                   3031: 	        }
                   3032:             }
                   3033:         }
                   3034:     } 
                   3035:     $version ++;
                   3036:     return($version);
                   3037: }
                   3038: 
1.305     banghart 3039: sub version_selected_portfile {
1.306     banghart 3040:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3041:     my ($answer_name,$answer_ver,$answer_ext) =
                   3042:         &file_name_version_ext($file_name);
                   3043:     my $new_answer;
                   3044:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3045:     if($env{'form.copy'} eq '-1') {
                   3046:         $new_answer = 'problem getting file';
                   3047:     } else {
                   3048:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3049:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3050:                             $stu_name,$domain,'copy',
                   3051: 		        '/portfolio'.$directory.$new_answer);
                   3052:     }    
                   3053:     return ($new_answer);
1.251     banghart 3054: }
                   3055: 
1.304     albertel 3056: sub file_name_version_ext {
                   3057:     my ($file)=@_;
                   3058:     my @file_parts = split(/\./, $file);
                   3059:     my ($name,$version,$ext);
                   3060:     if (@file_parts > 1) {
                   3061: 	$ext=pop(@file_parts);
                   3062: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3063: 	    $version=pop(@file_parts);
                   3064: 	}
                   3065: 	$name=join('.',@file_parts);
                   3066:     } else {
                   3067: 	$name=join('.',@file_parts);
                   3068:     }
                   3069:     return($name,$version,$ext);
                   3070: }
                   3071: 
1.44      ng       3072: #--------------------------------------------------------------------------------------
                   3073: #
                   3074: #-------------------------- Next few routines handles grading by section or whole class
                   3075: #
                   3076: #--- Javascript to handle grading by section or whole class
1.42      ng       3077: sub viewgrades_js {
                   3078:     my ($request) = shift;
                   3079: 
1.539     riegler  3080:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.41      ng       3081:     $request->print(<<VIEWJAVASCRIPT);
                   3082: <script type="text/javascript" language="javascript">
1.45      ng       3083:    function writePoint(partid,weight,point) {
1.125     ng       3084: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3085: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3086: 	if (point == "textval") {
1.125     ng       3087: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3088: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3089: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3090: 		var resetbox = false;
                   3091: 		for (var i=0; i<radioButton.length; i++) {
                   3092: 		    if (radioButton[i].checked) {
                   3093: 			textbox.value = i;
                   3094: 			resetbox = true;
                   3095: 		    }
                   3096: 		}
                   3097: 		if (!resetbox) {
                   3098: 		    textbox.value = "";
                   3099: 		}
                   3100: 		return;
                   3101: 	    }
1.109     matthew  3102: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3103: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3104: 				   ") greater than the weight for the part. Accept?");
                   3105: 		if (resp == false) {
                   3106: 		    textbox.value = "";
                   3107: 		    return;
                   3108: 		}
                   3109: 	    }
1.42      ng       3110: 	    for (var i=0; i<radioButton.length; i++) {
                   3111: 		radioButton[i].checked=false;
1.109     matthew  3112: 		if (parseFloat(point) == i) {
1.42      ng       3113: 		    radioButton[i].checked=true;
                   3114: 		}
                   3115: 	    }
1.41      ng       3116: 
1.42      ng       3117: 	} else {
1.125     ng       3118: 	    textbox.value = parseFloat(point);
1.42      ng       3119: 	}
1.41      ng       3120: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3121: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3122: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3123: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3124: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3125: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3126: 	    if (saveval != "correct") {
                   3127: 		scorename.value = point;
1.43      ng       3128: 		if (selname[0].selected != true) {
                   3129: 		    selname[0].selected = true;
                   3130: 		}
1.42      ng       3131: 	    }
                   3132: 	}
1.125     ng       3133: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3134:     }
                   3135: 
                   3136:     function writeRadText(partid,weight) {
1.125     ng       3137: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3138: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3139:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3140: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3141: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3142: 	    for (var i=0; i<radioButton.length; i++) {
                   3143: 		radioButton[i].checked=false;
                   3144: 
                   3145: 	    }
                   3146: 	    textbox.value = "";
                   3147: 
                   3148: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3149: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3150: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3151: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3152: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3153: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3154: 		if ((saveval != "correct") || override) {
1.42      ng       3155: 		    scorename.value = "";
1.125     ng       3156: 		    if (selval[1].selected) {
                   3157: 			selname[1].selected = true;
                   3158: 		    } else {
                   3159: 			selname[2].selected = true;
                   3160: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3161: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3162: 		    }
1.42      ng       3163: 		}
                   3164: 	    }
1.43      ng       3165: 	} else {
                   3166: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3167: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3168: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3169: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3170: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3171: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3172: 		if ((saveval != "correct") || override) {
1.125     ng       3173: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3174: 		    selname[0].selected = true;
                   3175: 		}
                   3176: 	    }
                   3177: 	}	    
1.42      ng       3178:     }
                   3179: 
                   3180:     function changeSelect(partid,user) {
1.125     ng       3181: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3182: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3183: 	var point  = textbox.value;
1.125     ng       3184: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3185: 
1.109     matthew  3186: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3187: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3188: 	    textbox.value = "";
                   3189: 	    return;
                   3190: 	}
1.109     matthew  3191: 	if (parseFloat(point) > parseFloat(weight)) {
                   3192: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3193: 			       ") greater than the weight of the part. Accept?");
                   3194: 	    if (resp == false) {
                   3195: 		textbox.value = "";
                   3196: 		return;
                   3197: 	    }
                   3198: 	}
1.42      ng       3199: 	selval[0].selected = true;
                   3200:     }
                   3201: 
                   3202:     function changeOneScore(partid,user) {
1.125     ng       3203: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3204: 	if (selval[1].selected || selval[2].selected) {
                   3205: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3206: 	    if (selval[2].selected) {
                   3207: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3208: 	    }
1.269     raeburn  3209:         }
1.42      ng       3210:     }
                   3211: 
                   3212:     function resetEntry(numpart) {
                   3213: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3214: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3215: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3216: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3217: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3218: 	    for (var i=0; i<radioButton.length; i++) {
                   3219: 		radioButton[i].checked=false;
                   3220: 
                   3221: 	    }
                   3222: 	    textbox.value = "";
                   3223: 	    selval[0].selected = true;
                   3224: 
                   3225: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3226: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3227: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3228: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3229: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3230: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3231: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3232: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3233: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3234: 		if (saveselval == "excused") {
1.43      ng       3235: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3236: 		} else {
1.43      ng       3237: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3238: 		}
                   3239: 	    }
1.41      ng       3240: 	}
1.42      ng       3241:     }
                   3242: 
1.41      ng       3243: </script>
                   3244: VIEWJAVASCRIPT
1.42      ng       3245: }
                   3246: 
1.44      ng       3247: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3248: sub viewgrades {
                   3249:     my ($request) = shift;
                   3250:     &viewgrades_js($request);
1.41      ng       3251: 
1.324     albertel 3252:     my ($symb) = &get_symb($request);
1.168     albertel 3253:     #need to make sure we have the correct data for later EXT calls, 
                   3254:     #thus invalidate the cache
                   3255:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3256:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3257:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3258:     &Apache::lonnet::clear_EXT_cache_status();
                   3259: 
1.398     albertel 3260:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.485     albertel 3261:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.41      ng       3262: 
                   3263:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3264:     $result.=&jscriptNform($symb);
1.41      ng       3265: 
1.44      ng       3266:     #beginning of class grading form
1.442     banghart 3267:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3268:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3269: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3270: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3271: 	&build_section_inputs().
1.257     albertel 3272: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3273: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3274: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3275: 
1.560     raeburn  3276:     my ($common_header,$specific_header);
1.257     albertel 3277:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3278: 	$common_header = &mt('Assign Common Grade to Class');
                   3279:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3280:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3281:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3282: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3283:     } else {
1.560     raeburn  3284:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3285:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3286: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3287:     }
1.560     raeburn  3288:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3289:     #radio buttons/text box for assigning points for a section or class.
                   3290:     #handles different parts of a problem
1.574.2.7  raeburn  3291:     my $res_error;
                   3292:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3293:     if ($res_error) {
                   3294:         return &navmap_errormsg();
                   3295:     }
1.42      ng       3296:     my %weight = ();
                   3297:     my $ctsparts = 0;
1.45      ng       3298:     my %seen = ();
1.375     albertel 3299:     my @part_response_id = &flatten_responseType($responseType);
                   3300:     foreach my $part_response_id (@part_response_id) {
                   3301:     	my ($partid,$respid) = @{ $part_response_id };
                   3302: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3303: 	next if $seen{$partid};
                   3304: 	$seen{$partid}++;
1.375     albertel 3305: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3306: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3307: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3308: 
1.324     albertel 3309: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3310: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3311: 	my $ctr = 0;
1.42      ng       3312: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3313: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3314: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3315: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3316: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3317: 	    $ctr++;
                   3318: 	}
1.485     albertel 3319: 	$radio.='</tr></table>';
                   3320: 	my $line = '<input type="text" name="TEXTVAL_'.
1.54      albertel 3321: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3322: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3323: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3324: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3325: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3326: 		$weight{$partid}.')"> '.
1.401     albertel 3327: 	    '<option selected="selected"> </option>'.
1.485     albertel 3328: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3329: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3330: 	    '</select></td>'.
                   3331:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3332: 	$line.='<input type="hidden" name="partid_'.
                   3333: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3334: 	$line.='<input type="hidden" name="weight_'.
                   3335: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3336: 
                   3337: 	$result.=
                   3338: 	    &Apache::loncommon::start_data_table_row()."\n".
1.539     riegler  3339: 	    '<td><b>'.&mt('Part').':</b></td><td>'.$display_part.'</td><td><b>'.&mt('Points').':</b></td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>'.
1.485     albertel 3340: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3341: 	$ctsparts++;
1.41      ng       3342:     }
1.474     albertel 3343:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3344: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3345:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.474     albertel 3346: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3347: 
1.44      ng       3348:     #table listing all the students in a section/class
                   3349:     #header of table
1.560     raeburn  3350:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3351:               &Apache::loncommon::start_data_table().
                   3352: 	      &Apache::loncommon::start_data_table_header_row().
                   3353: 	      '<th>'.&mt('No.').'</th>'.
                   3354: 	      '<th>'.&nameUserString('header')."</th>\n";
1.574.2.7  raeburn  3355:     my $partserror;
                   3356:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3357:     if ($partserror) {
                   3358:         return &navmap_errormsg();
                   3359:     }
1.324     albertel 3360:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3361:     my @partids = ();
1.41      ng       3362:     foreach my $part (@parts) {
                   3363: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3364:         my $narrowtext = &mt('Tries');
                   3365: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3366: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3367: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3368:         push(@partids,$partid);
1.324     albertel 3369: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3370: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3371: 	    $result.='<th>'.
                   3372: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3373: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3374: 	    next;
1.485     albertel 3375: 	    
1.207     albertel 3376: 	} else {
1.485     albertel 3377: 	    if ($display =~ /Problem Status/) {
                   3378: 		my $grade_status_mt = &mt('Grade Status');
                   3379: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3380: 	    }
                   3381: 	    my $part_mt = &mt('Part:');
                   3382: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3383: 	}
1.485     albertel 3384: 
1.474     albertel 3385: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3386:     }
1.474     albertel 3387:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3388: 
1.270     albertel 3389:     my %last_resets = 
                   3390: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3391: 
1.41      ng       3392:     #get info for each student
1.44      ng       3393:     #list all the students - with points and grade status
1.257     albertel 3394:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3395:     my $ctr = 0;
1.294     albertel 3396:     foreach (sort 
                   3397: 	     {
                   3398: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3399: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3400: 		 }
                   3401: 		 return $a cmp $b;
                   3402: 	     } (keys(%$fullname))) {
1.126     ng       3403: 	$ctr++;
1.324     albertel 3404: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3405: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3406:     }
1.474     albertel 3407:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3408:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3409:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.417     albertel 3410: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3411:     if (scalar(%$fullname) eq 0) {
                   3412: 	my $colspan=3+scalar(@parts);
1.433     banghart 3413: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3414:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3415: 	$result='<span class="LC_warning">'.
1.485     albertel 3416: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3417: 	        $section_display, $stu_status).
1.433     banghart 3418: 	    '</span>';
1.96      albertel 3419:     }
1.324     albertel 3420:     $result.=&show_grading_menu_form($symb);
1.41      ng       3421:     return $result;
                   3422: }
                   3423: 
1.44      ng       3424: #--- call by previous routine to display each student
1.41      ng       3425: sub viewstudentgrade {
1.324     albertel 3426:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3427:     my ($uname,$udom) = split(/:/,$student);
                   3428:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3429:     my %aggregates = (); 
1.474     albertel 3430:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3431: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3432: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3433: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3434: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3435: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3436:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3437:     foreach my $apart (@$parts) {
                   3438: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3439: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3440:         $result.='<td align="center">';
1.269     raeburn  3441:         my ($aggtries,$totaltries);
                   3442:         unless (exists($aggregates{$part})) {
1.270     albertel 3443: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3444: 
                   3445: 	    $aggtries = $totaltries;
1.269     raeburn  3446:             if ($$last_resets{$part}) {  
1.270     albertel 3447:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3448: 					   $part);
                   3449:             }
1.269     raeburn  3450:             $result.='<input type="hidden" name="'.
                   3451:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3452:             $result.='<input type="hidden" name="'.
                   3453:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3454:             $aggregates{$part} = 1;
                   3455:         }
1.41      ng       3456: 	if ($type eq 'awarded') {
1.320     albertel 3457: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3458: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3459: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3460: 	    $result.='<input type="text" name="'.
1.89      albertel 3461: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3462: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3463: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3464: 	} elsif ($type eq 'solved') {
                   3465: 	    my ($status,$foo)=split(/_/,$score,2);
                   3466: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3467: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3468: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3469: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3470: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3471: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3472: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3473: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3474: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3475: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3476: 	} else {
                   3477: 	    $result.='<input type="hidden" name="'.
                   3478: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3479: 		    "\n";
1.233     albertel 3480: 	    $result.='<input type="text" name="'.
1.122     ng       3481: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3482: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3483: 	}
                   3484:     }
1.474     albertel 3485:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3486:     return $result;
1.38      ng       3487: }
                   3488: 
1.44      ng       3489: #--- change scores for all the students in a section/class
                   3490: #    record does not get update if unchanged
1.38      ng       3491: sub editgrades {
1.41      ng       3492:     my ($request) = @_;
                   3493: 
1.324     albertel 3494:     my $symb=&get_symb($request);
1.433     banghart 3495:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3496:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
                   3497:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.433     banghart 3498:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3499: 
1.477     albertel 3500:     my $result= &Apache::loncommon::start_data_table().
                   3501: 	&Apache::loncommon::start_data_table_header_row().
                   3502: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3503: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3504:     my %scoreptr = (
                   3505: 		    'correct'  =>'correct_by_override',
                   3506: 		    'incorrect'=>'incorrect_by_override',
                   3507: 		    'excused'  =>'excused',
                   3508: 		    'ungraded' =>'ungraded_attempted',
                   3509: 		    'nothing'  => '',
                   3510: 		    );
1.257     albertel 3511:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3512: 
1.44      ng       3513:     my (@partid);
                   3514:     my %weight = ();
1.54      albertel 3515:     my %columns = ();
1.44      ng       3516:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3517: 
1.574.2.7  raeburn  3518:     my $partserror;
                   3519:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3520:     if ($partserror) {
                   3521:         return &navmap_errormsg();
                   3522:     }
1.54      albertel 3523:     my $header;
1.257     albertel 3524:     while ($ctr < $env{'form.totalparts'}) {
                   3525: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3526: 	push(@partid,$partid);
1.257     albertel 3527: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3528: 	$ctr++;
1.54      albertel 3529:     }
1.324     albertel 3530:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3531:     foreach my $partid (@partid) {
1.478     albertel 3532: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3533: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3534: 	$columns{$partid}=2;
                   3535: 	foreach my $stores (@parts) {
                   3536: 	    my ($part,$type) = &split_part_type($stores);
                   3537: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3538: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3539: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3540: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3541:             my $narrowtext = &mt('Tries');
                   3542: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3543: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3544: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3545: 	    $columns{$partid}+=2;
                   3546: 	}
                   3547:     }
                   3548:     foreach my $partid (@partid) {
1.324     albertel 3549: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3550: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3551: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3552: 	    '</th>';
1.54      albertel 3553: 
1.44      ng       3554:     }
1.477     albertel 3555:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3556: 	&Apache::loncommon::start_data_table_header_row().
                   3557: 	$header.
                   3558: 	&Apache::loncommon::end_data_table_header_row();
                   3559:     my @noupdate;
1.126     ng       3560:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3561:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3562: 	my $line;
1.257     albertel 3563: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3564: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3565: 	my %newrecord;
                   3566: 	my $updateflag = 0;
1.281     albertel 3567: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3568: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3569: 	if (!&canmodify($usec)) {
1.126     ng       3570: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3571: 	    push(@noupdate,
1.478     albertel 3572: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3573: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3574: 	    next;
                   3575: 	}
1.269     raeburn  3576:         my %aggregate = ();
                   3577:         my $aggregateflag = 0;
1.281     albertel 3578: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3579: 	foreach (@partid) {
1.257     albertel 3580: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3581: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3582: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3583: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3584: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3585: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3586: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3587: 	    my $score;
                   3588: 	    if ($partial eq '') {
1.257     albertel 3589: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3590: 	    } elsif ($partial > 0) {
                   3591: 		$score = 'correct_by_override';
                   3592: 	    } elsif ($partial == 0) {
                   3593: 		$score = 'incorrect_by_override';
                   3594: 	    }
1.257     albertel 3595: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3596: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3597: 
1.292     albertel 3598: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3599: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3600: 	    if ($dropMenu eq 'reset status' &&
                   3601: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3602: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3603: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3604: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3605: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3606: 		$updateflag = 1;
1.269     raeburn  3607:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3608:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3609:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3610:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3611:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3612:                     $aggregateflag = 1;
                   3613:                 }
1.139     albertel 3614: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3615: 		$updateflag = 1;
                   3616: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3617: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3618: 		$rec_update++;
1.125     ng       3619: 	    }
                   3620: 
1.93      albertel 3621: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3622: 		'<td align="center">'.$awarded.
                   3623: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3624: 
1.54      albertel 3625: 
                   3626: 	    my $partid=$_;
                   3627: 	    foreach my $stores (@parts) {
                   3628: 		my ($part,$type) = &split_part_type($stores);
                   3629: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3630: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3631: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3632: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3633: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3634: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3635: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3636: 		    $updateflag=1;
                   3637: 		}
1.93      albertel 3638: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3639: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3640: 	    }
1.44      ng       3641: 	}
1.477     albertel 3642: 	$line.="\n";
1.301     albertel 3643: 
                   3644: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3645: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3646: 
1.44      ng       3647: 	if ($updateflag) {
                   3648: 	    $count++;
1.257     albertel 3649: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3650: 				    $udom,$uname);
1.301     albertel 3651: 
                   3652: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3653: 					      $cnum,$udom,$uname)) {
                   3654: 		# need to figure out if should be in queue.
                   3655: 		my %record =  
                   3656: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3657: 					     $udom,$uname);
                   3658: 		my $all_graded = 1;
                   3659: 		my $none_graded = 1;
                   3660: 		foreach my $part (@parts) {
                   3661: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3662: 			$all_graded = 0;
                   3663: 		    } else {
                   3664: 			$none_graded = 0;
                   3665: 		    }
                   3666: 		}
                   3667: 
                   3668: 		if ($all_graded || $none_graded) {
                   3669: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3670: 							   $symb,$cdom,$cnum,
                   3671: 							   $udom,$uname);
                   3672: 		}
                   3673: 	    }
                   3674: 
1.477     albertel 3675: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3676: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3677: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3678: 	    $updateCtr++;
1.93      albertel 3679: 	} else {
1.477     albertel 3680: 	    push(@noupdate,
                   3681: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3682: 	    $noupdateCtr++;
1.44      ng       3683: 	}
1.269     raeburn  3684:         if ($aggregateflag) {
                   3685:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3686: 				  $cdom,$cnum);
1.269     raeburn  3687:         }
1.93      albertel 3688:     }
1.477     albertel 3689:     if (@noupdate) {
1.126     ng       3690: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3691: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3692: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3693: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3694: 	    &mt('No Changes Occurred For the Students Below').
                   3695: 	    '</td>'.
1.477     albertel 3696: 	    &Apache::loncommon::end_data_table_row();
                   3697: 	foreach my $line (@noupdate) {
                   3698: 	    $result.=
                   3699: 		&Apache::loncommon::start_data_table_row().
                   3700: 		$line.
                   3701: 		&Apache::loncommon::end_data_table_row();
                   3702: 	}
1.44      ng       3703:     }
1.477     albertel 3704:     $result .= &Apache::loncommon::end_data_table().
                   3705: 	&show_grading_menu_form($symb);
1.478     albertel 3706:     my $msg = '<p><b>'.
                   3707: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3708: 	    $rec_update,$count).'</b><br />'.
                   3709: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3710: 	'</b></p>';
1.44      ng       3711:     return $title.$msg.$result;
1.5       albertel 3712: }
1.54      albertel 3713: 
                   3714: sub split_part_type {
                   3715:     my ($partstr) = @_;
                   3716:     my ($temp,@allparts)=split(/_/,$partstr);
                   3717:     my $type=pop(@allparts);
1.439     albertel 3718:     my $part=join('_',@allparts);
1.54      albertel 3719:     return ($part,$type);
                   3720: }
                   3721: 
1.44      ng       3722: #------------- end of section for handling grading by section/class ---------
                   3723: #
                   3724: #----------------------------------------------------------------------------
                   3725: 
1.5       albertel 3726: 
1.44      ng       3727: #----------------------------------------------------------------------------
                   3728: #
                   3729: #-------------------------- Next few routines handles grading by csv upload
                   3730: #
                   3731: #--- Javascript to handle csv upload
1.27      albertel 3732: sub csvupload_javascript_reverse_associate {
1.573     bisitz   3733:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3734:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3735:   return(<<ENDPICK);
                   3736:   function verify(vf) {
                   3737:     var foundsomething=0;
                   3738:     var founduname=0;
1.243     albertel 3739:     var foundID=0;
1.27      albertel 3740:     for (i=0;i<=vf.nfields.value;i++) {
                   3741:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3742:       if (i==0 && tw!=0) { foundID=1; }
                   3743:       if (i==1 && tw!=0) { founduname=1; }
                   3744:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3745:     }
1.246     albertel 3746:     if (founduname==0 && foundID==0) {
                   3747: 	alert('$error1');
                   3748: 	return;
1.27      albertel 3749:     }
                   3750:     if (foundsomething==0) {
1.246     albertel 3751: 	alert('$error2');
                   3752: 	return;
1.27      albertel 3753:     }
                   3754:     vf.submit();
                   3755:   }
                   3756:   function flip(vf,tf) {
                   3757:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3758:     var i;
                   3759:     for (i=0;i<=vf.nfields.value;i++) {
                   3760:       //can not pick the same destination field for both name and domain
                   3761:       if (((i ==0)||(i ==1)) && 
                   3762:           ((tf==0)||(tf==1)) && 
                   3763:           (i!=tf) &&
                   3764:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3765:         eval('vf.f'+i+'.selectedIndex=0;')
                   3766:       }
                   3767:     }
                   3768:   }
                   3769: ENDPICK
                   3770: }
                   3771: 
                   3772: sub csvupload_javascript_forward_associate {
1.573     bisitz   3773:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3774:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3775:   return(<<ENDPICK);
                   3776:   function verify(vf) {
                   3777:     var foundsomething=0;
                   3778:     var founduname=0;
1.243     albertel 3779:     var foundID=0;
1.27      albertel 3780:     for (i=0;i<=vf.nfields.value;i++) {
                   3781:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3782:       if (tw==1) { foundID=1; }
                   3783:       if (tw==2) { founduname=1; }
                   3784:       if (tw>3) { foundsomething=1; }
1.27      albertel 3785:     }
1.246     albertel 3786:     if (founduname==0 && foundID==0) {
                   3787: 	alert('$error1');
                   3788: 	return;
1.27      albertel 3789:     }
                   3790:     if (foundsomething==0) {
1.246     albertel 3791: 	alert('$error2');
                   3792: 	return;
1.27      albertel 3793:     }
                   3794:     vf.submit();
                   3795:   }
                   3796:   function flip(vf,tf) {
                   3797:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3798:     var i;
                   3799:     //can not pick the same destination field twice
                   3800:     for (i=0;i<=vf.nfields.value;i++) {
                   3801:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3802:         eval('vf.f'+i+'.selectedIndex=0;')
                   3803:       }
                   3804:     }
                   3805:   }
                   3806: ENDPICK
                   3807: }
                   3808: 
1.26      albertel 3809: sub csvuploadmap_header {
1.324     albertel 3810:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3811:     my $javascript;
1.257     albertel 3812:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3813: 	$javascript=&csvupload_javascript_reverse_associate();
                   3814:     } else {
                   3815: 	$javascript=&csvupload_javascript_forward_associate();
                   3816:     }
1.45      ng       3817: 
1.324     albertel 3818:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3819:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3820:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3821:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3822:     $request->print(<<ENDPICK);
1.26      albertel 3823: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3824: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3825: $result
1.326     albertel 3826: <hr />
1.26      albertel 3827: <h3>Identify fields</h3>
                   3828: Total number of records found in file: $distotal <hr />
                   3829: Enter as many fields as you can. The system will inform you and bring you back
                   3830: to this page if the data selected is insufficient to run your class.<hr />
                   3831: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3832: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3833: <input type="hidden" name="associate"  value="" />
                   3834: <input type="hidden" name="phase"      value="three" />
                   3835: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3836: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3837: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3838: <input type="hidden" name="upfile_associate" 
1.257     albertel 3839:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3840: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3841: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3842: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3843: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3844: <hr />
                   3845: <script type="text/javascript" language="Javascript">
                   3846: $javascript
                   3847: </script>
                   3848: ENDPICK
1.118     ng       3849:     return '';
1.26      albertel 3850: 
                   3851: }
                   3852: 
                   3853: sub csvupload_fields {
1.574.2.7  raeburn  3854:     my ($symb,$errorref) = @_;
                   3855:     my (@parts) = &getpartlist($symb,$errorref);
                   3856:     if (ref($errorref)) {
                   3857:         if ($$errorref) {
                   3858:             return;
                   3859:         }
                   3860:     }
                   3861: 
1.556     weissno  3862:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 3863: 		['username','Student Username'],
                   3864: 		['domain','Student Domain']);
1.324     albertel 3865:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3866:     foreach my $part (sort(@parts)) {
                   3867: 	my @datum;
                   3868: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3869: 	my $name=$part;
                   3870: 	if  (!$display) { $display = $name; }
                   3871: 	@datum=($name,$display);
1.244     albertel 3872: 	if ($name=~/^stores_(.*)_awarded/) {
                   3873: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3874: 	}
1.41      ng       3875: 	push(@fields,\@datum);
                   3876:     }
                   3877:     return (@fields);
1.26      albertel 3878: }
                   3879: 
                   3880: sub csvuploadmap_footer {
1.41      ng       3881:     my ($request,$i,$keyfields) =@_;
                   3882:     $request->print(<<ENDPICK);
1.26      albertel 3883: </table>
                   3884: <input type="hidden" name="nfields" value="$i" />
                   3885: <input type="hidden" name="keyfields" value="$keyfields" />
                   3886: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3887: </form>
                   3888: ENDPICK
                   3889: }
                   3890: 
1.283     albertel 3891: sub checkforfile_js {
1.539     riegler  3892:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.86      ng       3893:     my $result =<<CSVFORMJS;
                   3894: <script type="text/javascript" language="javascript">
                   3895:     function checkUpload(formname) {
                   3896: 	if (formname.upfile.value == "") {
1.539     riegler  3897: 	    alert("$alertmsg");
1.86      ng       3898: 	    return false;
                   3899: 	}
                   3900: 	formname.submit();
                   3901:     }
                   3902:     </script>
                   3903: CSVFORMJS
1.283     albertel 3904:     return $result;
                   3905: }
                   3906: 
                   3907: sub upcsvScores_form {
                   3908:     my ($request) = shift;
1.324     albertel 3909:     my ($symb)=&get_symb($request);
1.283     albertel 3910:     if (!$symb) {return '';}
                   3911:     my $result=&checkforfile_js();
1.257     albertel 3912:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3913:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3914:     $result.=$table;
1.326     albertel 3915:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3916:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 3917:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
                   3918: 	'</b></td></tr>'."\n";
1.86      ng       3919:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3920:     my $upload=&mt("Upload Scores");
1.86      ng       3921:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3922:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3923:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3924:     $result.=<<ENDUPFORM;
1.106     albertel 3925: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3926: <input type="hidden" name="symb" value="$symb" />
                   3927: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3928: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3929: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3930: $upfile_select
1.370     www      3931: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3932: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3933: </form>
                   3934: ENDUPFORM
1.370     www      3935:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3936:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3937:     .'</td></tr></table>'."\n";
1.86      ng       3938:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3939:     $result.=&show_grading_menu_form($symb);
1.86      ng       3940:     return $result;
                   3941: }
                   3942: 
                   3943: 
1.26      albertel 3944: sub csvuploadmap {
1.41      ng       3945:     my ($request)= @_;
1.324     albertel 3946:     my ($symb)=&get_symb($request);
1.41      ng       3947:     if (!$symb) {return '';}
1.72      ng       3948: 
1.41      ng       3949:     my $datatoken;
1.257     albertel 3950:     if (!$env{'form.datatoken'}) {
1.41      ng       3951: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3952:     } else {
1.257     albertel 3953: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3954: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3955:     }
1.41      ng       3956:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3957:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3958:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3959:     my ($i,$keyfields);
                   3960:     if (@records) {
1.574.2.7  raeburn  3961:         my $fieldserror;
                   3962:         my @fields=&csvupload_fields($symb,\$fieldserror);
                   3963:         if ($fieldserror) {
                   3964:             $request->print(&navmap_errormsg());
                   3965:             return;
                   3966:         }
1.257     albertel 3967: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3968: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3969: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3970: 							  \@fields);
                   3971: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3972: 	    chop($keyfields);
                   3973: 	} else {
                   3974: 	    unshift(@fields,['none','']);
                   3975: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3976: 							    \@fields);
1.311     banghart 3977:             foreach my $rec (@records) {
                   3978:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3979:                 if (%temp) {
                   3980:                     $keyfields=join(',',sort(keys(%temp)));
                   3981:                     last;
                   3982:                 }
                   3983:             }
1.41      ng       3984: 	}
                   3985:     }
                   3986:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3987:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3988: 
1.41      ng       3989:     return '';
1.27      albertel 3990: }
                   3991: 
1.246     albertel 3992: sub csvuploadoptions {
1.41      ng       3993:     my ($request)= @_;
1.324     albertel 3994:     my ($symb)=&get_symb($request);
1.257     albertel 3995:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3996:     my $ignore=&mt('Ignore First Line');
                   3997:     $request->print(<<ENDPICK);
                   3998: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3999: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 4000: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 4001: <!--
1.246     albertel 4002: <p>
                   4003: <label>
                   4004:    <input type="checkbox" name="show_full_results" />
                   4005:    Show a table of all changes
                   4006: </label>
                   4007: </p>
1.302     albertel 4008: -->
1.246     albertel 4009: <p>
                   4010: <label>
                   4011:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   4012:    Overwrite any existing score
                   4013: </label>
                   4014: </p>
                   4015: ENDPICK
                   4016:     my %fields=&get_fields();
                   4017:     if (!defined($fields{'domain'})) {
1.257     albertel 4018: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 4019: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   4020:     }
1.257     albertel 4021:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4022: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4023: 	my $cleankey=$1;
                   4024: 	if ($cleankey eq 'command') { next; }
                   4025: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4026: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4027:     }
                   4028:     # FIXME do a check for any duplicated user ids...
                   4029:     # FIXME do a check for any invalid user ids?...
1.290     albertel 4030:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   4031: <hr /></form>'."\n");
1.324     albertel 4032:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 4033:     return '';
                   4034: }
                   4035: 
                   4036: sub get_fields {
                   4037:     my %fields;
1.257     albertel 4038:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4039:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4040: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4041: 	    if ($env{'form.f'.$i} ne 'none') {
                   4042: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4043: 	    }
                   4044: 	} else {
1.257     albertel 4045: 	    if ($env{'form.f'.$i} ne 'none') {
                   4046: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4047: 	    }
                   4048: 	}
1.27      albertel 4049:     }
1.246     albertel 4050:     return %fields;
                   4051: }
                   4052: 
                   4053: sub csvuploadassign {
                   4054:     my ($request)= @_;
1.324     albertel 4055:     my ($symb)=&get_symb($request);
1.246     albertel 4056:     if (!$symb) {return '';}
1.345     bowersj2 4057:     my $error_msg = '';
1.246     albertel 4058:     &Apache::loncommon::load_tmp_file($request);
                   4059:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 4060:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 4061:     my %fields=&get_fields();
1.41      ng       4062:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 4063:     my $courseid=$env{'request.course.id'};
1.97      albertel 4064:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4065:     my @notallowed;
1.41      ng       4066:     my @skipped;
                   4067:     my $countdone=0;
                   4068:     foreach my $grade (@gradedata) {
                   4069: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4070: 	my $domain;
                   4071: 	if ($entries{$fields{'domain'}}) {
                   4072: 	    $domain=$entries{$fields{'domain'}};
                   4073: 	} else {
1.257     albertel 4074: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4075: 	}
1.243     albertel 4076: 	$domain=~s/\s//g;
1.41      ng       4077: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4078: 	$username=~s/\s//g;
1.243     albertel 4079: 	if (!$username) {
                   4080: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4081: 	    $id=~s/\s//g;
1.243     albertel 4082: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4083: 	    $username=$ids{$id};
                   4084: 	}
1.41      ng       4085: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4086: 	    my $id=$entries{$fields{'ID'}};
                   4087: 	    $id=~s/\s//g;
                   4088: 	    if ($id) {
                   4089: 		push(@skipped,"$id:$domain");
                   4090: 	    } else {
                   4091: 		push(@skipped,"$username:$domain");
                   4092: 	    }
1.41      ng       4093: 	    next;
                   4094: 	}
1.108     albertel 4095: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4096: 	if (!&canmodify($usec)) {
                   4097: 	    push(@notallowed,"$username:$domain");
                   4098: 	    next;
                   4099: 	}
1.244     albertel 4100: 	my %points;
1.41      ng       4101: 	my %grades;
                   4102: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4103: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4104: 		$dest eq 'domain') { next; }
                   4105: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4106: 	    if ($dest=~/stores_(.*)_points/) {
                   4107: 		my $part=$1;
                   4108: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4109: 					      $symb,$domain,$username);
1.345     bowersj2 4110:                 if ($wgt) {
                   4111:                     $entries{$fields{$dest}}=~s/\s//g;
                   4112:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4113:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4114:                                           : 'correct_by_override';
1.345     bowersj2 4115:                     $grades{"resource.$part.awarded"}=$pcr;
                   4116:                     $grades{"resource.$part.solved"}=$award;
                   4117:                     $points{$part}=1;
                   4118:                 } else {
                   4119:                     $error_msg = "<br />" .
                   4120:                         &mt("Some point values were assigned"
                   4121:                             ." for problems with a weight "
                   4122:                             ."of zero. These values were "
                   4123:                             ."ignored.");
                   4124:                 }
1.244     albertel 4125: 	    } else {
                   4126: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4127: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4128: 		my $store_key=$dest;
                   4129: 		$store_key=~s/^stores/resource/;
                   4130: 		$store_key=~s/_/\./g;
                   4131: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4132: 	    }
1.41      ng       4133: 	}
1.508     www      4134: 	if (! %grades) { 
                   4135:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4136:         } else {
                   4137: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4138: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4139: 					   $env{'request.course.id'},
                   4140: 					   $domain,$username);
1.508     www      4141: 	   if ($result eq 'ok') {
                   4142: 	      $request->print('.');
                   4143: 	   } else {
                   4144: 	      $request->print("<p><span class=\"LC_error\">".
                   4145:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4146:                                   "$username:$domain",$result)."</span></p>");
                   4147: 	   }
                   4148: 	   $request->rflush();
                   4149: 	   $countdone++;
                   4150:         }
1.41      ng       4151:     }
1.570     www      4152:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.41      ng       4153:     if (@skipped) {
1.571     www      4154: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4155:         $request->print(join(', ',@skipped));
1.106     albertel 4156:     }
                   4157:     if (@notallowed) {
1.571     www      4158: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4159: 	$request->print(join(', ',@notallowed));
1.41      ng       4160:     }
1.106     albertel 4161:     $request->print("<br />\n");
1.324     albertel 4162:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 4163:     return $error_msg;
1.26      albertel 4164: }
1.44      ng       4165: #------------- end of section for handling csv file upload ---------
                   4166: #
                   4167: #-------------------------------------------------------------------
                   4168: #
1.122     ng       4169: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4170: #
                   4171: #--- Select a page/sequence and a student to grade
1.68      ng       4172: sub pickStudentPage {
                   4173:     my ($request) = shift;
                   4174: 
1.539     riegler  4175:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.68      ng       4176:     $request->print(<<LISTJAVASCRIPT);
                   4177: <script type="text/javascript" language="javascript">
                   4178: 
                   4179: function checkPickOne(formname) {
1.76      ng       4180:     if (radioSelection(formname.student) == null) {
1.539     riegler  4181: 	alert("$alertmsg");
1.68      ng       4182: 	return;
                   4183:     }
1.125     ng       4184:     ptr = pullDownSelection(formname.selectpage);
                   4185:     formname.page.value = formname["page"+ptr].value;
                   4186:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4187:     formname.submit();
                   4188: }
                   4189: 
                   4190: </script>
                   4191: LISTJAVASCRIPT
1.118     ng       4192:     &commonJSfunctions($request);
1.324     albertel 4193:     my ($symb) = &get_symb($request);
1.257     albertel 4194:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4195:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4196:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4197: 
1.398     albertel 4198:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4199: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4200: 
1.80      ng       4201:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.574.2.7  raeburn  4202:     my $map_error;
                   4203:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4204:     if ($map_error) {
                   4205:         $request->print(&navmap_errormsg());
                   4206:         return;
                   4207:     }
1.137     albertel 4208:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4209: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4210: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4211:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4212:     my $ctr=0;
1.68      ng       4213:     foreach (@$titles) {
                   4214: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4215: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4216: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4217: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4218: 	$ctr++;
1.68      ng       4219:     }
1.485     albertel 4220:     $select.= '</select>';
1.539     riegler  4221:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4222: 
1.70      ng       4223:     $ctr=0;
                   4224:     foreach (@$titles) {
                   4225: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4226: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4227: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4228: 	$ctr++;
                   4229:     }
1.72      ng       4230:     $result.='<input type="hidden" name="page" />'."\n".
                   4231: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4232: 
1.485     albertel 4233:     my $options =
                   4234: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4235: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4236:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4237: 
                   4238:     $options =
                   4239: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4240: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4241: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4242:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4243:     
                   4244:     $result.=&build_section_inputs();
1.442     banghart 4245:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4246:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4247: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4248: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4249: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4250: 
1.539     riegler  4251:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4252: 
1.80      ng       4253:     $result.='&nbsp;<input type="button" '.
1.539     riegler  4254: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4255: 
1.68      ng       4256:     $request->print($result);
                   4257: 
1.485     albertel 4258:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4259: 	&Apache::loncommon::start_data_table().
                   4260: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4261: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4262: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4263: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4264: 	'<th>'.&nameUserString('header').'</th>'.
                   4265: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4266:  
1.76      ng       4267:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4268:     my $ptr = 1;
1.294     albertel 4269:     foreach my $student (sort 
                   4270: 			 {
                   4271: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4272: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4273: 			     }
                   4274: 			     return $a cmp $b;
                   4275: 			 } (keys(%$fullname))) {
1.68      ng       4276: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4277: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4278:                                   : '</td>');
1.126     ng       4279: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4280: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4281: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4282: 	$studentTable.=
                   4283: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4284:                          : '');
1.68      ng       4285: 	$ptr++;
                   4286:     }
1.484     albertel 4287:     if ($ptr%2 == 0) {
                   4288: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4289: 	    &Apache::loncommon::end_data_table_row();
                   4290:     }
                   4291:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4292:     $studentTable.='<input type="button" '.
1.539     riegler  4293: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4294: 
1.324     albertel 4295:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4296:     $request->print($studentTable);
                   4297: 
                   4298:     return '';
                   4299: }
                   4300: 
                   4301: sub getSymbMap {
1.574.2.7  raeburn  4302:     my ($map_error) = @_;
1.132     bowersj2 4303:     my $navmap = Apache::lonnavmaps::navmap->new();
1.574.2.7  raeburn  4304:     unless (ref($navmap)) {
                   4305:         if (ref($map_error)) {
                   4306:             $$map_error = 'navmap';
                   4307:         }
                   4308:         return;
                   4309:     }
1.68      ng       4310:     my %symbx = ();
                   4311:     my @titles = ();
1.117     bowersj2 4312:     my $minder = 0;
                   4313: 
                   4314:     # Gather every sequence that has problems.
1.240     albertel 4315:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4316: 					       1,0,1);
1.117     bowersj2 4317:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4318: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4319: 	    my $title = $minder.'.'.
                   4320: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4321: 	    push(@titles, $title); # minder in case two titles are identical
                   4322: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4323: 	    $minder++;
1.241     albertel 4324: 	}
1.68      ng       4325:     }
                   4326:     return \@titles,\%symbx;
                   4327: }
                   4328: 
1.72      ng       4329: #
                   4330: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4331: sub displayPage {
                   4332:     my ($request) = shift;
                   4333: 
1.324     albertel 4334:     my ($symb) = &get_symb($request);
1.257     albertel 4335:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4336:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4337:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4338:     my $pageTitle = $env{'form.page'};
1.103     albertel 4339:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4340:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4341:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4342: 
                   4343:     #need to make sure we have the correct data for later EXT calls, 
                   4344:     #thus invalidate the cache
                   4345:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4346:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4347:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4348:     &Apache::lonnet::clear_EXT_cache_status();
                   4349: 
1.103     albertel 4350:     if (!&canview($usec)) {
1.485     albertel 4351: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4352: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4353: 	return;
                   4354:     }
1.398     albertel 4355:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4356:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4357: 	'</h3>'."\n";
1.500     albertel 4358:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4359:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4360: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4361:     } else {
                   4362: 	delete($env{'form.CODE'});
                   4363:     }
1.71      ng       4364:     &sub_page_js($request);
                   4365:     $request->print($result);
                   4366: 
1.132     bowersj2 4367:     my $navmap = Apache::lonnavmaps::navmap->new();
1.574.2.7  raeburn  4368:     unless (ref($navmap)) {
                   4369:         $request->print(&navmap_errormsg());
                   4370:         $request->print(&show_grading_menu_form($symb));
                   4371:         return;
                   4372:     }
1.257     albertel 4373:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4374:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4375:     if (!$map) {
1.485     albertel 4376: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.324     albertel 4377: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4378: 	return; 
                   4379:     }
1.68      ng       4380:     my $iterator = $navmap->getIterator($map->map_start(),
                   4381: 					$map->map_finish());
                   4382: 
1.71      ng       4383:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4384: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4385: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4386: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4387: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4388: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4389: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4390: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4391: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4392: 
1.382     albertel 4393:     if (defined($env{'form.CODE'})) {
                   4394: 	$studentTable.=
                   4395: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4396:     }
1.381     albertel 4397:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4398: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4399: 
1.485     albertel 4400:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
1.484     albertel 4401: 	&Apache::loncommon::start_data_table().
                   4402: 	&Apache::loncommon::start_data_table_header_row().
                   4403: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4404: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4405: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4406: 
1.329     albertel 4407:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4408:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4409:     $iterator->next(); # skip the first BEGIN_MAP
                   4410:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4411:     while ($depth > 0) {
1.68      ng       4412:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4413:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4414: 
1.385     albertel 4415:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4416: 	    my $parts = $curRes->parts();
1.68      ng       4417:             my $title = $curRes->compTitle();
1.71      ng       4418: 	    my $symbx = $curRes->symb();
1.484     albertel 4419: 	    $studentTable.=
                   4420: 		&Apache::loncommon::start_data_table_row().
                   4421: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4422: 		(scalar(@{$parts}) == 1 ? '' 
                   4423: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
                   4424: 							scalar(@{$parts}))
                   4425: 		 ).
                   4426: 		 '</td>';
1.71      ng       4427: 	    $studentTable.='<td valign="top">';
1.382     albertel 4428: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4429: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4430: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4431: 					     undef,'both',\%form);
1.71      ng       4432: 	    } else {
1.382     albertel 4433: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4434: 		$companswer =~ s|<form(.*?)>||g;
                   4435: 		$companswer =~ s|</form>||g;
1.71      ng       4436: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4437: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4438: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4439: #		}
1.116     ng       4440: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4441: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4442: 	    }
                   4443: 
1.257     albertel 4444: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4445: 
1.257     albertel 4446: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4447: 		if ($record{'version'} eq '') {
1.485     albertel 4448: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4449: 		} else {
1.116     ng       4450: 		    my %responseType = ();
                   4451: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4452: 			my @responseIds =$curRes->responseIds($partid);
                   4453: 			my @responseType =$curRes->responseType($partid);
                   4454: 			my %responseIds;
                   4455: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4456: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4457: 			}
                   4458: 			$responseType{$partid} = \%responseIds;
1.116     ng       4459: 		    }
1.148     albertel 4460: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4461: 
1.71      ng       4462: 		}
1.257     albertel 4463: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4464: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4465: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4466: 									$env{'request.course.id'},
1.71      ng       4467: 									'','.submission');
                   4468:  
                   4469: 	    }
1.103     albertel 4470: 	    if (&canmodify($usec)) {
                   4471: 		foreach my $partid (@{$parts}) {
                   4472: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4473: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4474: 		    $question++;
                   4475: 		}
1.196     albertel 4476: 		$prob++;
1.71      ng       4477: 	    }
                   4478: 	    $studentTable.='</td></tr>';
1.68      ng       4479: 
1.103     albertel 4480: 	}
1.68      ng       4481:         $curRes = $iterator->next();
                   4482:     }
                   4483: 
1.485     albertel 4484:     $studentTable.='</table>'."\n".
                   4485: 	'<input type="button" value="'.&mt('Save').'" '.
1.381     albertel 4486: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4487: 	'</form>'."\n";
1.324     albertel 4488:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4489:     $request->print($studentTable);
                   4490: 
                   4491:     return '';
1.119     ng       4492: }
                   4493: 
                   4494: sub displaySubByDates {
1.148     albertel 4495:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4496:     my $isCODE=0;
1.335     albertel 4497:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4498:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4499:     my $studentTable=&Apache::loncommon::start_data_table().
                   4500: 	&Apache::loncommon::start_data_table_header_row().
                   4501: 	'<th>'.&mt('Date/Time').'</th>'.
                   4502: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4503: 	'<th>'.&mt('Submission').'</th>'.
                   4504: 	'<th>'.&mt('Status').'</th>'.
                   4505: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4506:     my ($version);
                   4507:     my %mark;
1.148     albertel 4508:     my %orders;
1.119     ng       4509:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4510:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4511: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4512:     }
1.335     albertel 4513: 
                   4514:     my $interaction;
1.525     raeburn  4515:     my $no_increment = 1;
1.119     ng       4516:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4517: 	my $timestamp = 
                   4518: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4519: 	if (exists($$record{$version.':resource.0.version'})) {
                   4520: 	    $interaction = $$record{$version.':resource.0.version'};
                   4521: 	}
                   4522: 
                   4523: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4524: 		             : "$version:resource");
1.467     albertel 4525: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4526: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4527: 	if ($isCODE) {
                   4528: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4529: 	}
1.119     ng       4530: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4531: 	my @displaySub = ();
                   4532: 	foreach my $partid (@{$parts}) {
1.335     albertel 4533: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4534: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4535: 	    
                   4536: 
1.122     ng       4537: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4538: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4539: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4540: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4541: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4542: 
                   4543: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4544: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.467     albertel 4545: 		    $displaySub[0].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.'&nbsp;';
                   4546: 		    $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').'&nbsp;'.
1.398     albertel 4547: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4548: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.467     albertel 4549: 			$displaySub[0].=&mt('Trial&nbsp;not&nbsp;counted');
1.147     albertel 4550: 		    } else {
1.467     albertel 4551: 			$displaySub[0].=&mt('Trial&nbsp;[_1]',
                   4552: 					    $$record{"$where.$partid.tries"});
1.147     albertel 4553: 		    }
1.335     albertel 4554: 		    my $responseType=($isTask ? 'Task'
                   4555:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4556: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4557: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4558: 			$orders{$partid}->{$responseId}=
1.525     raeburn  4559: 			    &get_order($partid,$responseId,$symb,$uname,$udom,
                   4560:                                        $no_increment);
1.148     albertel 4561: 		    }
1.147     albertel 4562: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4563: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4564: 		}
                   4565: 	    }
1.335     albertel 4566: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4567: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4568: 				    $$record{"$where.$partid.checkedin"},
                   4569: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4570: 					'<br />';
1.335     albertel 4571: 	    }
                   4572: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4573: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4574: 		    lc($$record{"$where.$partid.award"}).' '.
                   4575: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4576: 		    '<br />';
                   4577: 	    }
1.335     albertel 4578: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4579: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4580: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4581: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4582: 		$displaySub[2].=
                   4583: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4584: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4585: 	    }
                   4586: 	}
                   4587: 	# needed because old essay regrader has not parts info
                   4588: 	if (exists $$record{"$version:resource.regrader"}) {
                   4589: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4590: 	}
                   4591: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4592: 	if ($displaySub[2]) {
1.467     albertel 4593: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4594: 	}
1.467     albertel 4595: 	$studentTable.='&nbsp;</td>'.
                   4596: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4597:     }
1.467     albertel 4598:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4599:     return $studentTable;
1.71      ng       4600: }
                   4601: 
                   4602: sub updateGradeByPage {
                   4603:     my ($request) = shift;
                   4604: 
1.257     albertel 4605:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4606:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4607:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4608:     my $pageTitle = $env{'form.page'};
1.103     albertel 4609:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4610:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4611:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4612:     if (!&canmodify($usec)) {
1.526     raeburn  4613: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4614: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4615: 	return;
                   4616:     }
1.398     albertel 4617:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4618:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4619: 	'</h3>'."\n";
1.70      ng       4620: 
1.68      ng       4621:     $request->print($result);
                   4622: 
1.132     bowersj2 4623:     my $navmap = Apache::lonnavmaps::navmap->new();
1.574.2.7  raeburn  4624:     unless (ref($navmap)) {
                   4625:         $request->print(&navmap_errormsg());
                   4626:         return;
                   4627:     }
1.257     albertel 4628:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4629:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4630:     if (!$map) {
1.527     raeburn  4631: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.324     albertel 4632: 	my ($symb)=&get_symb($request);
                   4633: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4634: 	return; 
                   4635:     }
1.71      ng       4636:     my $iterator = $navmap->getIterator($map->map_start(),
                   4637: 					$map->map_finish());
1.70      ng       4638: 
1.484     albertel 4639:     my $studentTable=
                   4640: 	&Apache::loncommon::start_data_table().
                   4641: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4642: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4643: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4644: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4645: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4646: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4647: 
                   4648:     $iterator->next(); # skip the first BEGIN_MAP
                   4649:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4650:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4651:     while ($depth > 0) {
1.71      ng       4652:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4653:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4654: 
1.385     albertel 4655:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4656: 	    my $parts = $curRes->parts();
1.71      ng       4657:             my $title = $curRes->compTitle();
                   4658: 	    my $symbx = $curRes->symb();
1.484     albertel 4659: 	    $studentTable.=
                   4660: 		&Apache::loncommon::start_data_table_row().
                   4661: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4662: 		(scalar(@{$parts}) == 1 ? '' 
1.526     raeburn  4663:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
                   4664: 		.')').'</td>';
1.71      ng       4665: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4666: 
                   4667: 	    my %newrecord=();
                   4668: 	    my @displayPts=();
1.269     raeburn  4669:             my %aggregate = ();
                   4670:             my $aggregateflag = 0;
1.71      ng       4671: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4672: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4673: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4674: 
1.257     albertel 4675: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4676: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4677: 		my $partial = $newpts/$wgt;
                   4678: 		my $score;
                   4679: 		if ($partial > 0) {
                   4680: 		    $score = 'correct_by_override';
1.125     ng       4681: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4682: 		    $score = 'incorrect_by_override';
                   4683: 		}
1.257     albertel 4684: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4685: 		if ($dropMenu eq 'excused') {
1.71      ng       4686: 		    $partial = '';
                   4687: 		    $score = 'excused';
1.125     ng       4688: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4689: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4690: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4691: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4692: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4693: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4694: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4695: 		    $changeflag++;
                   4696: 		    $newpts = '';
1.269     raeburn  4697:                     
                   4698:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4699:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4700:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4701:                     if ($aggtries > 0) {
                   4702:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4703:                         $aggregateflag = 1;
                   4704:                     }
1.71      ng       4705: 		}
1.324     albertel 4706: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4707: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4708: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4709: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4710: 		    '&nbsp;<br />';
1.526     raeburn  4711: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4712: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4713: 		    '&nbsp;<br />';
1.71      ng       4714: 		$question++;
1.380     albertel 4715: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4716: 
1.71      ng       4717: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4718: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4719: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4720: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4721: 
                   4722: 		$changeflag++;
                   4723: 	    }
                   4724: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4725: 		my %record = 
                   4726: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4727: 					     $udom,$uname);
                   4728: 
                   4729: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4730: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4731: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4732: 		    $newrecord{'resource.CODE'} = '';
                   4733: 		}
1.257     albertel 4734: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4735: 					$udom,$uname);
1.382     albertel 4736: 		%record = &Apache::lonnet::restore($symbx,
                   4737: 						   $env{'request.course.id'},
                   4738: 						   $udom,$uname);
1.380     albertel 4739: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4740: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4741: 	    }
1.380     albertel 4742: 	    
1.269     raeburn  4743:             if ($aggregateflag) {
                   4744:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4745:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4746:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4747:             }
1.125     ng       4748: 
1.71      ng       4749: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4750: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4751: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4752: 
1.196     albertel 4753: 	    $prob++;
1.68      ng       4754: 	}
1.71      ng       4755:         $curRes = $iterator->next();
1.68      ng       4756:     }
1.98      albertel 4757: 
1.484     albertel 4758:     $studentTable.=&Apache::loncommon::end_data_table();
1.324     albertel 4759:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.526     raeburn  4760:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4761: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4762: 		  $changeflag));
1.76      ng       4763:     $request->print($grademsg.$studentTable);
1.68      ng       4764: 
1.70      ng       4765:     return '';
                   4766: }
                   4767: 
1.72      ng       4768: #-------- end of section for handling grading by page/sequence ---------
                   4769: #
                   4770: #-------------------------------------------------------------------
                   4771: 
1.574.2.5  raeburn  4772: #--------------------Bubblesheet (Scantron) Grading-----------------------------------
1.75      albertel 4773: #
                   4774: #------ start of section for handling grading by page/sequence ---------
                   4775: 
1.423     albertel 4776: =pod
                   4777: 
                   4778: =head1 Bubble sheet grading routines
                   4779: 
1.424     albertel 4780:   For this documentation:
                   4781: 
                   4782:    'scanline' refers to the full line of characters
                   4783:    from the file that we are parsing that represents one entire sheet
                   4784: 
                   4785:    'bubble line' refers to the data
                   4786:    representing the line of bubbles that are on the physical bubble sheet
                   4787: 
                   4788: 
                   4789: The overall process is that a scanned in bubble sheet data is uploaded
                   4790: into a course. When a user wants to grade, they select a
                   4791: sequence/folder of resources, a file of bubble sheet info, and pick
                   4792: one of the predefined configurations for what each scanline looks
                   4793: like.
                   4794: 
                   4795: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4796: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4797: because too light bubbling), 'double bubble' (each bubble line should
                   4798: have no more that one letter picked), invalid or duplicated CODE,
1.556     weissno  4799: invalid student/employee ID
1.424     albertel 4800: 
                   4801: If the CODE option is used that determines the randomization of the
1.556     weissno  4802: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 4803: username:domain.
                   4804: 
                   4805: During the validation phase the instructor can choose to skip scanlines. 
                   4806: 
1.435     foxr     4807: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4808: 
                   4809:   scantron_original_filename (unmodified original file)
                   4810:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4811:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4812: 
                   4813: Also there is a separate hash nohist_scantrondata that contains extra
                   4814: correction information that isn't representable in the bubble sheet
                   4815: file (see &scantron_getfile() for more information)
                   4816: 
                   4817: After all scanlines are either valid, marked as valid or skipped, then
                   4818: foreach line foreach problem in the picked sequence, an ssi request is
                   4819: made that simulates a user submitting their selected letter(s) against
                   4820: the homework problem.
1.423     albertel 4821: 
                   4822: =over 4
                   4823: 
                   4824: 
                   4825: 
                   4826: =item defaultFormData
                   4827: 
                   4828:   Returns html hidden inputs used to hold context/default values.
                   4829: 
                   4830:  Arguments:
1.574.2.7  raeburn  4831:    $symb - $symb of the current resource
                   4832:    $map_error - ref to scalar which will container error if
                   4833:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 4834: 
                   4835: =cut
1.422     foxr     4836: 
1.81      albertel 4837: sub defaultFormData {
1.324     albertel 4838:     my ($symb)=@_;
1.447     foxr     4839:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4840:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4841:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4842: }
                   4843: 
1.447     foxr     4844: 
1.423     albertel 4845: =pod 
                   4846: 
                   4847: =item getSequenceDropDown
                   4848: 
                   4849:    Return html dropdown of possible sequences to grade
                   4850:  
                   4851:  Arguments:
                   4852:    $symb - $symb of the current resource 
                   4853: 
                   4854: =cut
1.422     foxr     4855: 
1.75      albertel 4856: sub getSequenceDropDown {
1.574.2.7  raeburn  4857:     my ($symb,$map_error)=@_;
1.75      albertel 4858:     my $result='<select name="selectpage">'."\n";
1.574.2.7  raeburn  4859:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4860:     if (ref($map_error)) {
                   4861:         return if ($$map_error);
                   4862:     }
1.137     albertel 4863:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4864:     my $ctr=0;
                   4865:     foreach (@$titles) {
                   4866: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4867: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4868: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4869: 	    '>'.$showtitle.'</option>'."\n";
                   4870: 	$ctr++;
                   4871:     }
                   4872:     $result.= '</select>';
                   4873:     return $result;
                   4874: }
                   4875: 
1.495     albertel 4876: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  4877:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 4878: 
                   4879: my %first_bubble_line;             # First bubble line no. for each bubble.
                   4880: 
1.509     raeburn  4881: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   4882:                                    # matchresponse or rankresponse, where 
                   4883:                                    # an individual response can have multiple 
                   4884:                                    # lines
1.503     raeburn  4885: 
                   4886: my %responsetype_per_response;     # responsetype for each response
                   4887: 
1.495     albertel 4888: # Save and restore the bubble lines array to the form env.
                   4889: 
                   4890: 
                   4891: sub save_bubble_lines {
                   4892:     foreach my $line (keys(%bubble_lines_per_response)) {
                   4893: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   4894: 	$env{"form.scantron.first_bubble_line.$line"} =
                   4895: 	    $first_bubble_line{$line};
1.503     raeburn  4896:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   4897:             $subdivided_bubble_lines{$line};
                   4898:         $env{"form.scantron.responsetype.$line"} =
                   4899:             $responsetype_per_response{$line};
1.495     albertel 4900:     }
                   4901: }
                   4902: 
                   4903: 
                   4904: sub restore_bubble_lines {
                   4905:     my $line = 0;
                   4906:     %bubble_lines_per_response = ();
                   4907:     while ($env{"form.scantron.bubblelines.$line"}) {
                   4908: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   4909: 	$bubble_lines_per_response{$line} = $value;
                   4910: 	$first_bubble_line{$line}  =
                   4911: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  4912:         $subdivided_bubble_lines{$line} =
                   4913:             $env{"form.scantron.sub_bubblelines.$line"};
                   4914:         $responsetype_per_response{$line} =
                   4915:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 4916: 	$line++;
                   4917:     }
                   4918: }
                   4919: 
                   4920: #  Given the parsed scanline, get the response for 
                   4921: #  'answer' number n:
                   4922: 
                   4923: sub get_response_bubbles {
                   4924:     my ($parsed_line, $response)  = @_;
                   4925: 
                   4926:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   4927:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   4928:     
                   4929:     my $selected = "";
                   4930: 
                   4931:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   4932: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   4933: 	$bubble_line++;
                   4934:     }
                   4935:     return $selected;
                   4936: }
1.423     albertel 4937: 
                   4938: =pod 
                   4939: 
                   4940: =item scantron_filenames
                   4941: 
                   4942:    Returns a list of the scantron files in the current course 
                   4943: 
                   4944: =cut
1.422     foxr     4945: 
1.202     albertel 4946: sub scantron_filenames {
1.257     albertel 4947:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4948:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  4949:     my $getpropath = 1;
1.157     albertel 4950:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  4951:                                        $getpropath);
1.202     albertel 4952:     my @possiblenames;
1.201     albertel 4953:     foreach my $filename (sort(@files)) {
1.157     albertel 4954: 	($filename)=split(/&/,$filename);
                   4955: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4956: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4957: 	push(@possiblenames,$filename);
                   4958:     }
                   4959:     return @possiblenames;
                   4960: }
                   4961: 
1.423     albertel 4962: =pod 
                   4963: 
                   4964: =item scantron_uploads
                   4965: 
                   4966:    Returns  html drop-down list of scantron files in current course.
                   4967: 
                   4968:  Arguments:
                   4969:    $file2grade - filename to set as selected in the dropdown
                   4970: 
                   4971: =cut
1.422     foxr     4972: 
1.202     albertel 4973: sub scantron_uploads {
1.209     ng       4974:     my ($file2grade) = @_;
1.202     albertel 4975:     my $result=	'<select name="scantron_selectfile">';
                   4976:     $result.="<option></option>";
                   4977:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4978: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4979:     }
                   4980:     $result.="</select>";
                   4981:     return $result;
                   4982: }
                   4983: 
1.423     albertel 4984: =pod 
                   4985: 
                   4986: =item scantron_scantab
                   4987: 
                   4988:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4989:   file.
                   4990: 
                   4991: =cut
1.422     foxr     4992: 
1.82      albertel 4993: sub scantron_scantab {
                   4994:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4995:     $result.='<option></option>'."\n";
1.518     raeburn  4996:     my @lines = &get_scantronformat_file();
                   4997:     if (@lines > 0) {
                   4998:         foreach my $line (@lines) {
                   4999:             next if (($line =~ /^\#/) || ($line eq ''));
                   5000: 	    my ($name,$descrip)=split(/:/,$line);
                   5001: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5002:         }
1.82      albertel 5003:     }
                   5004:     $result.='</select>'."\n";
1.518     raeburn  5005:     return $result;
                   5006: }
                   5007: 
                   5008: =pod
                   5009: 
                   5010: =item get_scantronformat_file
                   5011: 
                   5012:   Returns an array containing lines from the scantron format file for
                   5013:   the domain of the course.
                   5014: 
                   5015:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5016:   lines are from this file.
                   5017: 
                   5018:   Otherwise, if a default.tab has been published in RES space by the 
                   5019:   domainconfig user, lines are from this file.
                   5020: 
                   5021:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5022:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5023: 
1.518     raeburn  5024: =cut
                   5025: 
                   5026: sub get_scantronformat_file {
                   5027:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5028:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5029:     my $gottab = 0;
                   5030:     my @lines;
                   5031:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5032:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5033:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5034:             if ($formatfile ne '-1') {
                   5035:                 @lines = split("\n",$formatfile,-1);
                   5036:                 $gottab = 1;
                   5037:             }
                   5038:         }
                   5039:     }
                   5040:     if (!$gottab) {
                   5041:         my $confname = $cdom.'-domainconfig';
                   5042:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5043:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5044:         if ($formatfile ne '-1') {
                   5045:             @lines = split("\n",$formatfile,-1);
                   5046:             $gottab = 1;
                   5047:         }
                   5048:     }
                   5049:     if (!$gottab) {
1.519     raeburn  5050:         my @domains = &Apache::lonnet::current_machine_domains();
                   5051:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5052:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5053:             @lines = <$fh>;
                   5054:             close($fh);
                   5055:         } else {
                   5056:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5057:             @lines = <$fh>;
                   5058:             close($fh);
                   5059:         }
1.518     raeburn  5060:     }
                   5061:     return @lines;
1.82      albertel 5062: }
                   5063: 
1.423     albertel 5064: =pod 
                   5065: 
                   5066: =item scantron_CODElist
                   5067: 
                   5068:   Returns html drop down of the saved CODE lists from current course,
                   5069:   generated from earlier printings.
                   5070: 
                   5071: =cut
1.422     foxr     5072: 
1.186     albertel 5073: sub scantron_CODElist {
1.257     albertel 5074:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5075:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5076:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5077:     my $namechoice='<option></option>';
1.225     albertel 5078:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5079: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5080: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5081: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5082:     }
                   5083:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5084:     return $namechoice;
                   5085: }
                   5086: 
1.423     albertel 5087: =pod 
                   5088: 
                   5089: =item scantron_CODEunique
                   5090: 
                   5091:   Returns the html for "Each CODE to be used once" radio.
                   5092: 
                   5093: =cut
1.422     foxr     5094: 
1.186     albertel 5095: sub scantron_CODEunique {
1.532     bisitz   5096:     my $result='<span class="LC_nobreak">
1.272     albertel 5097:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5098:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5099:                 </span>
1.532     bisitz   5100:                 <span class="LC_nobreak">
1.272     albertel 5101:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5102:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5103:                 </span>';
1.186     albertel 5104:     return $result;
                   5105: }
1.423     albertel 5106: 
                   5107: =pod 
                   5108: 
                   5109: =item scantron_selectphase
                   5110: 
                   5111:   Generates the initial screen to start the bubble sheet process.
                   5112:   Allows for - starting a grading run.
1.424     albertel 5113:              - downloading existing scan data (original, corrected
1.423     albertel 5114:                                                 or skipped info)
                   5115: 
                   5116:              - uploading new scan data
                   5117: 
                   5118:  Arguments:
                   5119:   $r          - The Apache request object
                   5120:   $file2grade - name of the file that contain the scanned data to score
                   5121: 
                   5122: =cut
1.186     albertel 5123: 
1.75      albertel 5124: sub scantron_selectphase {
1.209     ng       5125:     my ($r,$file2grade) = @_;
1.324     albertel 5126:     my ($symb)=&get_symb($r);
1.75      albertel 5127:     if (!$symb) {return '';}
1.574.2.7  raeburn  5128:     my $map_error;
                   5129:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5130:     if ($map_error) {
                   5131:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5132:         return;
                   5133:     }
1.324     albertel 5134:     my $default_form_data=&defaultFormData($symb);
                   5135:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       5136:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5137:     my $format_selector=&scantron_scantab();
1.186     albertel 5138:     my $CODE_selector=&scantron_CODElist();
                   5139:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5140:     my $result;
1.422     foxr     5141: 
1.513     foxr     5142:     $ssi_error = 0;
                   5143: 
1.422     foxr     5144:     # Chunk of form to prompt for a file to grade and how:
                   5145: 
1.489     albertel 5146:     $result.= '
                   5147:     <br />
                   5148:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5149:     <input type="hidden" name="command" value="scantron_warning" />
                   5150:     '.$default_form_data.'
                   5151:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5152:        '.&Apache::loncommon::start_data_table_header_row().'
                   5153:             <th colspan="2">
1.492     albertel 5154:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5155:             </th>
                   5156:        '.&Apache::loncommon::end_data_table_header_row().'
                   5157:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5158:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5159:        '.&Apache::loncommon::end_data_table_row().'
                   5160:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5161:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5162:        '.&Apache::loncommon::end_data_table_row().'
                   5163:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5164:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5165:        '.&Apache::loncommon::end_data_table_row().'
                   5166:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5167:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5168:        '.&Apache::loncommon::end_data_table_row().'
                   5169:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5170:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5171:        '.&Apache::loncommon::end_data_table_row().'
                   5172:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5173: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5174:             <td>
1.492     albertel 5175: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5176:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5177:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5178: 	    </td>
1.489     albertel 5179:        '.&Apache::loncommon::end_data_table_row().'
                   5180:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5181:             <td colspan="2">
1.572     www      5182:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5183:             </td>
1.489     albertel 5184:        '.&Apache::loncommon::end_data_table_row().'
                   5185:     '.&Apache::loncommon::end_data_table().'
                   5186:     </form>
                   5187: ';
1.162     albertel 5188:    
                   5189:     $r->print($result);
                   5190: 
1.257     albertel 5191:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5192:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 5193: 
1.422     foxr     5194: 	# Chunk of form to prompt for a scantron file upload.
                   5195: 
1.489     albertel 5196:         $r->print('
                   5197:     <br />
                   5198:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5199:        '.&Apache::loncommon::start_data_table_header_row().'
                   5200:             <th>
1.572     www      5201:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
1.489     albertel 5202:             </th>
                   5203:        '.&Apache::loncommon::end_data_table_header_row().'
                   5204:        '.&Apache::loncommon::start_data_table_row().'
1.162     albertel 5205:             <td>
1.489     albertel 5206: ');
1.324     albertel 5207:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 5208:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5209:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.492     albertel 5210:     $r->print('
1.174     albertel 5211:               <script type="text/javascript" language="javascript">
                   5212:     function checkUpload(formname) {
                   5213: 	if (formname.upfile.value == "") {
1.492     albertel 5214: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
1.174     albertel 5215: 	    return false;
                   5216: 	}
                   5217: 	formname.submit();
                   5218:     }
                   5219:               </script>
                   5220: 
1.492     albertel 5221:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5222:                 '.$default_form_data.'
                   5223:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5224:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5225:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5226:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
1.174     albertel 5227:                 <br />
1.572     www      5228:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.174     albertel 5229:               </form>
1.492     albertel 5230: ');
1.162     albertel 5231: 
1.489     albertel 5232:         $r->print('
1.162     albertel 5233:             </td>
1.489     albertel 5234:        '.&Apache::loncommon::end_data_table_row().'
                   5235:        '.&Apache::loncommon::end_data_table().'
                   5236: ');
1.162     albertel 5237:     }
1.422     foxr     5238: 
                   5239:     # Chunk of the form that prompts to view a scoring office file,
                   5240:     # corrected file, skipped records in a file.
                   5241: 
1.489     albertel 5242:     $r->print('
                   5243:    <br />
                   5244:    <form action="/adm/grades" name="scantron_download">
                   5245:      '.$default_form_data.'
                   5246:      <input type="hidden" name="command" value="scantron_download" />
                   5247:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5248:        '.&Apache::loncommon::start_data_table_header_row().'
                   5249:               <th>
1.492     albertel 5250:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5251:               </th>
                   5252:        '.&Apache::loncommon::end_data_table_header_row().'
                   5253:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5254:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5255:                 <br />
1.492     albertel 5256:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5257:        '.&Apache::loncommon::end_data_table_row().'
                   5258:      '.&Apache::loncommon::end_data_table().'
                   5259:    </form>
                   5260:    <br />
                   5261: ');
1.162     albertel 5262: 
1.457     banghart 5263:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5264: 
1.528     raeburn  5265:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5266:              $default_form_data."\n".
                   5267:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5268:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5269:              '<th colspan="2">
1.572     www      5270:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5271:              '</th>'."\n".
                   5272:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5273:               &Apache::loncommon::start_data_table_row()."\n".
                   5274:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5275:               '<td> '.$sequence_selector.' </td>'.
                   5276:               &Apache::loncommon::end_data_table_row()."\n".
                   5277:               &Apache::loncommon::start_data_table_row()."\n".
                   5278:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5279:               '<td> '.$file_selector.' </td>'."\n".
                   5280:               &Apache::loncommon::end_data_table_row()."\n".
                   5281:               &Apache::loncommon::start_data_table_row()."\n".
                   5282:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5283:               '<td> '.$format_selector.' </td>'."\n".
                   5284:               &Apache::loncommon::end_data_table_row()."\n".
                   5285:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5286:               '<td> '.&mt('Options').' </td>'."\n".
                   5287:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5288:               &Apache::loncommon::end_data_table_row()."\n".
                   5289:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5290:               '<td colspan="2">'."\n".
                   5291:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.574.2.5  raeburn  5292:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5293:               '</td>'."\n".
                   5294:               &Apache::loncommon::end_data_table_row()."\n".
                   5295:               &Apache::loncommon::end_data_table()."\n".
                   5296:               '</form><br />');
1.457     banghart 5297:     $r->print($grading_menu_button);
1.523     raeburn  5298:     return;
1.75      albertel 5299: }
                   5300: 
1.423     albertel 5301: =pod
                   5302: 
                   5303: =item get_scantron_config
                   5304: 
                   5305:    Parse and return the scantron configuration line selected as a
                   5306:    hash of configuration file fields.
                   5307: 
                   5308:  Arguments:
                   5309:     which - the name of the configuration to parse from the file.
                   5310: 
                   5311: 
                   5312:  Returns:
                   5313:             If the named configuration is not in the file, an empty
                   5314:             hash is returned.
                   5315:     a hash with the fields
                   5316:       name         - internal name for the this configuration setup
                   5317:       description  - text to display to operator that describes this config
                   5318:       CODElocation - if 0 or the string 'none'
                   5319:                           - no CODE exists for this config
                   5320:                      if -1 || the string 'letter'
                   5321:                           - a CODE exists for this config and is
                   5322:                             a string of letters
                   5323:                      Unsupported value (but planned for future support)
                   5324:                           if a positive integer
                   5325:                                - The CODE exists as the first n items from
                   5326:                                  the question section of the form
                   5327:                           if the string 'number'
                   5328:                                - The CODE exists for this config and is
                   5329:                                  a string of numbers
                   5330:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5331:                      the CODE starts
                   5332:       CODElength  - length of the CODE
1.573     bisitz   5333:       IDstart     - column where the student/employee ID starts
1.556     weissno  5334:       IDlength    - length of the student/employee ID info
1.423     albertel 5335:       Qstart      - column where the information from the bubbled
                   5336:                     'questions' start
                   5337:       Qlength     - number of columns comprising a single bubble line from
                   5338:                     the sheet. (usually either 1 or 10)
1.424     albertel 5339:       Qon         - either a single character representing the character used
1.423     albertel 5340:                     to signal a bubble was chosen in the positional setup, or
                   5341:                     the string 'letter' if the letter of the chosen bubble is
                   5342:                     in the final, or 'number' if a number representing the
                   5343:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5344:       Qoff        - the character used to represent that a bubble was
                   5345:                     left blank
1.423     albertel 5346:       PaperID     - if the scanning process generates a unique number for each
                   5347:                     sheet scanned the column that this ID number starts in
                   5348:       PaperIDlength - number of columns that comprise the unique ID number
                   5349:                       for the sheet of paper
1.424     albertel 5350:       FirstName   - column that the first name starts in
1.423     albertel 5351:       FirstNameLength - number of columns that the first name spans
                   5352:  
                   5353:       LastName    - column that the last name starts in
                   5354:       LastNameLength - number of columns that the last name spans
                   5355: 
                   5356: =cut
1.422     foxr     5357: 
1.82      albertel 5358: sub get_scantron_config {
                   5359:     my ($which) = @_;
1.518     raeburn  5360:     my @lines = &get_scantronformat_file();
1.82      albertel 5361:     my %config;
1.157     albertel 5362:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5363:     foreach my $line (@lines) {
1.82      albertel 5364: 	my ($name,$descrip)=split(/:/,$line);
                   5365: 	if ($name ne $which ) { next; }
                   5366: 	chomp($line);
                   5367: 	my @config=split(/:/,$line);
                   5368: 	$config{'name'}=$config[0];
                   5369: 	$config{'description'}=$config[1];
                   5370: 	$config{'CODElocation'}=$config[2];
                   5371: 	$config{'CODEstart'}=$config[3];
                   5372: 	$config{'CODElength'}=$config[4];
                   5373: 	$config{'IDstart'}=$config[5];
                   5374: 	$config{'IDlength'}=$config[6];
                   5375: 	$config{'Qstart'}=$config[7];
1.497     foxr     5376:  	$config{'Qlength'}=$config[8];
1.82      albertel 5377: 	$config{'Qoff'}=$config[9];
                   5378: 	$config{'Qon'}=$config[10];
1.157     albertel 5379: 	$config{'PaperID'}=$config[11];
                   5380: 	$config{'PaperIDlength'}=$config[12];
                   5381: 	$config{'FirstName'}=$config[13];
                   5382: 	$config{'FirstNamelength'}=$config[14];
                   5383: 	$config{'LastName'}=$config[15];
                   5384: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5385: 	last;
                   5386:     }
                   5387:     return %config;
                   5388: }
                   5389: 
1.423     albertel 5390: =pod 
                   5391: 
                   5392: =item username_to_idmap
                   5393: 
1.556     weissno  5394:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5395:     student username:domain.
                   5396: 
                   5397:   Arguments:
                   5398: 
                   5399:     $classlist - reference to the class list hash. This is a hash
                   5400:                  keyed by student name:domain  whose elements are references
1.424     albertel 5401:                  to arrays containing various chunks of information
1.423     albertel 5402:                  about the student. (See loncoursedata for more info).
                   5403: 
                   5404:   Returns
                   5405:     %idmap - the constructed hash
                   5406: 
                   5407: =cut
                   5408: 
1.82      albertel 5409: sub username_to_idmap {
                   5410:     my ($classlist)= @_;
                   5411:     my %idmap;
                   5412:     foreach my $student (keys(%$classlist)) {
                   5413: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5414: 	    $student;
                   5415:     }
                   5416:     return %idmap;
                   5417: }
1.423     albertel 5418: 
                   5419: =pod
                   5420: 
1.424     albertel 5421: =item scantron_fixup_scanline
1.423     albertel 5422: 
                   5423:    Process a requested correction to a scanline.
                   5424: 
                   5425:   Arguments:
                   5426:     $scantron_config   - hash from &get_scantron_config()
                   5427:     $scan_data         - hash of correction information 
                   5428:                           (see &scantron_getfile())
                   5429:     $line              - existing scanline
                   5430:     $whichline         - line number of the passed in scanline
                   5431:     $field             - type of change to process 
                   5432:                          (either 
1.573     bisitz   5433:                           'ID'     -> correct the student/employee ID
1.423     albertel 5434:                           'CODE'   -> correct the CODE
                   5435:                           'answer' -> fixup the submitted answers)
                   5436:     
                   5437:    $args               - hash of additional info,
                   5438:                           - 'ID' 
                   5439:                                'newid' -> studentID to use in replacement
1.424     albertel 5440:                                           of existing one
1.423     albertel 5441:                           - 'CODE' 
                   5442:                                'CODE_ignore_dup' - set to true if duplicates
                   5443:                                                    should be ignored.
                   5444: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5445:                                         if the existing unfound code should
1.423     albertel 5446:                                         be used as is
                   5447:                           - 'answer'
                   5448:                                'response' - new answer or 'none' if blank
                   5449:                                'question' - the bubble line to change
1.503     raeburn  5450:                                'questionnum' - the question identifier,
                   5451:                                                may include subquestion. 
1.423     albertel 5452: 
                   5453:   Returns:
                   5454:     $line - the modified scanline
                   5455: 
                   5456:   Side effects: 
                   5457:     $scan_data - may be updated
                   5458: 
                   5459: =cut
                   5460: 
1.82      albertel 5461: 
1.157     albertel 5462: sub scantron_fixup_scanline {
                   5463:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5464:     if ($field eq 'ID') {
                   5465: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5466: 	    return ($line,1,'New value too large');
1.157     albertel 5467: 	}
                   5468: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5469: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5470: 				     $args->{'newid'});
                   5471: 	}
                   5472: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5473: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5474: 	if ($args->{'newid'}=~/^\s*$/) {
                   5475: 	    &scan_data($scan_data,"$whichline.user",
                   5476: 		       $args->{'username'}.':'.$args->{'domain'});
                   5477: 	}
1.186     albertel 5478:     } elsif ($field eq 'CODE') {
1.192     albertel 5479: 	if ($args->{'CODE_ignore_dup'}) {
                   5480: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5481: 	}
                   5482: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5483: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5484: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5485: 		return ($line,1,'New CODE value too large');
                   5486: 	    }
                   5487: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5488: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5489: 	    }
                   5490: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5491: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5492: 	}
1.157     albertel 5493:     } elsif ($field eq 'answer') {
1.497     foxr     5494: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5495: 	my $off=$scantron_config->{'Qoff'};
                   5496: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5497: 	my $answer=${off}x$length;
                   5498: 	if ($args->{'response'} eq 'none') {
                   5499: 	    &scan_data($scan_data,
1.503     raeburn  5500: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5501: 	} else {
                   5502: 	    if ($on eq 'letter') {
                   5503: 		my @alphabet=('A'..'Z');
                   5504: 		$answer=$alphabet[$args->{'response'}];
                   5505: 	    } elsif ($on eq 'number') {
                   5506: 		$answer=$args->{'response'}+1;
                   5507: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5508: 	    } else {
1.497     foxr     5509: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5510: 	    }
1.497     foxr     5511: 	    &scan_data($scan_data,
1.503     raeburn  5512: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5513: 	}
1.497     foxr     5514: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5515: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5516:     }
                   5517:     return $line;
                   5518: }
1.423     albertel 5519: 
                   5520: =pod
                   5521: 
                   5522: =item scan_data
                   5523: 
                   5524:     Edit or look up  an item in the scan_data hash.
                   5525: 
                   5526:   Arguments:
                   5527:     $scan_data  - The hash (see scantron_getfile)
                   5528:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5529:                   scantronfilename_key).
1.423     albertel 5530:     $data        - New value of the hash entry.
                   5531:     $delete      - If true, the entry is removed from the hash.
                   5532: 
                   5533:   Returns:
                   5534:     The new value of the hash table field (undefined if deleted).
                   5535: 
                   5536: =cut
                   5537: 
                   5538: 
1.157     albertel 5539: sub scan_data {
                   5540:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5541:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5542:     if (defined($value)) {
                   5543: 	$scan_data->{$filename.'_'.$key} = $value;
                   5544:     }
                   5545:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5546:     return $scan_data->{$filename.'_'.$key};
                   5547: }
1.423     albertel 5548: 
1.495     albertel 5549: # ----- These first few routines are general use routines.----
                   5550: 
                   5551: # Return the number of occurences of a pattern in a string.
                   5552: 
                   5553: sub occurence_count {
                   5554:     my ($string, $pattern) = @_;
                   5555: 
                   5556:     my @matches = ($string =~ /$pattern/g);
                   5557: 
                   5558:     return scalar(@matches);
                   5559: }
                   5560: 
                   5561: 
                   5562: # Take a string known to have digits and convert all the
                   5563: # digits into letters in the range J,A..I.
                   5564: 
                   5565: sub digits_to_letters {
                   5566:     my ($input) = @_;
                   5567: 
                   5568:     my @alphabet = ('J', 'A'..'I');
                   5569: 
                   5570:     my @input    = split(//, $input);
                   5571:     my $output ='';
                   5572:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5573: 	if ($input[$i] =~ /\d/) {
                   5574: 	    $output .= $alphabet[$input[$i]];
                   5575: 	} else {
                   5576: 	    $output .= $input[$i];
                   5577: 	}
                   5578:     }
                   5579:     return $output;
                   5580: }
                   5581: 
1.423     albertel 5582: =pod 
                   5583: 
                   5584: =item scantron_parse_scanline
                   5585: 
                   5586:   Decodes a scanline from the selected scantron file
                   5587: 
                   5588:  Arguments:
                   5589:     line             - The text of the scantron file line to process
                   5590:     whichline        - Line number
                   5591:     scantron_config  - Hash describing the format of the scantron lines.
                   5592:     scan_data        - Hash of extra information about the scanline
                   5593:                        (see scantron_getfile for more information)
                   5594:     just_header      - True if should not process question answers but only
                   5595:                        the stuff to the left of the answers.
                   5596:  Returns:
                   5597:    Hash containing the result of parsing the scanline
                   5598: 
                   5599:    Keys are all proceeded by the string 'scantron.'
                   5600: 
                   5601:        CODE    - the CODE in use for this scanline
                   5602:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5603:                  by the operator
                   5604:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5605:                             CODEs were selected, but the usage has been
                   5606:                             forced by the operator
1.556     weissno  5607:        ID  - student/employee ID
1.423     albertel 5608:        PaperID - if used, the ID number printed on the sheet when the 
                   5609:                  paper was scanned
                   5610:        FirstName - first name from the sheet
                   5611:        LastName  - last name from the sheet
                   5612: 
                   5613:      if just_header was not true these key may also exist
                   5614: 
1.447     foxr     5615:        missingerror - a list of bubble ranges that are considered to be answers
                   5616:                       to a single question that don't have any bubbles filled in.
                   5617:                       Of the form questionnumber:firstbubblenumber:count.
                   5618:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5619:                       to a single question that have more than one bubble filled in.
                   5620:                       Of the form questionnumber::firstbubblenumber:count
                   5621:    
                   5622:                 In the above, count is the number of bubble responses in the
                   5623:                 input line needed to represent the possible answers to the question.
                   5624:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5625:                 per line would have count = 2.
                   5626: 
1.423     albertel 5627:        maxquest     - the number of the last bubble line that was parsed
                   5628: 
                   5629:        (<number> starts at 1)
                   5630:        <number>.answer - zero or more letters representing the selected
                   5631:                          letters from the scanline for the bubble line 
                   5632:                          <number>.
                   5633:                          if blank there was either no bubble or there where
                   5634:                          multiple bubbles, (consult the keys missingerror and
                   5635:                          doubleerror if this is an error condition)
                   5636: 
                   5637: =cut
                   5638: 
1.82      albertel 5639: sub scantron_parse_scanline {
1.423     albertel 5640:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5641: 
1.82      albertel 5642:     my %record;
1.550     raeburn  5643:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5644:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.422     foxr     5645:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5646:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5647: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5648: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5649: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5650: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5651: 	    $record{'scantron.CODE'}=substr($data,
                   5652: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5653: 					    $$scantron_config{'CODElength'});
1.191     albertel 5654: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5655: 		$record{'scantron.useCODE'}=1;
                   5656: 	    }
1.192     albertel 5657: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5658: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5659: 	    }
1.82      albertel 5660: 	} else {
                   5661: 	    #FIXME interpret first N questions
                   5662: 	}
                   5663:     }
1.83      albertel 5664:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5665: 				  $$scantron_config{'IDlength'});
1.157     albertel 5666:     $record{'scantron.PaperID'}=
                   5667: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5668: 	       $$scantron_config{'PaperIDlength'});
                   5669:     $record{'scantron.FirstName'}=
                   5670: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5671: 	       $$scantron_config{'FirstNamelength'});
                   5672:     $record{'scantron.LastName'}=
                   5673: 	substr($data,$$scantron_config{'LastName'}-1,
                   5674: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5675:     if ($just_header) { return \%record; }
1.194     albertel 5676: 
1.82      albertel 5677:     my @alphabet=('A'..'Z');
                   5678:     my $questnum=0;
1.447     foxr     5679:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5680: 
1.470     foxr     5681:     chomp($questions);		# Get rid of any trailing \n.
                   5682:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5683:     while (length($questions)) {
1.447     foxr     5684: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5685:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5686:                              || 1;
                   5687:         $questnum++;
                   5688:         my $quest_id = $questnum;
                   5689:         my $currentquest = substr($questions,0,$answer_length);
                   5690:         $questions       = substr($questions,$answer_length);
                   5691:         if (length($currentquest) < $answer_length) { next; }
                   5692: 
                   5693:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5694:             my $subquestnum = 1;
                   5695:             my $subquestions = $currentquest;
                   5696:             my @subanswers_needed = 
                   5697:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5698:             foreach my $subans (@subanswers_needed) {
                   5699:                 my $subans_length =
                   5700:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5701:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5702:                 $subquestions   = substr($subquestions,$subans_length);
                   5703:                 $quest_id = "$questnum.$subquestnum";
                   5704:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5705:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5706:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5707:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5708:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5709:                 } else {
                   5710:                     $ansnum = &scantron_validator_positional($ansnum,
                   5711:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5712:                 }
                   5713:                 $subquestnum ++;
                   5714:             }
                   5715:         } else {
                   5716:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5717:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5718:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5719:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5720:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5721:             } else {
                   5722:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5723:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5724:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5725:             }
                   5726:         }
                   5727:     }
                   5728:     $record{'scantron.maxquest'}=$questnum;
                   5729:     return \%record;
                   5730: }
1.447     foxr     5731: 
1.503     raeburn  5732: sub scantron_validator_lettnum {
                   5733:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5734:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5735: 
                   5736:     # Qon 'letter' implies for each slot in currquest we have:
                   5737:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5738:     #    about anything else (esp. a value of Qoff) for missing
                   5739:     #    bubbles.
                   5740:     #
                   5741:     # Qon 'number' implies each slot gives a digit that indexes the
                   5742:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5743:     #    and * or ? for double bubbles on a single line.
                   5744:     #
1.447     foxr     5745: 
1.503     raeburn  5746:     my $matchon;
                   5747:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5748:         $matchon = '[A-Z]';
                   5749:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5750:         $matchon = '\d';
                   5751:     }
                   5752:     my $occurrences = 0;
                   5753:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5754:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5755:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5756:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5757:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5758:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5759:         my @singlelines = split('',$currquest);
                   5760:         foreach my $entry (@singlelines) {
                   5761:             $occurrences = &occurence_count($entry,$matchon);
                   5762:             if ($occurrences > 1) {
                   5763:                 last;
                   5764:             }
                   5765:         } 
                   5766:     } else {
                   5767:         $occurrences = &occurence_count($currquest,$matchon); 
                   5768:     }
                   5769:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5770:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5771:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5772:             my $bubble = substr($currquest,$ans,1);
                   5773:             if ($bubble =~ /$matchon/ ) {
                   5774:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5775:                     if ($bubble == 0) {
                   5776:                         $bubble = 10; 
                   5777:                     }
                   5778:                     $record->{"scantron.$ansnum.answer"} = 
                   5779:                         $alphabet->[$bubble-1];
                   5780:                 } else {
                   5781:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5782:                 }
                   5783:             } else {
                   5784:                 $record->{"scantron.$ansnum.answer"}='';
                   5785:             }
                   5786:             $ansnum++;
                   5787:         }
                   5788:     } elsif (!defined($currquest)
                   5789:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5790:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5791:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5792:             $record->{"scantron.$ansnum.answer"}='';
                   5793:             $ansnum++;
                   5794:         }
                   5795:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5796:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5797:         }
                   5798:     } else {
                   5799:         if ($$scantron_config{'Qon'} eq 'number') {
                   5800:             $currquest = &digits_to_letters($currquest);            
                   5801:         }
                   5802:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5803:             my $bubble = substr($currquest,$ans,1);
                   5804:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5805:             $ansnum++;
                   5806:         }
                   5807:     }
                   5808:     return $ansnum;
                   5809: }
1.447     foxr     5810: 
1.503     raeburn  5811: sub scantron_validator_positional {
                   5812:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5813:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5814: 
1.503     raeburn  5815:     # Otherwise there's a positional notation;
                   5816:     # each bubble line requires Qlength items, and there are filled in
                   5817:     # bubbles for each case where there 'Qon' characters.
                   5818:     #
1.447     foxr     5819: 
1.503     raeburn  5820:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5821: 
1.503     raeburn  5822:     # If the split only gives us one element.. the full length of the
                   5823:     # answer string, no bubbles are filled in:
1.447     foxr     5824: 
1.507     raeburn  5825:     if ($answers_needed eq '') {
                   5826:         return;
                   5827:     }
                   5828: 
1.503     raeburn  5829:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5830:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5831:             $record->{"scantron.$ansnum.answer"}='';
                   5832:             $ansnum++;
                   5833:         }
                   5834:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5835:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5836:         }
                   5837:     } elsif (scalar(@array) == 2) {
                   5838:         my $location = length($array[0]);
                   5839:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5840:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5841:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5842:             if ($ans eq $line_num) {
                   5843:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   5844:             } else {
                   5845:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   5846:             }
                   5847:             $ansnum++;
                   5848:          }
                   5849:     } else {
                   5850:         #  If there's more than one instance of a bubble character
                   5851:         #  That's a double bubble; with positional notation we can
                   5852:         #  record all the bubbles filled in as well as the
                   5853:         #  fact this response consists of multiple bubbles.
                   5854:         #
                   5855:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5856:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5857:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5858:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5859:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5860:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5861:             my $doubleerror = 0;
                   5862:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   5863:                    (!$doubleerror)) {
                   5864:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   5865:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   5866:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   5867:                if (length(@currarray) > 2) {
                   5868:                    $doubleerror = 1;
                   5869:                } 
                   5870:             }
                   5871:             if ($doubleerror) {
                   5872:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5873:             }
                   5874:         } else {
                   5875:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5876:         }
                   5877:         my $item = $ansnum;
                   5878:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5879:             $record->{"scantron.$item.answer"} = '';
                   5880:             $item ++;
                   5881:         }
1.447     foxr     5882: 
1.503     raeburn  5883:         my @ans=@array;
                   5884:         my $i=0;
                   5885:         my $increment = 0;
                   5886:         while ($#ans) {
                   5887:             $i+=length($ans[0]) + $increment;
                   5888:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   5889:             my $bubble = $i%$$scantron_config{'Qlength'};
                   5890:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   5891:             shift(@ans);
                   5892:             $increment = 1;
                   5893:         }
                   5894:         $ansnum += $answers_needed;
1.82      albertel 5895:     }
1.503     raeburn  5896:     return $ansnum;
1.82      albertel 5897: }
                   5898: 
1.423     albertel 5899: =pod
                   5900: 
                   5901: =item scantron_add_delay
                   5902: 
                   5903:    Adds an error message that occurred during the grading phase to a
                   5904:    queue of messages to be shown after grading pass is complete
                   5905: 
                   5906:  Arguments:
1.424     albertel 5907:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5908:    $scanline    - the scanline that caused the error
                   5909:    $errormesage - the error message
                   5910:    $errorcode   - a numeric code for the error
                   5911: 
                   5912:  Side Effects:
1.424     albertel 5913:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5914: 
                   5915: =cut
                   5916: 
1.82      albertel 5917: sub scantron_add_delay {
1.140     albertel 5918:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5919:     push(@$delayqueue,
                   5920: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5921: 	  'ecode' => $errorcode }
                   5922: 	 );
1.82      albertel 5923: }
                   5924: 
1.423     albertel 5925: =pod
                   5926: 
                   5927: =item scantron_find_student
                   5928: 
1.424     albertel 5929:    Finds the username for the current scanline
                   5930: 
                   5931:   Arguments:
                   5932:    $scantron_record - hash result from scantron_parse_scanline
                   5933:    $scan_data       - hash of correction information 
                   5934:                       (see &scantron_getfile() form more information)
                   5935:    $idmap           - hash from &username_to_idmap()
                   5936:    $line            - number of current scanline
                   5937:  
                   5938:   Returns:
                   5939:    Either 'username:domain' or undef if unknown
                   5940: 
1.423     albertel 5941: =cut
                   5942: 
1.82      albertel 5943: sub scantron_find_student {
1.157     albertel 5944:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5945:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5946:     if ($scanID =~ /^\s*$/) {
                   5947:  	return &scan_data($scan_data,"$line.user");
                   5948:     }
1.83      albertel 5949:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5950:  	if (lc($id) eq lc($scanID)) {
                   5951:  	    return $$idmap{$id};
                   5952:  	}
1.83      albertel 5953:     }
                   5954:     return undef;
                   5955: }
                   5956: 
1.423     albertel 5957: =pod
                   5958: 
                   5959: =item scantron_filter
                   5960: 
1.424     albertel 5961:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5962:    hidden resources was selected
                   5963: 
1.423     albertel 5964: =cut
                   5965: 
1.83      albertel 5966: sub scantron_filter {
                   5967:     my ($curres)=@_;
1.331     albertel 5968: 
                   5969:     if (ref($curres) && $curres->is_problem()) {
                   5970: 	# if the user has asked to not have either hidden
                   5971: 	# or 'randomout' controlled resources to be graded
                   5972: 	# don't include them
                   5973: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5974: 	    && $curres->randomout) {
                   5975: 	    return 0;
                   5976: 	}
1.83      albertel 5977: 	return 1;
                   5978:     }
                   5979:     return 0;
1.82      albertel 5980: }
                   5981: 
1.423     albertel 5982: =pod
                   5983: 
                   5984: =item scantron_process_corrections
                   5985: 
1.424     albertel 5986:    Gets correction information out of submitted form data and corrects
                   5987:    the scanline
                   5988: 
1.423     albertel 5989: =cut
                   5990: 
1.157     albertel 5991: sub scantron_process_corrections {
                   5992:     my ($r) = @_;
1.257     albertel 5993:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5994:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5995:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5996:     my $which=$env{'form.scantron_line'};
1.200     albertel 5997:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5998:     my ($skip,$err,$errmsg);
1.257     albertel 5999:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6000: 	$skip=1;
1.257     albertel 6001:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6002: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6003: 	    $env{'form.scantron_domain'};
1.157     albertel 6004: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6005: 	($line,$err,$errmsg)=
                   6006: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6007: 				     'ID',{'newid'=>$newid,
1.257     albertel 6008: 				    'username'=>$env{'form.scantron_username'},
                   6009: 				    'domain'=>$env{'form.scantron_domain'}});
                   6010:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6011: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6012: 	my $newCODE;
1.192     albertel 6013: 	my %args;
1.190     albertel 6014: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6015: 	    $newCODE='use_unfound';
1.190     albertel 6016: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6017: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6018: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6019: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6020: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6021: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6022: 	}
1.257     albertel 6023: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6024: 	    $args{'CODE_ignore_dup'}=1;
                   6025: 	}
                   6026: 	$args{'CODE'}=$newCODE;
1.186     albertel 6027: 	($line,$err,$errmsg)=
                   6028: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6029: 				     'CODE',\%args);
1.257     albertel 6030:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6031: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6032: 	    ($line,$err,$errmsg)=
                   6033: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6034: 					 $which,'answer',
                   6035: 					 { 'question'=>$question,
1.503     raeburn  6036: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6037:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6038: 	    if ($err) { last; }
                   6039: 	}
                   6040:     }
                   6041:     if ($err) {
1.398     albertel 6042: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 6043:     } else {
1.200     albertel 6044: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6045: 	&scantron_putfile($scanlines,$scan_data);
                   6046:     }
                   6047: }
                   6048: 
1.423     albertel 6049: =pod
                   6050: 
                   6051: =item reset_skipping_status
                   6052: 
1.424     albertel 6053:    Forgets the current set of remember skipped scanlines (and thus
                   6054:    reverts back to considering all lines in the
                   6055:    scantron_skipped_<filename> file)
                   6056: 
1.423     albertel 6057: =cut
                   6058: 
1.200     albertel 6059: sub reset_skipping_status {
                   6060:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6061:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6062:     &scantron_putfile(undef,$scan_data);
                   6063: }
                   6064: 
1.423     albertel 6065: =pod
                   6066: 
                   6067: =item start_skipping
                   6068: 
1.424     albertel 6069:    Marks a scanline to be skipped. 
                   6070: 
1.423     albertel 6071: =cut
                   6072: 
1.376     albertel 6073: sub start_skipping {
1.200     albertel 6074:     my ($scan_data,$i)=@_;
                   6075:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6076:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6077: 	$remembered{$i}=2;
                   6078:     } else {
                   6079: 	$remembered{$i}=1;
                   6080:     }
1.200     albertel 6081:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6082: }
                   6083: 
1.423     albertel 6084: =pod
                   6085: 
                   6086: =item should_be_skipped
                   6087: 
1.424     albertel 6088:    Checks whether a scanline should be skipped.
                   6089: 
1.423     albertel 6090: =cut
                   6091: 
1.200     albertel 6092: sub should_be_skipped {
1.376     albertel 6093:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6094:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6095: 	# not redoing old skips
1.376     albertel 6096: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6097: 	return 0;
                   6098:     }
                   6099:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6100: 
                   6101:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6102: 	return 0;
                   6103:     }
1.200     albertel 6104:     return 1;
                   6105: }
                   6106: 
1.423     albertel 6107: =pod
                   6108: 
                   6109: =item remember_current_skipped
                   6110: 
1.424     albertel 6111:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6112:    file and remembers them into scan_data for later use.
                   6113: 
1.423     albertel 6114: =cut
                   6115: 
1.200     albertel 6116: sub remember_current_skipped {
                   6117:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6118:     my %to_remember;
                   6119:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6120: 	if ($scanlines->{'skipped'}[$i]) {
                   6121: 	    $to_remember{$i}=1;
                   6122: 	}
                   6123:     }
1.376     albertel 6124: 
1.200     albertel 6125:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6126:     &scantron_putfile(undef,$scan_data);
                   6127: }
                   6128: 
1.423     albertel 6129: =pod
                   6130: 
                   6131: =item check_for_error
                   6132: 
1.424     albertel 6133:     Checks if there was an error when attempting to remove a specific
                   6134:     scantron_.. bubble sheet data file. Prints out an error if
                   6135:     something went wrong.
                   6136: 
1.423     albertel 6137: =cut
                   6138: 
1.200     albertel 6139: sub check_for_error {
                   6140:     my ($r,$result)=@_;
                   6141:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6142: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6143:     }
                   6144: }
1.157     albertel 6145: 
1.423     albertel 6146: =pod
                   6147: 
                   6148: =item scantron_warning_screen
                   6149: 
1.424     albertel 6150:    Interstitial screen to make sure the operator has selected the
                   6151:    correct options before we start the validation phase.
                   6152: 
1.423     albertel 6153: =cut
                   6154: 
1.203     albertel 6155: sub scantron_warning_screen {
                   6156:     my ($button_text)=@_;
1.257     albertel 6157:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6158:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6159:     my $CODElist;
1.284     albertel 6160:     if ($scantron_config{'CODElocation'} &&
                   6161: 	$scantron_config{'CODEstart'} &&
                   6162: 	$scantron_config{'CODElength'}) {
                   6163: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6164: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6165: 	$CODElist=
1.492     albertel 6166: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6167: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6168:     }
1.492     albertel 6169:     return ('
1.203     albertel 6170: <p>
1.492     albertel 6171: <span class="LC_warning">
                   6172: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6173: </p>
                   6174: <table>
1.492     albertel 6175: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6176: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6177: '.$CODElist.'
1.203     albertel 6178: </table>
                   6179: <br />
1.492     albertel 6180: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   6181: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 6182: 
                   6183: <br />
1.492     albertel 6184: ');
1.203     albertel 6185: }
                   6186: 
1.423     albertel 6187: =pod
                   6188: 
                   6189: =item scantron_do_warning
                   6190: 
1.424     albertel 6191:    Check if the operator has picked something for all required
                   6192:    fields. Error out if something is missing.
                   6193: 
1.423     albertel 6194: =cut
                   6195: 
1.203     albertel 6196: sub scantron_do_warning {
                   6197:     my ($r)=@_;
1.324     albertel 6198:     my ($symb)=&get_symb($r);
1.203     albertel 6199:     if (!$symb) {return '';}
1.324     albertel 6200:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6201:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6202:     if ( $env{'form.selectpage'} eq '' ||
                   6203: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6204: 	 $env{'form.scantron_format'} eq '' ) {
1.492     albertel 6205: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6206: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6207: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6208: 	} 
1.257     albertel 6209: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.492     albertel 6210: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
1.237     albertel 6211: 	} 
1.257     albertel 6212: 	if ( $env{'form.scantron_format'} eq '') {
1.492     albertel 6213: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
1.237     albertel 6214: 	} 
                   6215:     } else {
1.265     www      6216: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.492     albertel 6217: 	$r->print('
                   6218: '.$warning.'
                   6219: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6220: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6221: ');
1.237     albertel 6222:     }
1.352     albertel 6223:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 6224:     return '';
                   6225: }
                   6226: 
1.423     albertel 6227: =pod
                   6228: 
                   6229: =item scantron_form_start
                   6230: 
1.424     albertel 6231:     html hidden input for remembering all selected grading options
                   6232: 
1.423     albertel 6233: =cut
                   6234: 
1.203     albertel 6235: sub scantron_form_start {
                   6236:     my ($max_bubble)=@_;
                   6237:     my $result= <<SCANTRONFORM;
                   6238: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6239:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6240:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6241:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6242:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6243:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6244:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6245:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6246:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6247:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6248: SCANTRONFORM
1.447     foxr     6249: 
                   6250:   my $line = 0;
                   6251:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6252:        my $chunk =
                   6253: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6254:        $chunk .=
                   6255: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6256:        $chunk .= 
                   6257:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6258:        $chunk .=
                   6259:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6260:        $result .= $chunk;
                   6261:        $line++;
                   6262:    }
1.203     albertel 6263:     return $result;
                   6264: }
                   6265: 
1.423     albertel 6266: =pod
                   6267: 
                   6268: =item scantron_validate_file
                   6269: 
1.424     albertel 6270:     Dispatch routine for doing validation of a bubble sheet data file.
                   6271: 
                   6272:     Also processes any necessary information resets that need to
                   6273:     occur before validation begins (ignore previous corrections,
                   6274:     restarting the skipped records processing)
                   6275: 
1.423     albertel 6276: =cut
                   6277: 
1.157     albertel 6278: sub scantron_validate_file {
                   6279:     my ($r) = @_;
1.324     albertel 6280:     my ($symb)=&get_symb($r);
1.157     albertel 6281:     if (!$symb) {return '';}
1.324     albertel 6282:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6283:     
                   6284:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6285:     # them when doing the corrections reset
1.257     albertel 6286:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6287: 	&reset_skipping_status();
                   6288:     }
1.257     albertel 6289:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6290: 	&remember_current_skipped();
1.257     albertel 6291: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6292:     }
                   6293: 
1.257     albertel 6294:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6295: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6296: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6297: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6298: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6299:     }
1.200     albertel 6300: 
1.257     albertel 6301:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6302: 	&scantron_process_corrections($r);
                   6303:     }
1.503     raeburn  6304:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6305:     #get the student pick code ready
                   6306:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.574.2.7  raeburn  6307:     my $nav_error;
                   6308:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   6309:     if ($nav_error) {
                   6310:         $r->print(&navmap_errormsg());
                   6311:         return '';
                   6312:     }
1.203     albertel 6313:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6314:     $r->print($result);
                   6315:     
1.334     albertel 6316:     my @validate_phases=( 'sequence',
                   6317: 			  'ID',
1.157     albertel 6318: 			  'CODE',
                   6319: 			  'doublebubble',
                   6320: 			  'missingbubbles');
1.257     albertel 6321:     if (!$env{'form.validatepass'}) {
                   6322: 	$env{'form.validatepass'} = 0;
1.157     albertel 6323:     }
1.257     albertel 6324:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6325: 
1.448     foxr     6326: 
1.157     albertel 6327:     my $stop=0;
                   6328:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6329: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6330: 	$r->rflush();
                   6331: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6332: 	{
                   6333: 	    no strict 'refs';
                   6334: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6335: 	}
                   6336:     }
                   6337:     if (!$stop) {
1.203     albertel 6338: 	my $warning=&scantron_warning_screen('Start Grading');
1.542     raeburn  6339: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6340:                   $warning.
                   6341:                   &mt('Perform verification for each student after storage of submissions?').
                   6342:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6343:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6344:                   ('&nbsp;'x3).'<label>'.
                   6345:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6346:                   '</label></span><br />'.
                   6347:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.572     www      6348:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
1.542     raeburn  6349:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6350:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6351:     } else {
                   6352: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6353: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6354:     }
                   6355:     if ($stop) {
1.334     albertel 6356: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6357: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6358: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6359: 
1.492     albertel 6360: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6361: 	} else {
1.503     raeburn  6362:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6363: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6364:             } else {
1.539     riegler  6365:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6366:             }
1.492     albertel 6367: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6368: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6369: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6370: 	}
1.157     albertel 6371:     }
1.352     albertel 6372:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 6373:     return '';
                   6374: }
                   6375: 
1.423     albertel 6376: 
                   6377: =pod
                   6378: 
                   6379: =item scantron_remove_file
                   6380: 
1.424     albertel 6381:    Removes the requested bubble sheet data file, makes sure that
                   6382:    scantron_original_<filename> is never removed
                   6383: 
                   6384: 
1.423     albertel 6385: =cut
                   6386: 
1.200     albertel 6387: sub scantron_remove_file {
1.192     albertel 6388:     my ($which)=@_;
1.257     albertel 6389:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6390:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6391:     my $file='scantron_';
1.200     albertel 6392:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6393: 	$file.=$which.'_';
1.192     albertel 6394:     } else {
                   6395: 	return 'refused';
                   6396:     }
1.257     albertel 6397:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6398:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6399: }
                   6400: 
1.423     albertel 6401: 
                   6402: =pod
                   6403: 
                   6404: =item scantron_remove_scan_data
                   6405: 
1.424     albertel 6406:    Removes all scan_data correction for the requested bubble sheet
                   6407:    data file.  (In the case that both the are doing skipped records we need
                   6408:    to remember the old skipped lines for the time being so that element
                   6409:    persists for a while.)
                   6410: 
1.423     albertel 6411: =cut
                   6412: 
1.200     albertel 6413: sub scantron_remove_scan_data {
1.257     albertel 6414:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6415:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6416:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6417:     my @todelete;
1.257     albertel 6418:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6419:     foreach my $key (@keys) {
                   6420: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6421: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6422: 		$key=~/remember_skipping/) {
                   6423: 		next;
                   6424: 	    }
1.192     albertel 6425: 	    push(@todelete,$key);
                   6426: 	}
                   6427:     }
1.200     albertel 6428:     my $result;
1.192     albertel 6429:     if (@todelete) {
1.491     albertel 6430: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6431: 				       \@todelete,$cdom,$cname);
                   6432:     } else {
                   6433: 	$result = 'ok';
1.192     albertel 6434:     }
                   6435:     return $result;
                   6436: }
                   6437: 
1.423     albertel 6438: 
                   6439: =pod
                   6440: 
                   6441: =item scantron_getfile
                   6442: 
1.424     albertel 6443:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6444:     the scan_data hash
                   6445:   
                   6446:   Arguments:
                   6447:     None
                   6448: 
                   6449:   Returns:
                   6450:     2 hash references
                   6451: 
                   6452:      - first one has 
                   6453:          orig      -
                   6454:          corrected -
                   6455:          skipped   -  each of which points to an array ref of the specified
                   6456:                       file broken up into individual lines
                   6457:          count     - number of scanlines
                   6458:  
                   6459:      - second is the scan_data hash possible keys are
1.425     albertel 6460:        ($number refers to scanline numbered $number and thus the key affects
                   6461:         only that scanline
                   6462:         $bubline refers to the specific bubble line element and the aspects
                   6463:         refers to that specific bubble line element)
                   6464: 
                   6465:        $number.user - username:domain to use
                   6466:        $number.CODE_ignore_dup 
                   6467:                     - ignore the duplicate CODE error 
                   6468:        $number.useCODE
                   6469:                     - use the CODE in the scanline as is
                   6470:        $number.no_bubble.$bubline
                   6471:                     - it is valid that there is no bubbled in bubble
                   6472:                       at $number $bubline
                   6473:        remember_skipping
                   6474:                     - a frozen hash containing keys of $number and values
                   6475:                       of either 
                   6476:                         1 - we are on a 'do skipped records pass' and plan
                   6477:                             on processing this line
                   6478:                         2 - we are on a 'do skipped records pass' and this
                   6479:                             scanline has been marked to skip yet again
1.424     albertel 6480: 
1.423     albertel 6481: =cut
                   6482: 
1.157     albertel 6483: sub scantron_getfile {
1.200     albertel 6484:     #FIXME really would prefer a scantron directory
1.257     albertel 6485:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6486:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6487:     my $lines;
                   6488:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6489: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6490:     my %scanlines;
                   6491:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6492:     my $temp=$scanlines{'orig'};
                   6493:     $scanlines{'count'}=$#$temp;
                   6494: 
                   6495:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6496: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6497:     if ($lines eq '-1') {
                   6498: 	$scanlines{'corrected'}=[];
                   6499:     } else {
                   6500: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6501:     }
                   6502:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6503: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6504:     if ($lines eq '-1') {
                   6505: 	$scanlines{'skipped'}=[];
                   6506:     } else {
                   6507: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6508:     }
1.175     albertel 6509:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6510:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6511:     my %scan_data = @tmp;
                   6512:     return (\%scanlines,\%scan_data);
                   6513: }
                   6514: 
1.423     albertel 6515: =pod
                   6516: 
                   6517: =item lonnet_putfile
                   6518: 
1.424     albertel 6519:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6520: 
                   6521:  Arguments:
                   6522:    $contents - data to store
                   6523:    $filename - filename to store $contents into
                   6524: 
                   6525:  Returns:
                   6526:    result value from &Apache::lonnet::finishuserfileupload
                   6527: 
1.423     albertel 6528: =cut
                   6529: 
1.157     albertel 6530: sub lonnet_putfile {
                   6531:     my ($contents,$filename)=@_;
1.257     albertel 6532:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6533:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6534:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6535:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6536: 
                   6537: }
                   6538: 
1.423     albertel 6539: =pod
                   6540: 
                   6541: =item scantron_putfile
                   6542: 
1.424     albertel 6543:     Stores the current version of the bubble sheet data files, and the
                   6544:     scan_data hash. (Does not modify the original version only the
                   6545:     corrected and skipped versions.
                   6546: 
                   6547:  Arguments:
                   6548:     $scanlines - hash ref that looks like the first return value from
                   6549:                  &scantron_getfile()
                   6550:     $scan_data - hash ref that looks like the second return value from
                   6551:                  &scantron_getfile()
                   6552: 
1.423     albertel 6553: =cut
                   6554: 
1.157     albertel 6555: sub scantron_putfile {
                   6556:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6557:     #FIXME really would prefer a scantron directory
1.257     albertel 6558:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6559:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6560:     if ($scanlines) {
                   6561: 	my $prefix='scantron_';
1.157     albertel 6562: # no need to update orig, shouldn't change
                   6563: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6564: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6565: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6566: 			$prefix.'corrected_'.
1.257     albertel 6567: 			$env{'form.scantron_selectfile'});
1.200     albertel 6568: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6569: 			$prefix.'skipped_'.
1.257     albertel 6570: 			$env{'form.scantron_selectfile'});
1.200     albertel 6571:     }
1.175     albertel 6572:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6573: }
                   6574: 
1.423     albertel 6575: =pod
                   6576: 
                   6577: =item scantron_get_line
                   6578: 
1.424     albertel 6579:    Returns the correct version of the scanline
                   6580: 
                   6581:  Arguments:
                   6582:     $scanlines - hash ref that looks like the first return value from
                   6583:                  &scantron_getfile()
                   6584:     $scan_data - hash ref that looks like the second return value from
                   6585:                  &scantron_getfile()
                   6586:     $i         - number of the requested line (starts at 0)
                   6587: 
                   6588:  Returns:
                   6589:    A scanline, (either the original or the corrected one if it
                   6590:    exists), or undef if the requested scanline should be
                   6591:    skipped. (Either because it's an skipped scanline, or it's an
                   6592:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6593:    pass.
                   6594: 
1.423     albertel 6595: =cut
                   6596: 
1.157     albertel 6597: sub scantron_get_line {
1.200     albertel 6598:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6599:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6600:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6601:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6602:     return $scanlines->{'orig'}[$i]; 
                   6603: }
                   6604: 
1.423     albertel 6605: =pod
                   6606: 
                   6607: =item scantron_todo_count
                   6608: 
1.424     albertel 6609:     Counts the number of scanlines that need processing.
                   6610: 
                   6611:  Arguments:
                   6612:     $scanlines - hash ref that looks like the first return value from
                   6613:                  &scantron_getfile()
                   6614:     $scan_data - hash ref that looks like the second return value from
                   6615:                  &scantron_getfile()
                   6616: 
                   6617:  Returns:
                   6618:     $count - number of scanlines to process
                   6619: 
1.423     albertel 6620: =cut
                   6621: 
1.200     albertel 6622: sub get_todo_count {
                   6623:     my ($scanlines,$scan_data)=@_;
                   6624:     my $count=0;
                   6625:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6626: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6627: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6628: 	$count++;
                   6629:     }
                   6630:     return $count;
                   6631: }
                   6632: 
1.423     albertel 6633: =pod
                   6634: 
                   6635: =item scantron_put_line
                   6636: 
1.424     albertel 6637:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6638:     data file.
                   6639: 
                   6640:  Arguments:
                   6641:     $scanlines - hash ref that looks like the first return value from
                   6642:                  &scantron_getfile()
                   6643:     $scan_data - hash ref that looks like the second return value from
                   6644:                  &scantron_getfile()
                   6645:     $i         - line number to update
                   6646:     $newline   - contents of the updated scanline
                   6647:     $skip      - if true make the line for skipping and update the
                   6648:                  'skipped' file
                   6649: 
1.423     albertel 6650: =cut
                   6651: 
1.157     albertel 6652: sub scantron_put_line {
1.200     albertel 6653:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6654:     if ($skip) {
                   6655: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6656: 	&start_skipping($scan_data,$i);
1.157     albertel 6657: 	return;
                   6658:     }
                   6659:     $scanlines->{'corrected'}[$i]=$newline;
                   6660: }
                   6661: 
1.423     albertel 6662: =pod
                   6663: 
                   6664: =item scantron_clear_skip
                   6665: 
1.424     albertel 6666:    Remove a line from the 'skipped' file
                   6667: 
                   6668:  Arguments:
                   6669:     $scanlines - hash ref that looks like the first return value from
                   6670:                  &scantron_getfile()
                   6671:     $scan_data - hash ref that looks like the second return value from
                   6672:                  &scantron_getfile()
                   6673:     $i         - line number to update
                   6674: 
1.423     albertel 6675: =cut
                   6676: 
1.376     albertel 6677: sub scantron_clear_skip {
                   6678:     my ($scanlines,$scan_data,$i)=@_;
                   6679:     if (exists($scanlines->{'skipped'}[$i])) {
                   6680: 	undef($scanlines->{'skipped'}[$i]);
                   6681: 	return 1;
                   6682:     }
                   6683:     return 0;
                   6684: }
                   6685: 
1.423     albertel 6686: =pod
                   6687: 
                   6688: =item scantron_filter_not_exam
                   6689: 
1.424     albertel 6690:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6691:    filter out resources that are not marked as 'exam' mode
                   6692: 
1.423     albertel 6693: =cut
                   6694: 
1.334     albertel 6695: sub scantron_filter_not_exam {
                   6696:     my ($curres)=@_;
                   6697:     
                   6698:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6699: 	# if the user has asked to not have either hidden
                   6700: 	# or 'randomout' controlled resources to be graded
                   6701: 	# don't include them
                   6702: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6703: 	    && $curres->randomout) {
                   6704: 	    return 0;
                   6705: 	}
                   6706: 	return 1;
                   6707:     }
                   6708:     return 0;
                   6709: }
                   6710: 
1.423     albertel 6711: =pod
                   6712: 
                   6713: =item scantron_validate_sequence
                   6714: 
1.424     albertel 6715:     Validates the selected sequence, checking for resource that are
                   6716:     not set to exam mode.
                   6717: 
1.423     albertel 6718: =cut
                   6719: 
1.334     albertel 6720: sub scantron_validate_sequence {
                   6721:     my ($r,$currentphase) = @_;
                   6722: 
                   6723:     my $navmap=Apache::lonnavmaps::navmap->new();
1.574.2.7  raeburn  6724:     unless (ref($navmap)) {
                   6725:         $r->print(&navmap_errormsg());
                   6726:         return (1,$currentphase);
                   6727:     }
1.334     albertel 6728:     my (undef,undef,$sequence)=
                   6729: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6730: 
                   6731:     my $map=$navmap->getResourceByUrl($sequence);
                   6732: 
                   6733:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6734:                                     value="ignore" />');
                   6735:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6736: 	my @resources=
                   6737: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6738: 	if (@resources) {
1.357     banghart 6739: 	    $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 6740: 	    return (1,$currentphase);
                   6741: 	}
                   6742:     }
                   6743: 
                   6744:     return (0,$currentphase+1);
                   6745: }
                   6746: 
1.423     albertel 6747: 
                   6748: 
1.157     albertel 6749: sub scantron_validate_ID {
                   6750:     my ($r,$currentphase) = @_;
                   6751:     
                   6752:     #get student info
                   6753:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6754:     my %idmap=&username_to_idmap($classlist);
                   6755: 
                   6756:     #get scantron line setup
1.257     albertel 6757:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6758:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6759:     
1.574.2.7  raeburn  6760:     my $nav_error;
                   6761:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
                   6762:     if ($nav_error) {
                   6763:         $r->print(&navmap_errormsg());
                   6764:         return(1,$currentphase);
                   6765:     }
1.157     albertel 6766: 
                   6767:     my %found=('ids'=>{},'usernames'=>{});
                   6768:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6769: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6770: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6771: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6772: 						 $scan_data);
                   6773: 	my $id=$$scan_record{'scantron.ID'};
                   6774: 	my $found;
                   6775: 	foreach my $checkid (keys(%idmap)) {
                   6776: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6777: 	}
                   6778: 	if ($found) {
                   6779: 	    my $username=$idmap{$found};
                   6780: 	    if ($found{'ids'}{$found}) {
                   6781: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6782: 					 $line,'duplicateID',$found);
1.194     albertel 6783: 		return(1,$currentphase);
1.157     albertel 6784: 	    } elsif ($found{'usernames'}{$username}) {
                   6785: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6786: 					 $line,'duplicateID',$username);
1.194     albertel 6787: 		return(1,$currentphase);
1.157     albertel 6788: 	    }
1.186     albertel 6789: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6790: 	    $found{'ids'}{$found}++;
                   6791: 	    $found{'usernames'}{$username}++;
                   6792: 	} else {
                   6793: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6794: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6795: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6796: 		    &scantron_get_correction($r,$i,$scan_record,
                   6797: 					     \%scantron_config,
                   6798: 					     $line,'duplicateID',$username);
1.194     albertel 6799: 		    return(1,$currentphase);
1.157     albertel 6800: 		} elsif (!defined($username)) {
                   6801: 		    &scantron_get_correction($r,$i,$scan_record,
                   6802: 					     \%scantron_config,
                   6803: 					     $line,'incorrectID');
1.194     albertel 6804: 		    return(1,$currentphase);
1.157     albertel 6805: 		}
                   6806: 		$found{'usernames'}{$username}++;
                   6807: 	    } else {
                   6808: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6809: 					 $line,'incorrectID');
1.194     albertel 6810: 		return(1,$currentphase);
1.157     albertel 6811: 	    }
                   6812: 	}
                   6813:     }
                   6814: 
                   6815:     return (0,$currentphase+1);
                   6816: }
                   6817: 
1.423     albertel 6818: 
1.157     albertel 6819: sub scantron_get_correction {
                   6820:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6821: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6822: #to show both the current line and the previous one and allow skipping
                   6823: #the previous one or the current one
                   6824: 
1.333     albertel 6825:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6826: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6827: 			    " for PaperID <tt>[_1]</tt>",
                   6828: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6829:     } else {
1.492     albertel 6830: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6831: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6832: 			    $i,$line)."</p> \n");
                   6833:     }
                   6834:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6835: 			  "The name on the paper is [_2],[_3]",
                   6836: 			  $$scan_record{'scantron.ID'},
                   6837: 			  $$scan_record{'scantron.LastName'},
                   6838: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6839: 
1.157     albertel 6840:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6841:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6842:                            # Array populated for doublebubble or
                   6843:     my @lines_to_correct;  # missingbubble errors to build javascript
                   6844:                            # to validate radio button checking   
                   6845: 
1.157     albertel 6846:     if ($error =~ /ID$/) {
1.186     albertel 6847: 	if ($error eq 'incorrectID') {
1.492     albertel 6848: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   6849: 		      "</p>\n");
1.157     albertel 6850: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 6851: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6852: 	}
1.242     albertel 6853: 	$r->print($message);
1.492     albertel 6854: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6855: 	$r->print("\n<ul><li> ");
                   6856: 	#FIXME it would be nice if this sent back the user ID and
                   6857: 	#could do partial userID matches
                   6858: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6859: 				       'scantron_username','scantron_domain'));
                   6860: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6861: 	$r->print("\n@".
1.257     albertel 6862: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6863: 
                   6864: 	$r->print('</li>');
1.186     albertel 6865:     } elsif ($error =~ /CODE$/) {
                   6866: 	if ($error eq 'incorrectCODE') {
1.492     albertel 6867: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6868: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 6869: 	    $r->print("<p>".&mt("The encoded CODE has also been used by a previous paper [_1], and CODEs are supposed to be unique.",join(', ',@{$arg}))."</p>\n");
1.186     albertel 6870: 	}
1.492     albertel 6871: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   6872: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 6873: 	$r->print($message);
1.492     albertel 6874: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 6875: 	$r->print("\n<br /> ");
1.194     albertel 6876: 	my $i=0;
1.273     albertel 6877: 	if ($error eq 'incorrectCODE' 
                   6878: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6879: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6880: 	    if ($closest > 0) {
                   6881: 		foreach my $testcode (@{$closest}) {
                   6882: 		    my $checked='';
1.569     bisitz   6883: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6884: 		    $r->print("
                   6885:    <label>
1.569     bisitz   6886:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 6887:        ".&mt("Use the similar CODE [_1] instead.",
                   6888: 	    "<b><tt>".$testcode."</tt></b>")."
                   6889:     </label>
                   6890:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6891: 		    $r->print("\n<br />");
                   6892: 		    $i++;
                   6893: 		}
1.194     albertel 6894: 	    }
                   6895: 	}
1.273     albertel 6896: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   6897: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6898: 	    $r->print("
                   6899:     <label>
1.569     bisitz   6900:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.492     albertel 6901:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   6902: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6903:     </label>");
1.273     albertel 6904: 	    $r->print("\n<br />");
                   6905: 	}
1.194     albertel 6906: 
1.188     albertel 6907: 	$r->print(<<ENDSCRIPT);
                   6908: <script type="text/javascript">
                   6909: function change_radio(field) {
1.190     albertel 6910:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6911:     var i;
                   6912:     for (i=0;i<slct.length;i++) {
                   6913:         if (slct[i].value==field) { slct[i].checked=true; }
                   6914:     }
                   6915: }
                   6916: </script>
                   6917: ENDSCRIPT
1.187     albertel 6918: 	my $href="/adm/pickcode?".
1.359     www      6919: 	   "form=".&escape("scantronupload").
                   6920: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6921: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6922: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6923: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6924: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 6925: 	    $r->print("
                   6926:     <label>
                   6927:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   6928:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   6929: 	     "<a target='_blank' href='$href'>","</a>")."
                   6930:     </label> 
1.558     bisitz   6931:     ".&mt("Selected CODE is [_1]",'<input readonly="readonly" type="text" size="8" name="scantron_CODE_selectedvalue" onfocus="javascript:change_radio(\'use_found\')" onchange="javascript:change_radio(\'use_found\')" />'));
1.332     albertel 6932: 	    $r->print("\n<br />");
                   6933: 	}
1.492     albertel 6934: 	$r->print("
                   6935:     <label>
                   6936:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   6937:        ".&mt("Use [_1] as the CODE.",
                   6938: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
1.187     albertel 6939: 	$r->print("\n<br /><br />");
1.157     albertel 6940:     } elsif ($error eq 'doublebubble') {
1.503     raeburn  6941: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     6942: 
                   6943: 	# The form field scantron_questions is acutally a list of line numbers.
                   6944: 	# represented by this form so:
                   6945: 
                   6946: 	my $line_list = &questions_to_line_list($arg);
                   6947: 
1.157     albertel 6948: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6949: 		  $line_list.'" />');
1.242     albertel 6950: 	$r->print($message);
1.492     albertel 6951: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 6952: 	foreach my $question (@{$arg}) {
1.503     raeburn  6953: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6954:                                                    $scan_record, $error);
1.524     raeburn  6955:             push(@lines_to_correct,@linenums);
1.157     albertel 6956: 	}
1.503     raeburn  6957:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6958:     } elsif ($error eq 'missingbubble') {
1.492     albertel 6959: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 6960: 	$r->print($message);
1.492     albertel 6961: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  6962: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     6963: 
1.503     raeburn  6964: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     6965: 	# a list of question numbers. Therefore:
                   6966: 	#
                   6967: 	
                   6968: 	my $line_list = &questions_to_line_list($arg);
                   6969: 
1.157     albertel 6970: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6971: 		  $line_list.'" />');
1.157     albertel 6972: 	foreach my $question (@{$arg}) {
1.503     raeburn  6973: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6974:                                                    $scan_record, $error);
1.524     raeburn  6975:             push(@lines_to_correct,@linenums);
1.157     albertel 6976: 	}
1.503     raeburn  6977:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6978:     } else {
                   6979: 	$r->print("\n<ul>");
                   6980:     }
                   6981:     $r->print("\n</li></ul>");
1.497     foxr     6982: }
                   6983: 
1.503     raeburn  6984: sub verify_bubbles_checked {
                   6985:     my (@ansnums) = @_;
                   6986:     my $ansnumstr = join('","',@ansnums);
                   6987:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
                   6988:     my $output = (<<ENDSCRIPT);
                   6989: <script type="text/javascript">
                   6990: function verify_bubble_radio(form) {
                   6991:     var ansnumArray = new Array ("$ansnumstr");
                   6992:     var need_bubble_count = 0;
                   6993:     for (var i=0; i<ansnumArray.length; i++) {
                   6994:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   6995:             var bubble_picked = 0; 
                   6996:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   6997:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   6998:                     bubble_picked = 1;
                   6999:                 }
                   7000:             }
                   7001:             if (bubble_picked == 0) {
                   7002:                 need_bubble_count ++;
                   7003:             }
                   7004:         }
                   7005:     }
                   7006:     if (need_bubble_count) {
                   7007:         alert("$warning");
                   7008:         return;
                   7009:     }
                   7010:     form.submit(); 
                   7011: }
                   7012: </script>
                   7013: ENDSCRIPT
                   7014:     return $output;
                   7015: }
                   7016: 
1.497     foxr     7017: =pod
                   7018: 
                   7019: =item  questions_to_line_list
1.157     albertel 7020: 
1.497     foxr     7021: Converts a list of questions into a string of comma separated
                   7022: line numbers in the answer sheet used by the questions.  This is
                   7023: used to fill in the scantron_questions form field.
                   7024: 
                   7025:   Arguments:
                   7026:      questions    - Reference to an array of questions.
                   7027: 
                   7028: =cut
                   7029: 
                   7030: 
                   7031: sub questions_to_line_list {
                   7032:     my ($questions) = @_;
                   7033:     my @lines;
                   7034: 
1.503     raeburn  7035:     foreach my $item (@{$questions}) {
                   7036:         my $question = $item;
                   7037:         my ($first,$count,$last);
                   7038:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7039:             $question = $1;
                   7040:             my $subquestion = $2;
                   7041:             $first = $first_bubble_line{$question-1} + 1;
                   7042:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7043:             my $subcount = 1;
                   7044:             while ($subcount<$subquestion) {
                   7045:                 $first += $subans[$subcount-1];
                   7046:                 $subcount ++;
                   7047:             }
                   7048:             $count = $subans[$subquestion-1];
                   7049:         } else {
                   7050: 	    $first   = $first_bubble_line{$question-1} + 1;
                   7051: 	    $count   = $bubble_lines_per_response{$question-1};
                   7052:         }
1.506     raeburn  7053:         $last = $first+$count-1;
1.503     raeburn  7054:         push(@lines, ($first..$last));
1.497     foxr     7055:     }
                   7056:     return join(',', @lines);
                   7057: }
                   7058: 
                   7059: =pod 
                   7060: 
                   7061: =item prompt_for_corrections
                   7062: 
                   7063: Prompts for a potentially multiline correction to the
                   7064: user's bubbling (factors out common code from scantron_get_correction
                   7065: for multi and missing bubble cases).
                   7066: 
                   7067:  Arguments:
                   7068:    $r           - Apache request object.
                   7069:    $question    - The question number to prompt for.
                   7070:    $scan_config - The scantron file configuration hash.
                   7071:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7072:    $error       - Type of error
1.497     foxr     7073: 
                   7074:  Implicit inputs:
                   7075:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7076:                                   Numbered from 0 (but question numbers are from
                   7077:                                   1.
                   7078:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7079:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7080:                                   type problems render as separate sub-questions, 
1.503     raeburn  7081:                                   in exam mode. This hash contains a 
                   7082:                                   comma-separated list of the lines per 
                   7083:                                   sub-question.
1.510     raeburn  7084:    %responsetype_per_response   - essayresponse, formularesponse,
                   7085:                                   stringresponse, imageresponse, reactionresponse,
                   7086:                                   and organicresponse type problem parts can have
1.503     raeburn  7087:                                   multiple lines per response if the weight
                   7088:                                   assigned exceeds 10.  In this case, only
                   7089:                                   one bubble per line is permitted, but more 
                   7090:                                   than one line might contain bubbles, e.g.
                   7091:                                   bubbling of: line 1 - J, line 2 - J, 
                   7092:                                   line 3 - B would assign 22 points.  
1.497     foxr     7093: 
                   7094: =cut
                   7095: 
                   7096: sub prompt_for_corrections {
1.503     raeburn  7097:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   7098:     my ($current_line,$lines);
                   7099:     my @linenums;
                   7100:     my $questionnum = $question;
                   7101:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7102:         $question = $1;
                   7103:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7104:         my $subquestion = $2;
                   7105:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7106:         my $subcount = 1;
                   7107:         while ($subcount<$subquestion) {
                   7108:             $current_line += $subans[$subcount-1];
                   7109:             $subcount ++;
                   7110:         }
                   7111:         $lines = $subans[$subquestion-1];
                   7112:     } else {
                   7113:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7114:         $lines        = $bubble_lines_per_response{$question-1};
                   7115:     }
1.497     foxr     7116:     if ($lines > 1) {
1.503     raeburn  7117:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7118:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7119:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7120:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7121:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7122:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7123:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.572     www      7124:             $r->print(&mt("Although this particular question type requires handgrading, the instructions for this question in the exam directed students to leave [quant,_1,line] blank on their bubblesheets.",$lines).'<br /><br />'.&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.').'<br />'.&mt('The score for this question will be a sum of the numeric values for the selected bubbles from each line, where A=1 point, B=2 points etc.').'<br />'.&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.").'<br /><br />');
1.503     raeburn  7125:         } else {
                   7126:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7127:         }
1.497     foxr     7128:     }
                   7129:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7130:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7131: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7132: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7133:         push(@linenums,$current_line);
1.497     foxr     7134: 	$current_line++;
                   7135:     }
                   7136:     if ($lines > 1) {
                   7137: 	$r->print("<hr /><br />");
                   7138:     }
1.503     raeburn  7139:     return @linenums;
1.157     albertel 7140: }
1.423     albertel 7141: 
                   7142: =pod
                   7143: 
                   7144: =item scantron_bubble_selector
                   7145:   
                   7146:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7147:    possibly showing the existing the selected bubbles if known
1.423     albertel 7148: 
                   7149:  Arguments:
                   7150:     $r           - Apache request object
                   7151:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7152:     $line        - Number of the line being displayed.
1.503     raeburn  7153:     $questionnum - Question number (may include subquestion)
                   7154:     $error       - Type of error.
1.497     foxr     7155:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7156: 
                   7157: =cut
                   7158: 
1.157     albertel 7159: sub scantron_bubble_selector {
1.503     raeburn  7160:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7161:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7162: 
                   7163:     my $scmode=$$scan_config{'Qon'};
                   7164:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   7165: 
1.157     albertel 7166:     my @alphabet=('A'..'Z');
1.503     raeburn  7167:     $r->print(&Apache::loncommon::start_data_table().
                   7168:               &Apache::loncommon::start_data_table_row());
                   7169:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7170:     for (my $i=0;$i<$max+1;$i++) {
                   7171: 	$r->print("\n".'<td align="center">');
                   7172: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7173: 	else { $r->print('&nbsp;'); }
                   7174: 	$r->print('</td>');
                   7175:     }
1.503     raeburn  7176:     $r->print(&Apache::loncommon::end_data_table_row().
                   7177:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7178:     for (my $i=0;$i<$max;$i++) {
                   7179: 	$r->print("\n".
                   7180: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7181: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7182:     }
1.503     raeburn  7183:     my $nobub_checked = ' ';
                   7184:     if ($error eq 'missingbubble') {
                   7185:         $nobub_checked = ' checked = "checked" ';
                   7186:     }
                   7187:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7188: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7189:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7190:               $line.'" value="'.$questionnum.'" /></td>');
                   7191:     $r->print(&Apache::loncommon::end_data_table_row().
                   7192:               &Apache::loncommon::end_data_table());
1.157     albertel 7193: }
                   7194: 
1.423     albertel 7195: =pod
                   7196: 
                   7197: =item num_matches
                   7198: 
1.424     albertel 7199:    Counts the number of characters that are the same between the two arguments.
                   7200: 
                   7201:  Arguments:
                   7202:    $orig - CODE from the scanline
                   7203:    $code - CODE to match against
                   7204: 
                   7205:  Returns:
                   7206:    $count - integer count of the number of same characters between the
                   7207:             two arguments
                   7208: 
1.423     albertel 7209: =cut
                   7210: 
1.194     albertel 7211: sub num_matches {
                   7212:     my ($orig,$code) = @_;
                   7213:     my @code=split(//,$code);
                   7214:     my @orig=split(//,$orig);
                   7215:     my $same=0;
                   7216:     for (my $i=0;$i<scalar(@code);$i++) {
                   7217: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7218:     }
                   7219:     return $same;
                   7220: }
                   7221: 
1.423     albertel 7222: =pod
                   7223: 
                   7224: =item scantron_get_closely_matching_CODEs
                   7225: 
1.424     albertel 7226:    Cycles through all CODEs and finds the set that has the greatest
                   7227:    number of same characters as the provided CODE
                   7228: 
                   7229:  Arguments:
                   7230:    $allcodes - hash ref returned by &get_codes()
                   7231:    $CODE     - CODE from the current scanline
                   7232: 
                   7233:  Returns:
                   7234:    2 element list
                   7235:     - first elements is number of how closely matching the best fit is 
                   7236:       (5 means best set has 5 matching characters)
                   7237:     - second element is an arrary ref containing the set of valid CODEs
                   7238:       that best fit the passed in CODE
                   7239: 
1.423     albertel 7240: =cut
                   7241: 
1.194     albertel 7242: sub scantron_get_closely_matching_CODEs {
                   7243:     my ($allcodes,$CODE)=@_;
                   7244:     my @CODEs;
                   7245:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7246: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7247:     }
                   7248: 
                   7249:     return ($#CODEs,$CODEs[-1]);
                   7250: }
                   7251: 
1.423     albertel 7252: =pod
                   7253: 
                   7254: =item get_codes
                   7255: 
1.424     albertel 7256:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7257:    set of remembered CODEs.
                   7258: 
                   7259:  Arguments:
                   7260:   $old_name - name of the set of remembered CODEs
                   7261:   $cdom     - domain of the course
                   7262:   $cnum     - internal course name
                   7263: 
                   7264:  Returns:
                   7265:   %allcodes - keys are the valid CODEs, values are all 1
                   7266: 
1.423     albertel 7267: =cut
                   7268: 
1.194     albertel 7269: sub get_codes {
1.280     foxr     7270:     my ($old_name, $cdom, $cnum) = @_;
                   7271:     if (!$old_name) {
                   7272: 	$old_name=$env{'form.scantron_CODElist'};
                   7273:     }
                   7274:     if (!$cdom) {
                   7275: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7276:     }
                   7277:     if (!$cnum) {
                   7278: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7279:     }
1.278     albertel 7280:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7281: 				    $cdom,$cnum);
                   7282:     my %allcodes;
                   7283:     if ($result{"type\0$old_name"} eq 'number') {
                   7284: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7285:     } else {
                   7286: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7287:     }
1.194     albertel 7288:     return %allcodes;
                   7289: }
                   7290: 
1.423     albertel 7291: =pod
                   7292: 
                   7293: =item scantron_validate_CODE
                   7294: 
1.424     albertel 7295:    Validates all scanlines in the selected file to not have any
                   7296:    invalid or underspecified CODEs and that none of the codes are
                   7297:    duplicated if this was requested.
                   7298: 
1.423     albertel 7299: =cut
                   7300: 
1.157     albertel 7301: sub scantron_validate_CODE {
                   7302:     my ($r,$currentphase) = @_;
1.257     albertel 7303:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7304:     if ($scantron_config{'CODElocation'} &&
                   7305: 	$scantron_config{'CODEstart'} &&
                   7306: 	$scantron_config{'CODElength'}) {
1.257     albertel 7307: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7308: 	    &FIXME_blow_up()
                   7309: 	}
                   7310:     } else {
                   7311: 	return (0,$currentphase+1);
                   7312:     }
                   7313:     
                   7314:     my %usedCODEs;
                   7315: 
1.194     albertel 7316:     my %allcodes=&get_codes();
1.186     albertel 7317: 
1.574.2.7  raeburn  7318:     my $nav_error;
                   7319:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
                   7320:     if ($nav_error) {
                   7321:         $r->print(&navmap_errormsg());
                   7322:         return(1,$currentphase);
                   7323:     }
1.447     foxr     7324: 
1.186     albertel 7325:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7326:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7327: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7328: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7329: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7330: 						 $scan_data);
                   7331: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7332: 	my $error=0;
1.224     albertel 7333: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7334: 	    &scantron_get_correction($r,$i,$scan_record,
                   7335: 				     \%scantron_config,
                   7336: 				     $line,'incorrectCODE',\%allcodes);
                   7337: 	    return(1,$currentphase);
                   7338: 	}
1.221     albertel 7339: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7340: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7341: 	    &scantron_get_correction($r,$i,$scan_record,
                   7342: 				     \%scantron_config,
1.194     albertel 7343: 				     $line,'incorrectCODE',\%allcodes);
                   7344: 	    return(1,$currentphase);
1.186     albertel 7345: 	}
1.214     albertel 7346: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7347: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7348: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7349: 	    &scantron_get_correction($r,$i,$scan_record,
                   7350: 				     \%scantron_config,
1.194     albertel 7351: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7352: 	    return(1,$currentphase);
1.186     albertel 7353: 	}
1.524     raeburn  7354: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7355:     }
1.157     albertel 7356:     return (0,$currentphase+1);
                   7357: }
                   7358: 
1.423     albertel 7359: =pod
                   7360: 
                   7361: =item scantron_validate_doublebubble
                   7362: 
1.424     albertel 7363:    Validates all scanlines in the selected file to not have any
                   7364:    bubble lines with multiple bubbles marked.
                   7365: 
1.423     albertel 7366: =cut
                   7367: 
1.157     albertel 7368: sub scantron_validate_doublebubble {
                   7369:     my ($r,$currentphase) = @_;
                   7370:     #get student info
                   7371:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7372:     my %idmap=&username_to_idmap($classlist);
                   7373: 
                   7374:     #get scantron line setup
1.257     albertel 7375:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7376:     my ($scanlines,$scan_data)=&scantron_getfile();
1.574.2.7  raeburn  7377:     my $nav_error;
                   7378:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
                   7379:     if ($nav_error) {
                   7380:         $r->print(&navmap_errormsg());
                   7381:         return(1,$currentphase);
                   7382:     }
1.447     foxr     7383: 
1.157     albertel 7384:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7385: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7386: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7387: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7388: 						 $scan_data);
                   7389: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7390: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7391: 				 'doublebubble',
                   7392: 				 $$scan_record{'scantron.doubleerror'});
                   7393:     	return (1,$currentphase);
                   7394:     }
                   7395:     return (0,$currentphase+1);
                   7396: }
                   7397: 
1.423     albertel 7398: 
1.503     raeburn  7399: sub scantron_get_maxbubble {
1.574.2.7  raeburn  7400:     my ($nav_error) = @_;
                   7401: 
1.257     albertel 7402:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7403: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7404: 	&restore_bubble_lines();
1.257     albertel 7405: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7406:     }
1.330     albertel 7407: 
1.447     foxr     7408:     my (undef, undef, $sequence) =
1.257     albertel 7409: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7410: 
1.447     foxr     7411:     my $navmap=Apache::lonnavmaps::navmap->new();
1.574.2.7  raeburn  7412:     unless (ref($navmap)) {
                   7413:         if (ref($nav_error)) {
                   7414:             $$nav_error = 1;
                   7415:         }
1.574.2.8  raeburn  7416:         return;
1.574.2.7  raeburn  7417:     }
1.191     albertel 7418:     my $map=$navmap->getResourceByUrl($sequence);
                   7419:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 7420: 
                   7421:     &Apache::lonxml::clear_problem_counter();
                   7422: 
1.557     raeburn  7423:     my $uname       = $env{'user.name'};
                   7424:     my $udom        = $env{'user.domain'};
1.435     foxr     7425:     my $cid         = $env{'request.course.id'};
                   7426:     my $total_lines = 0;
                   7427:     %bubble_lines_per_response = ();
1.447     foxr     7428:     %first_bubble_line         = ();
1.503     raeburn  7429:     %subdivided_bubble_lines   = ();
                   7430:     %responsetype_per_response = ();
1.554     raeburn  7431: 
1.447     foxr     7432:     my $response_number = 0;
                   7433:     my $bubble_line     = 0;
1.191     albertel 7434:     foreach my $resource (@resources) {
1.542     raeburn  7435:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
                   7436:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7437: 	    foreach my $part_id (@{$parts}) {
                   7438:                 my $lines;
                   7439: 
                   7440: 	        # TODO - make this a persistent hash not an array.
                   7441: 
                   7442:                 # optionresponse, matchresponse and rankresponse type items 
                   7443:                 # render as separate sub-questions in exam mode.
                   7444:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7445:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7446:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7447:                     my ($numbub,$numshown);
                   7448:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7449:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   7450:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   7451:                         }
                   7452:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   7453:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7454:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   7455:                         }
                   7456:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7457:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7458:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7459:                         }
                   7460:                     }
                   7461:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7462:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7463:                     }
                   7464:                     my $bubbles_per_line = 10;
                   7465:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
                   7466:                     if (($numbub % $bubbles_per_line) != 0) {
                   7467:                         $inner_bubble_lines++;
                   7468:                     }
                   7469:                     for (my $i=0; $i<$numshown; $i++) {
                   7470:                         $subdivided_bubble_lines{$response_number} .= 
                   7471:                             $inner_bubble_lines.',';
                   7472:                     }
                   7473:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7474:                     $lines = $numshown * $inner_bubble_lines;
                   7475:                 } else {
                   7476:                     $lines = $analysis->{"$part_id.bubble_lines"};
                   7477:                 } 
                   7478: 
                   7479:                 $first_bubble_line{$response_number} = $bubble_line;
                   7480: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7481:                 $responsetype_per_response{$response_number} = 
                   7482:                     $analysis->{$part_id.'.type'};
                   7483: 	        $response_number++;
                   7484: 
                   7485: 	        $bubble_line +=  $lines;
                   7486: 	        $total_lines +=  $lines;
                   7487: 	    }
                   7488:         }
                   7489:     }
1.552     raeburn  7490:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  7491: 
                   7492:     &save_bubble_lines();
                   7493:     $env{'form.scantron_maxbubble'} =
                   7494: 	$total_lines;
                   7495:     return $env{'form.scantron_maxbubble'};
                   7496: }
1.523     raeburn  7497: 
1.157     albertel 7498: sub scantron_validate_missingbubbles {
                   7499:     my ($r,$currentphase) = @_;
                   7500:     #get student info
                   7501:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7502:     my %idmap=&username_to_idmap($classlist);
                   7503: 
                   7504:     #get scantron line setup
1.257     albertel 7505:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7506:     my ($scanlines,$scan_data)=&scantron_getfile();
1.574.2.7  raeburn  7507:     my $nav_error;
                   7508:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   7509:     if ($nav_error) {
                   7510:         return(1,$currentphase);
                   7511:     }
1.157     albertel 7512:     if (!$max_bubble) { $max_bubble=2**31; }
                   7513:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7514: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7515: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7516: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7517: 						 $scan_data);
                   7518: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7519: 	my @to_correct;
1.470     foxr     7520: 	
                   7521: 	# Probably here's where the error is...
                   7522: 
1.157     albertel 7523: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7524:             my $lastbubble;
                   7525:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7526:                my $question = $1;
                   7527:                my $subquestion = $2;
                   7528:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7529:                my $first = $first_bubble_line{$question-1};
                   7530:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7531:                my $subcount = 1;
                   7532:                while ($subcount<$subquestion) {
                   7533:                    $first += $subans[$subcount-1];
                   7534:                    $subcount ++;
                   7535:                }
                   7536:                my $count = $subans[$subquestion-1];
                   7537:                $lastbubble = $first + $count;
                   7538:             } else {
                   7539:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7540:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7541:             }
                   7542:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7543: 	    push(@to_correct,$missing);
                   7544: 	}
                   7545: 	if (@to_correct) {
                   7546: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7547: 				     $line,'missingbubble',\@to_correct);
                   7548: 	    return (1,$currentphase);
                   7549: 	}
                   7550: 
                   7551:     }
                   7552:     return (0,$currentphase+1);
                   7553: }
                   7554: 
1.423     albertel 7555: 
1.82      albertel 7556: sub scantron_process_students {
1.75      albertel 7557:     my ($r) = @_;
1.513     foxr     7558: 
1.257     albertel 7559:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 7560:     my ($symb)=&get_symb($r);
1.513     foxr     7561:     if (!$symb) {
                   7562: 	return '';
                   7563:     }
1.324     albertel 7564:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7565: 
1.257     albertel 7566:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7567:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7568:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7569:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7570:     my $navmap=Apache::lonnavmaps::navmap->new();
1.574.2.7  raeburn  7571:     unless (ref($navmap)) {
                   7572:         $r->print(&navmap_errormsg());
                   7573:         return '';
                   7574:     }  
1.83      albertel 7575:     my $map=$navmap->getResourceByUrl($sequence);
                   7576:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.557     raeburn  7577:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7578:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7579:                             \%grader_randomlists_by_symb);
1.574.2.8  raeburn  7580:     my $resource_error;
1.557     raeburn  7581:     foreach my $resource (@resources) {
1.574.2.8  raeburn  7582:         my $ressymb;
                   7583:         if (ref($resource)) {
                   7584:             $ressymb = $resource->symb();
                   7585:         } else {
                   7586:             $resource_error = 1;
                   7587:             last;
                   7588:         }
1.557     raeburn  7589:         my ($analysis,$parts) =
                   7590:             &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7591:                                       $env{'user.name'},$env{'user.domain'},1);
                   7592:         $grader_partids_by_symb{$ressymb} = $parts;
                   7593:         if (ref($analysis) eq 'HASH') {
                   7594:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7595:                 $grader_randomlists_by_symb{$ressymb} = 
                   7596:                     $analysis->{'parts_withrandomlist'};
                   7597:             }
                   7598:         }
                   7599:     }
1.574.2.8  raeburn  7600:     if ($resource_error) {
                   7601:         $r->print(&navmap_errormsg());
                   7602:         return '';
                   7603:     }
1.557     raeburn  7604: 
1.554     raeburn  7605:     my ($uname,$udom);
1.82      albertel 7606:     my $result= <<SCANTRONFORM;
1.81      albertel 7607: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7608:   <input type="hidden" name="command" value="scantron_configphase" />
                   7609:   $default_form_data
                   7610: SCANTRONFORM
1.82      albertel 7611:     $r->print($result);
                   7612: 
                   7613:     my @delayqueue;
1.542     raeburn  7614:     my (%completedstudents,%scandata);
1.140     albertel 7615:     
1.520     www      7616:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7617:     my $count=&get_todo_count($scanlines,$scan_data);
1.574.2.5  raeburn  7618:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
                   7619:  				    'Bubblesheet Progress',$count,
1.195     albertel 7620: 				    'inline',undef,'scantronupload');
1.140     albertel 7621:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7622: 					  'Processing first student');
1.542     raeburn  7623:     $r->print('<br />');
1.140     albertel 7624:     my $start=&Time::HiRes::time();
1.158     albertel 7625:     my $i=-1;
1.542     raeburn  7626:     my $started;
1.447     foxr     7627: 
1.574.2.7  raeburn  7628:     my $nav_error;
                   7629:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   7630:     if ($nav_error) {
                   7631:         $r->print(&navmap_errormsg());
                   7632:         return '';
                   7633:     }
1.513     foxr     7634: 
                   7635:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7636:     # the user and return.
                   7637: 
                   7638:     if ($ssi_error) {
                   7639: 	$r->print("</form>");
                   7640: 	&ssi_print_error($r);
                   7641: 	$r->print(&show_grading_menu_form($symb));
1.520     www      7642:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7643: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7644:     }
1.447     foxr     7645: 
1.542     raeburn  7646:     my %lettdig = &letter_to_digits();
                   7647:     my $numletts = scalar(keys(%lettdig));
                   7648: 
1.157     albertel 7649:     while ($i<$scanlines->{'count'}) {
                   7650:  	($uname,$udom)=('','');
                   7651:  	$i++;
1.200     albertel 7652:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7653:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7654: 	if ($started) {
                   7655: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7656: 						     'last student');
                   7657: 	}
                   7658: 	$started=1;
1.157     albertel 7659:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7660:  						 $scan_data);
                   7661:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7662:  					      \%idmap,$i)) {
                   7663:   	    &scantron_add_delay(\@delayqueue,$line,
                   7664:  				'Unable to find a student that matches',1);
                   7665:  	    next;
                   7666:   	}
                   7667:  	if (exists $completedstudents{$uname}) {
                   7668:  	    &scantron_add_delay(\@delayqueue,$line,
                   7669:  				'Student '.$uname.' has multiple sheets',2);
                   7670:  	    next;
                   7671:  	}
                   7672:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7673: 
1.574.2.8  raeburn  7674:         my (%partids_by_symb,$res_error);
1.554     raeburn  7675:         foreach my $resource (@resources) {
1.574.2.8  raeburn  7676:             my $ressymb;
                   7677:             if (ref($resource)) {
                   7678:                 $ressymb = $resource->symb();
                   7679:             } else {
                   7680:                 $res_error = 1;
                   7681:                 last;
                   7682:             }
1.557     raeburn  7683:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   7684:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   7685:                 my ($analysis,$parts) =
                   7686:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
                   7687:                 $partids_by_symb{$ressymb} = $parts;
                   7688:             } else {
                   7689:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   7690:             }
1.554     raeburn  7691:         }
                   7692: 
1.574.2.8  raeburn  7693:         if ($res_error) {
                   7694:             &scantron_add_delay(\@delayqueue,$line,
                   7695:                                 'An error occurred while grading student '.$uname,2);
                   7696:             next;
                   7697:         }
                   7698: 
1.330     albertel 7699: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7700:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7701: 
                   7702: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7703: 	    &scantron_putfile($scanlines,$scan_data);
                   7704: 	}
1.161     albertel 7705: 	
1.542     raeburn  7706:         my $scancode;
                   7707:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   7708:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   7709:             $scancode = $scan_record->{'scantron.CODE'};
                   7710:         } else {
                   7711:             $scancode = '';
                   7712:         }
                   7713: 
                   7714:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.554     raeburn  7715:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
1.542     raeburn  7716:             $ssi_error = 0; # So end of handler error message does not trigger.
                   7717:             $r->print("</form>");
                   7718:             &ssi_print_error($r);
                   7719:             $r->print(&show_grading_menu_form($symb));
                   7720:             &Apache::lonnet::remove_lock($lock);
                   7721:             return '';      # Why return ''?  Beats me.
                   7722:         }
1.513     foxr     7723: 
1.140     albertel 7724: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  7725:         if ($env{'form.verifyrecord'}) {
                   7726:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7727:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7728:             chomp($studentdata);
                   7729:             $studentdata =~ s/\r$//;
                   7730:             my $studentrecord = '';
                   7731:             my $counter = -1;
                   7732:             foreach my $resource (@resources) {
1.554     raeburn  7733:                 my $ressymb = $resource->symb();
1.542     raeburn  7734:                 ($counter,my $recording) =
                   7735:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7736:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7737:                                              \%scantron_config,\%lettdig,$numletts);
                   7738:                 $studentrecord .= $recording;
                   7739:             }
                   7740:             if ($studentrecord ne $studentdata) {
1.554     raeburn  7741:                 &Apache::lonxml::clear_problem_counter();
                   7742:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
                   7743:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
                   7744:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   7745:                     $r->print("</form>");
                   7746:                     &ssi_print_error($r);
                   7747:                     $r->print(&show_grading_menu_form($symb));
                   7748:                     &Apache::lonnet::remove_lock($lock);
                   7749:                     delete($completedstudents{$uname});
                   7750:                     return '';
                   7751:                 }
1.542     raeburn  7752:                 $counter = -1;
                   7753:                 $studentrecord = '';
                   7754:                 foreach my $resource (@resources) {
1.554     raeburn  7755:                     my $ressymb = $resource->symb();
1.542     raeburn  7756:                     ($counter,my $recording) =
                   7757:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7758:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7759:                                                  \%scantron_config,\%lettdig,$numletts);
                   7760:                     $studentrecord .= $recording;
                   7761:                 }
                   7762:                 if ($studentrecord ne $studentdata) {
                   7763:                     $r->print('<p><span class="LC_error">');
                   7764:                     if ($scancode eq '') {
                   7765:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
                   7766:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   7767:                     } else {
                   7768:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
                   7769:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   7770:                     }
                   7771:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   7772:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   7773:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   7774:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   7775:                               &Apache::loncommon::start_data_table_row().
                   7776:                               '<td>'.&mt('Bubble Sheet').'</td>'.
                   7777:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
                   7778:                               &Apache::loncommon::end_data_table_row().
                   7779:                               &Apache::loncommon::start_data_table_row().
                   7780:                               '<td>Stored submissions</td>'.
                   7781:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
                   7782:                               &Apache::loncommon::end_data_table_row().
                   7783:                               &Apache::loncommon::end_data_table().'</p>');
                   7784:                 } else {
                   7785:                     $r->print('<br /><span class="LC_warning">'.
                   7786:                              &mt('A second grading pass was needed for user: [_1] with ID: [_2], because a mismatch was seen on the first pass.',$uname.':'.$udom,$scan_record->{'scantron.ID'}).'<br />'.
                   7787:                              &mt("As a consequence, this user's submission history records two tries.").
                   7788:                                  '</span><br />');
                   7789:                 }
                   7790:             }
                   7791:         }
1.543     raeburn  7792:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7793:     } continue {
1.330     albertel 7794: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  7795: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 7796:     }
1.140     albertel 7797:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7798:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7799: #    my $lasttime = &Time::HiRes::time()-$start;
                   7800: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7801: 
1.200     albertel 7802:     $r->print("</form>");
1.324     albertel 7803:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 7804:     return '';
1.75      albertel 7805: }
1.157     albertel 7806: 
1.557     raeburn  7807: sub graders_resources_pass {
                   7808:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
                   7809:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   7810:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   7811:         foreach my $resource (@{$resources}) {
                   7812:             my $ressymb = $resource->symb();
                   7813:             my ($analysis,$parts) =
                   7814:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7815:                                           $env{'user.name'},$env{'user.domain'},1);
                   7816:             $grader_partids_by_symb->{$ressymb} = $parts;
                   7817:             if (ref($analysis) eq 'HASH') {
                   7818:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7819:                     $grader_randomlists_by_symb->{$ressymb} =
                   7820:                         $analysis->{'parts_withrandomlist'};
                   7821:                 }
                   7822:             }
                   7823:         }
                   7824:     }
                   7825:     return;
                   7826: }
                   7827: 
1.542     raeburn  7828: sub grade_student_bubbles {
1.554     raeburn  7829:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
                   7830:     if (ref($resources) eq 'ARRAY') {
                   7831:         my $count = 0;
                   7832:         foreach my $resource (@{$resources}) {
                   7833:             my $ressymb = $resource->symb();
                   7834:             my %form = ('submitted'      => 'scantron',
                   7835:                         'grade_target'   => 'grade',
                   7836:                         'grade_username' => $uname,
                   7837:                         'grade_domain'   => $udom,
                   7838:                         'grade_courseid' => $env{'request.course.id'},
                   7839:                         'grade_symb'     => $ressymb,
                   7840:                         'CODE'           => $scancode
                   7841:                        );
                   7842:             if (ref($parts) eq 'HASH') {
                   7843:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   7844:                     foreach my $part (@{$parts->{$ressymb}}) {
                   7845:                         $form{'scantron_questnum_start.'.$part} =
                   7846:                             1+$env{'form.scantron.first_bubble_line.'.$count};
                   7847:                         $count++;
                   7848:                     }
                   7849:                 }
                   7850:             }
                   7851:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   7852:             return 'ssi_error' if ($ssi_error);
                   7853:             last if (&Apache::loncommon::connection_aborted($r));
                   7854:         }
1.542     raeburn  7855:     }
                   7856:     return;
                   7857: }
                   7858: 
1.157     albertel 7859: sub scantron_upload_scantron_data {
                   7860:     my ($r)=@_;
1.565     raeburn  7861:     my $dom = $env{'request.role.domain'};
                   7862:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   7863:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 7864:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7865: 							  'domainid',
1.565     raeburn  7866: 							  'coursename',$dom);
                   7867:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   7868:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.324     albertel 7869:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.574.2.3  raeburn  7870:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   7871:     my $nocourseid_alert = &mt("Please use the 'Select Course' link to open a separate window where you can search for a course to which a file can be uploaded.");
1.492     albertel 7872:     $r->print('
1.157     albertel 7873: <script type="text/javascript" language="javascript">
                   7874:     function checkUpload(formname) {
                   7875: 	if (formname.upfile.value == "") {
1.574.2.3  raeburn  7876: 	    alert("'.$nofile_alert.'");
1.157     albertel 7877: 	    return false;
                   7878: 	}
1.565     raeburn  7879:         if (formname.courseid.value == "") {
1.574.2.3  raeburn  7880:             alert("'.$nocourseid_alert.'");
1.565     raeburn  7881:             return false;
                   7882:         }
1.157     albertel 7883: 	formname.submit();
                   7884:     }
1.565     raeburn  7885: 
                   7886:     function ToSyllabus() {
                   7887:         var cdom = '."'$dom'".';
                   7888:         var cnum = document.rules.courseid.value;
                   7889:         if (cdom == "" || cdom == null) {
                   7890:             return;
                   7891:         }
                   7892:         if (cnum == "" || cnum == null) {
                   7893:            return;
                   7894:         }
                   7895:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   7896:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   7897:         return;
                   7898:     }
                   7899: 
1.157     albertel 7900: </script>
                   7901: 
1.566     raeburn  7902: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
                   7903: 
1.492     albertel 7904: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  7905: '.$default_form_data.
                   7906:   &Apache::lonhtmlcommon::start_pick_box().
                   7907:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   7908:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   7909:   &Apache::lonhtmlcommon::row_closure().
                   7910:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   7911:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   7912:   &Apache::lonhtmlcommon::row_closure().
                   7913:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   7914:   '<input name="domainid" type="hidden" />'.$domdesc.
                   7915:   &Apache::lonhtmlcommon::row_closure().
                   7916:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   7917:   '<input type="file" name="upfile" size="50" />'.
                   7918:   &Apache::lonhtmlcommon::row_closure(1).
                   7919:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   7920: 
1.492     albertel 7921: <input name="command" value="scantronupload_save" type="hidden" />
1.574.2.5  raeburn  7922: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 7923: </form>
1.492     albertel 7924: ');
1.157     albertel 7925:     return '';
                   7926: }
                   7927: 
1.423     albertel 7928: 
1.157     albertel 7929: sub scantron_upload_scantron_data_save {
                   7930:     my($r)=@_;
1.324     albertel 7931:     my ($symb)=&get_symb($r,1);
1.182     albertel 7932:     my $doanotherupload=
                   7933: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7934: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 7935: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 7936: 	'</form>'."\n";
1.257     albertel 7937:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7938: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7939: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.574.2.5  raeburn  7940: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.182     albertel 7941: 	if ($symb) {
1.324     albertel 7942: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 7943: 	} else {
                   7944: 	    $r->print($doanotherupload);
                   7945: 	}
1.162     albertel 7946: 	return '';
                   7947:     }
1.257     albertel 7948:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  7949:     my $uploadedfile;
1.567     raeburn  7950:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
1.257     albertel 7951:     if (length($env{'form.upfile'}) < 2) {
1.568     raeburn  7952:         $r->print(&mt('[_1]Error:[_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.','<span class="LC_error">','</span>','<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 7953:     } else {
1.568     raeburn  7954:         my $result = 
                   7955:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   7956:                                             $env{'form.courseid'},$env{'form.domainid'});
                   7957: 	if ($result =~ m{^/uploaded/}) {
1.567     raeburn  7958: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
                   7959:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
                   7960: 			  '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  7961:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  7962:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  7963:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 7964: 	} else {
1.567     raeburn  7965: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
                   7966:                           '<span class="LC_error">','</span>',$result,
1.568     raeburn  7967: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 7968: 	}
                   7969:     }
1.174     albertel 7970:     if ($symb) {
1.209     ng       7971: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 7972:     } else {
1.182     albertel 7973: 	$r->print($doanotherupload);
1.174     albertel 7974:     }
1.157     albertel 7975:     return '';
                   7976: }
                   7977: 
1.567     raeburn  7978: sub validate_uploaded_scantron_file {
                   7979:     my ($cdom,$cname,$fname) = @_;
                   7980:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   7981:     my @lines;
                   7982:     if ($scanlines ne '-1') {
                   7983:         @lines=split("\n",$scanlines,-1);
                   7984:     }
                   7985:     my $output;
                   7986:     if (@lines) {
                   7987:         my (%counts,$max_match_format);
                   7988:         my ($max_match_count,$max_match_pct) = (0,0);
                   7989:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   7990:         my %idmap = &username_to_idmap($classlist);
                   7991:         foreach my $key (keys(%idmap)) {
                   7992:             my $lckey = lc($key);
                   7993:             $idmap{$lckey} = $idmap{$key};
                   7994:         }
                   7995:         my %unique_formats;
                   7996:         my @formatlines = &get_scantronformat_file();
                   7997:         foreach my $line (@formatlines) {
                   7998:             chomp($line);
                   7999:             my @config = split(/:/,$line);
                   8000:             my $idstart = $config[5];
                   8001:             my $idlength = $config[6];
                   8002:             if (($idstart ne '') && ($idlength > 0)) {
                   8003:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   8004:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   8005:                 } else {
                   8006:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   8007:                 }
                   8008:             }
                   8009:         }
                   8010:         foreach my $key (keys(%unique_formats)) {
                   8011:             my ($idstart,$idlength) = split(':',$key);
                   8012:             %{$counts{$key}} = (
                   8013:                                'found'   => 0,
                   8014:                                'total'   => 0,
                   8015:                               );
                   8016:             foreach my $line (@lines) {
                   8017:                 next if ($line =~ /^#/);
                   8018:                 next if ($line =~ /^[\s\cz]*$/);
                   8019:                 my $id = substr($line,$idstart-1,$idlength);
                   8020:                 $id = lc($id);
                   8021:                 if (exists($idmap{$id})) {
                   8022:                     $counts{$key}{'found'} ++;
                   8023:                 }
                   8024:                 $counts{$key}{'total'} ++;
                   8025:             }
                   8026:             if ($counts{$key}{'total'}) {
                   8027:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   8028:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   8029:                     $max_match_pct = $percent_match;
                   8030:                     $max_match_format = $key;
                   8031:                     $max_match_count = $counts{$key}{'total'};
                   8032:                 }
                   8033:             }
                   8034:         }
                   8035:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8036:             my $format_descs;
                   8037:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8038:             for (my $i=0; $i<$numwithformat; $i++) {
                   8039:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8040:                 if ($i<$numwithformat-2) {
                   8041:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8042:                 } elsif ($i==$numwithformat-2) {
                   8043:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8044:                 } elsif ($i==$numwithformat-1) {
                   8045:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8046:                 }
                   8047:             }
                   8048:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
                   8049:             $output .= '<br />'.&mt('Comparison of student IDs in the uploaded file with the course roster found matches for [_1] of the [_2] entries in the file (for the format defined for [_3]).','<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   8050:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
                   8051:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
                   8052:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
                   8053:                                   '<i>'.$cdom.'</i>').'</li>'.
                   8054:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8055:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
                   8056:                        '</ul>';
                   8057:         }
                   8058:     } else {
                   8059:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
                   8060:     }
                   8061:     return $output;
                   8062: }
                   8063: 
1.202     albertel 8064: sub valid_file {
                   8065:     my ($requested_file)=@_;
                   8066:     foreach my $filename (sort(&scantron_filenames())) {
                   8067: 	if ($requested_file eq $filename) { return 1; }
                   8068:     }
                   8069:     return 0;
                   8070: }
                   8071: 
                   8072: sub scantron_download_scantron_data {
                   8073:     my ($r)=@_;
1.324     albertel 8074:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 8075:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8076:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8077:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8078:     if (! &valid_file($file)) {
1.492     albertel 8079: 	$r->print('
1.202     albertel 8080: 	<p>
1.492     albertel 8081: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 8082:         </p>
1.492     albertel 8083: ');
1.324     albertel 8084: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 8085: 	return;
                   8086:     }
                   8087:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8088:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8089:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8090:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8091:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8092:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8093:     $r->print('
1.202     albertel 8094:     <p>
1.492     albertel 8095: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   8096: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8097:     </p>
                   8098:     <p>
1.492     albertel 8099: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8100: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8101:     </p>
                   8102:     <p>
1.492     albertel 8103: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8104: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8105:     </p>
1.492     albertel 8106: ');
1.324     albertel 8107:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 8108:     return '';
                   8109: }
1.157     albertel 8110: 
1.523     raeburn  8111: sub checkscantron_results {
                   8112:     my ($r) = @_;
                   8113:     my ($symb)=&get_symb($r);
                   8114:     if (!$symb) {return '';}
                   8115:     my $grading_menu_button=&show_grading_menu_form($symb);
                   8116:     my $cid = $env{'request.course.id'};
1.542     raeburn  8117:     my %lettdig = &letter_to_digits();
1.523     raeburn  8118:     my $numletts = scalar(keys(%lettdig));
                   8119:     my $cnum = $env{'course.'.$cid.'.num'};
                   8120:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8121:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8122:     my %record;
                   8123:     my %scantron_config =
                   8124:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
                   8125:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8126:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8127:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8128:     my $navmap=Apache::lonnavmaps::navmap->new();
1.574.2.7  raeburn  8129:     unless (ref($navmap)) {
                   8130:         $r->print(&navmap_errormsg());
                   8131:         return '';
                   8132:     }
1.523     raeburn  8133:     my $map=$navmap->getResourceByUrl($sequence);
1.557     raeburn  8134:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8135:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   8136:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
                   8137: 
1.554     raeburn  8138:     my ($uname,$udom);
1.523     raeburn  8139:     my (%scandata,%lastname,%bylast);
                   8140:     $r->print('
                   8141: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8142: 
                   8143:     my @delayqueue;
                   8144:     my %completedstudents;
                   8145: 
                   8146:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
1.574.2.5  raeburn  8147:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
                   8148:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
1.523     raeburn  8149:                                     'inline',undef,'checkscantron');
1.546     raeburn  8150:     my ($username,$domain,$started);
1.574.2.7  raeburn  8151:     my $nav_error;
                   8152:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   8153:     if ($nav_error) {
                   8154:         $r->print(&navmap_errormsg());
                   8155:         return '';
                   8156:     }
1.523     raeburn  8157: 
                   8158:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   8159:                                           'Processing first student');
                   8160:     my $start=&Time::HiRes::time();
                   8161:     my $i=-1;
                   8162: 
                   8163:     while ($i<$scanlines->{'count'}) {
                   8164:         ($username,$domain,$uname)=('','','');
                   8165:         $i++;
                   8166:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8167:         if ($line=~/^[\s\cz]*$/) { next; }
                   8168:         if ($started) {
                   8169:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8170:                                                      'last student');
                   8171:         }
                   8172:         $started=1;
                   8173:         my $scan_record=
                   8174:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8175:                                                      $scan_data);
                   8176:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   8177:                                                               \%idmap,$i)) {
                   8178:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8179:                                 'Unable to find a student that matches',1);
                   8180:             next;
                   8181:         }
                   8182:         if (exists $completedstudents{$uname}) {
                   8183:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8184:                                 'Student '.$uname.' has multiple sheets',2);
                   8185:             next;
                   8186:         }
                   8187:         my $pid = $scan_record->{'scantron.ID'};
                   8188:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8189:         push(@{$bylast{$lastname{$pid}}},$pid);
                   8190:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8191:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8192:         chomp($scandata{$pid});
                   8193:         $scandata{$pid} =~ s/\r$//;
                   8194:         ($username,$domain)=split(/:/,$uname);
                   8195:         my $counter = -1;
                   8196:         foreach my $resource (@resources) {
1.557     raeburn  8197:             my $parts;
1.554     raeburn  8198:             my $ressymb = $resource->symb();
1.557     raeburn  8199:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8200:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8201:                 (my $analysis,$parts) =
                   8202:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
                   8203:             } else {
                   8204:                 $parts = $grader_partids_by_symb{$ressymb};
                   8205:             }
1.542     raeburn  8206:             ($counter,my $recording) =
                   8207:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  8208:                                          $scandata{$pid},$parts,
1.542     raeburn  8209:                                          \%scantron_config,\%lettdig,$numletts);
                   8210:             $record{$pid} .= $recording;
1.523     raeburn  8211:         }
                   8212:     }
                   8213:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8214:     $r->print('<br />');
                   8215:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8216:     $passed = 0;
                   8217:     $failed = 0;
                   8218:     $numstudents = 0;
                   8219:     foreach my $last (sort(keys(%bylast))) {
                   8220:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8221:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8222:                 my $showscandata = $scandata{$pid};
                   8223:                 my $showrecord = $record{$pid};
                   8224:                 $showscandata =~ s/\s/&nbsp;/g;
                   8225:                 $showrecord =~ s/\s/&nbsp;/g;
                   8226:                 if ($scandata{$pid} eq $record{$pid}) {
                   8227:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8228:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.574.2.5  raeburn  8229: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  8230: '</tr>'."\n".
                   8231: '<tr class="'.$css_class.'">'."\n".
                   8232: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8233:                     $passed ++;
                   8234:                 } else {
                   8235:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.574.2.5  raeburn  8236:                     $badstudents .= '<tr class="'.$css_class.'"><td>'.&mt('Bubblesheet').'</td><td><span class="LC_nobreak">'.$scandata{$pid}.'</span></td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  8237: '</tr>'."\n".
                   8238: '<tr class="'.$css_class.'">'."\n".
                   8239: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8240: '</tr>'."\n";
                   8241:                     $failed ++;
                   8242:                 }
                   8243:                 $numstudents ++;
                   8244:             }
                   8245:         }
                   8246:     }
1.572     www      8247:     $r->print('<p>'.&mt('Comparison of bubblesheet data (including corrections) with corresponding submission records (most recent submission) for <b>[quant,_1,student]</b>  ([_2] scantron lines/student).',$numstudents,$env{'form.scantron_maxbubble'}).'</p>');
1.523     raeburn  8248:     $r->print('<p>'.&mt('Exact matches for <b>[quant,_1,student]</b>.',$passed).'<br />'.&mt('Discrepancies detected for <b>[quant,_1,student]</b>.',$failed).'</p>');
                   8249:     if ($passed) {
1.572     www      8250:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8251:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8252:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8253:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8254:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8255:                  $okstudents."\n".
                   8256:                  &Apache::loncommon::end_data_table().'<br />');
                   8257:     }
                   8258:     if ($failed) {
1.572     www      8259:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8260:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8261:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8262:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8263:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8264:                  $badstudents."\n".
                   8265:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      8266:                  &mt('Differences can occur if submissions were modified using manual grading after a bubblesheet grading pass.').'<br />'.&mt('If unexpected discrepancies were detected, it is recommended that you inspect the original bubblesheets.');  
1.523     raeburn  8267:     }
                   8268:     $r->print('</form><br />'.$grading_menu_button);
                   8269:     return;
                   8270: }
                   8271: 
1.542     raeburn  8272: sub verify_scantron_grading {
1.554     raeburn  8273:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.542     raeburn  8274:         $scantron_config,$lettdig,$numletts) = @_;
                   8275:     my ($record,%expected,%startpos);
                   8276:     return ($counter,$record) if (!ref($resource));
                   8277:     return ($counter,$record) if (!$resource->is_problem());
                   8278:     my $symb = $resource->symb();
1.554     raeburn  8279:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   8280:     foreach my $part_id (@{$partids}) {
1.542     raeburn  8281:         $counter ++;
                   8282:         $expected{$part_id} = 0;
                   8283:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8284:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8285:             foreach my $item (@sub_lines) {
                   8286:                 $expected{$part_id} += $item;
                   8287:             }
                   8288:         } else {
                   8289:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8290:         }
                   8291:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8292:     }
                   8293:     if ($symb) {
                   8294:         my %recorded;
                   8295:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8296:         if ($returnhash{'version'}) {
                   8297:             my %lasthash=();
                   8298:             my $version;
                   8299:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8300:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8301:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8302:                 }
                   8303:             }
                   8304:             foreach my $key (keys(%lasthash)) {
                   8305:                 if ($key =~ /\.scantron$/) {
                   8306:                     my $value = &unescape($lasthash{$key});
                   8307:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8308:                     if ($value eq '') {
                   8309:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8310:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8311:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8312:                             }
                   8313:                         }
                   8314:                     } else {
                   8315:                         my @tocheck;
                   8316:                         my @items = split(//,$value);
                   8317:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8318:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8319:                             if (@items < $expected{$part_id}) {
                   8320:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8321:                                 my @singles = split(//,$fragment);
                   8322:                                 foreach my $pos (@singles) {
                   8323:                                     if ($pos eq ' ') {
                   8324:                                         push(@tocheck,$pos);
                   8325:                                     } else {
                   8326:                                         my $next = shift(@items);
                   8327:                                         push(@tocheck,$next);
                   8328:                                     }
                   8329:                                 }
                   8330:                             } else {
                   8331:                                 @tocheck = @items;
                   8332:                             }
                   8333:                             foreach my $letter (@tocheck) {
                   8334:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8335:                                     if ($letter !~ /^[A-J]$/) {
                   8336:                                         $letter = $scantron_config->{'Qoff'};
                   8337:                                     }
                   8338:                                     $recorded{$part_id} .= $letter;
                   8339:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8340:                                     my $digit;
                   8341:                                     if ($letter !~ /^[A-J]$/) {
                   8342:                                         $digit = $scantron_config->{'Qoff'};
                   8343:                                     } else {
                   8344:                                         $digit = $lettdig->{$letter};
                   8345:                                     }
                   8346:                                     $recorded{$part_id} .= $digit;
                   8347:                                 }
                   8348:                             }
                   8349:                         } else {
                   8350:                             @tocheck = @items;
                   8351:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8352:                                 my $curr_sub = shift(@tocheck);
                   8353:                                 my $digit;
                   8354:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8355:                                     $digit = $lettdig->{$curr_sub}-1;
                   8356:                                 }
                   8357:                                 if ($curr_sub eq 'J') {
                   8358:                                     $digit += scalar($numletts);
                   8359:                                 }
                   8360:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8361:                                     if ($j == $digit) {
                   8362:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8363:                                     } else {
                   8364:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8365:                                     }
                   8366:                                 }
                   8367:                             }
                   8368:                         }
                   8369:                     }
                   8370:                 }
                   8371:             }
                   8372:         }
1.554     raeburn  8373:         foreach my $part_id (@{$partids}) {
1.542     raeburn  8374:             if ($recorded{$part_id} eq '') {
                   8375:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8376:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8377:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8378:                     }
                   8379:                 }
                   8380:             }
                   8381:             $record .= $recorded{$part_id};
                   8382:         }
                   8383:     }
                   8384:     return ($counter,$record);
                   8385: }
                   8386: 
                   8387: sub letter_to_digits { 
                   8388:     my %lettdig = (
                   8389:                     A => 1,
                   8390:                     B => 2,
                   8391:                     C => 3,
                   8392:                     D => 4,
                   8393:                     E => 5,
                   8394:                     F => 6,
                   8395:                     G => 7,
                   8396:                     H => 8,
                   8397:                     I => 9,
                   8398:                     J => 0,
                   8399:                   );
                   8400:     return %lettdig;
                   8401: }
                   8402: 
1.423     albertel 8403: 
1.75      albertel 8404: #-------- end of section for handling grading scantron forms -------
                   8405: #
                   8406: #-------------------------------------------------------------------
                   8407: 
1.72      ng       8408: #-------------------------- Menu interface -------------------------
                   8409: #
                   8410: #--- Show a Grading Menu button - Calls the next routine ---
                   8411: sub show_grading_menu_form {
1.324     albertel 8412:     my ($symb)=@_;
1.125     ng       8413:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 8414: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 8415: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       8416: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
1.478     albertel 8417: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
1.72      ng       8418: 	'</form>'."\n";
                   8419:     return $result;
                   8420: }
                   8421: 
1.77      ng       8422: # -- Retrieve choices for grading form
                   8423: sub savedState {
                   8424:     my %savedState = ();
1.257     albertel 8425:     if ($env{'form.saveState'}) {
                   8426: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       8427: 	    my ($key,$value) = split(/=/,$_,2);
                   8428: 	    $savedState{$key} = $value;
                   8429: 	}
                   8430:     }
                   8431:     return \%savedState;
                   8432: }
1.76      ng       8433: 
1.443     banghart 8434: sub grading_menu {
                   8435:     my ($request) = @_;
                   8436:     my ($symb)=&get_symb($request);
                   8437:     if (!$symb) {return '';}
                   8438:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   8439:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   8440: 
1.444     banghart 8441:     $request->print($table);
1.443     banghart 8442:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   8443:                   'handgrade'=>$hdgrade,
                   8444:                   'probTitle'=>$probTitle,
                   8445:                   'command'=>'submit_options',
                   8446:                   'saveState'=>"",
                   8447:                   'gradingMenu'=>1,
                   8448:                   'showgrading'=>"yes");
1.574.2.1  raeburn  8449:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8450:     my @menu = ({ url => $url,
                   8451:                      name => &mt('Manual Grading/View Submissions'),
                   8452:                      short_description =>
                   8453:     &mt('Start the process of hand grading submissions.'),
                   8454:                  });
1.443     banghart 8455:     $fields{'command'} = 'csvform';
1.574.2.1  raeburn  8456:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8457:     push(@menu, { url => $url,
                   8458:                    name => &mt('Upload Scores'),
                   8459:                    short_description =>
                   8460:             &mt('Specify a file containing the class scores for current resource.')});
1.443     banghart 8461:     $fields{'command'} = 'processclicker';
1.574.2.1  raeburn  8462:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8463:     push(@menu, { url => $url,
                   8464:                    name => &mt('Process Clicker'),
                   8465:                    short_description =>
                   8466:             &mt('Specify a file containing the clicker information for this resource.')});
1.443     banghart 8467:     $fields{'command'} = 'scantron_selectphase';
1.574.2.1  raeburn  8468:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8469:     push(@menu, { url => $url,
1.574.2.5  raeburn  8470:                    name => &mt('Grade/Manage/Review Bubblesheets'),
1.574.2.1  raeburn  8471:                    short_description =>
1.574.2.11  raeburn  8472:             &mt('Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.')});
1.574.2.1  raeburn  8473:     $fields{'command'} = 'verify';
                   8474:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8475:     push(@menu, { url => "",
1.574.2.10  raeburn  8476:                    name => &mt('Verify Receipt No.'),
1.574.2.1  raeburn  8477:                    short_description =>
                   8478:             &mt('')});
1.443     banghart 8479:     # Create the menu
                   8480:     my $Str;
1.444     banghart 8481:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 8482:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8483:     $Str .= '<input type="hidden" name="command" value="" />'.
                   8484:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   8485: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
1.476     albertel 8486: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.445     banghart 8487: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   8488: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8489: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
1.574.2.1  raeburn  8490:     foreach my $menudata (@menu) {
1.574.2.10  raeburn  8491:         if ($menudata->{'name'} ne &mt('Verify Receipt No.')) {
1.574.2.1  raeburn  8492:             $Str .='    <h3><a '.
                   8493:                 $menudata->{'jscript'}.
                   8494:                 ' href="'.
                   8495:                 $menudata->{'url'}.'" >'.
                   8496:                 $menudata->{'name'}."</a></h3>\n";
                   8497:         } else {
1.574.2.10  raeburn  8498:             $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
1.574.2.1  raeburn  8499:                 $menudata->{'jscript'}.
                   8500:                 ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
                   8501:                 ' /> '.
                   8502:                 &Apache::lonnet::recprefix($env{'request.course.id'}).
                   8503:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
                   8504:         }
                   8505:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
                   8506:             "\n";
                   8507:     }
1.444     banghart 8508:     $Str .="</form>\n";
1.539     riegler  8509:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
1.443     banghart 8510:     $request->print(<<GRADINGMENUJS);
                   8511: <script type="text/javascript" language="javascript">
                   8512:     function checkChoice(formname,val,cmdx) {
                   8513: 	if (val <= 2) {
                   8514: 	    var cmd = radioSelection(formname.radioChoice);
                   8515: 	    var cmdsave = cmd;
                   8516: 	} else {
                   8517: 	    cmd = cmdx;
                   8518: 	    cmdsave = 'submission';
                   8519: 	}
                   8520: 	formname.command.value = cmd;
                   8521: 	if (val < 5) formname.submit();
                   8522: 	if (val == 5) {
1.458     banghart 8523: 	    if (!checkReceiptNo(formname,'notOK')) { 
                   8524: 	        return false;
                   8525: 	    } else {
                   8526: 	        formname.submit();
                   8527: 	    }
1.445     banghart 8528: 	}
                   8529:     }
1.443     banghart 8530: 
                   8531:     function checkReceiptNo(formname,nospace) {
                   8532: 	var receiptNo = formname.receipt.value;
                   8533: 	var checkOpt = false;
                   8534: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   8535: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   8536: 	if (checkOpt) {
1.539     riegler  8537: 	    alert("$receiptalert");
1.443     banghart 8538: 	    formname.receipt.value = "";
                   8539: 	    formname.receipt.focus();
                   8540: 	    return false;
                   8541: 	}
                   8542: 	return true;
                   8543:     }
                   8544: </script>
                   8545: GRADINGMENUJS
                   8546:     &commonJSfunctions($request);
                   8547:     return $Str;    
                   8548: }
                   8549: 
                   8550: 
                   8551: #--- Displays the submissions first page -------
                   8552: sub submit_options {
1.72      ng       8553:     my ($request) = @_;
1.324     albertel 8554:     my ($symb)=&get_symb($request);
1.72      ng       8555:     if (!$symb) {return '';}
1.76      ng       8556:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       8557: 
1.539     riegler  8558:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
1.72      ng       8559:     $request->print(<<GRADINGMENUJS);
                   8560: <script type="text/javascript" language="javascript">
1.116     ng       8561:     function checkChoice(formname,val,cmdx) {
                   8562: 	if (val <= 2) {
                   8563: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       8564: 	    var cmdsave = cmd;
1.116     ng       8565: 	} else {
                   8566: 	    cmd = cmdx;
1.118     ng       8567: 	    cmdsave = 'submission';
1.116     ng       8568: 	}
                   8569: 	formname.command.value = cmd;
1.118     ng       8570: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 8571: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       8572: 	if (val < 5) formname.submit();
                   8573: 	if (val == 5) {
1.72      ng       8574: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   8575: 	    formname.submit();
                   8576: 	}
1.238     albertel 8577: 	if (val < 7) formname.submit();
1.72      ng       8578:     }
                   8579: 
                   8580:     function checkReceiptNo(formname,nospace) {
                   8581: 	var receiptNo = formname.receipt.value;
                   8582: 	var checkOpt = false;
                   8583: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   8584: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   8585: 	if (checkOpt) {
1.539     riegler  8586: 	    alert("$receiptalert");
1.72      ng       8587: 	    formname.receipt.value = "";
                   8588: 	    formname.receipt.focus();
                   8589: 	    return false;
                   8590: 	}
                   8591: 	return true;
                   8592:     }
                   8593: </script>
                   8594: GRADINGMENUJS
1.118     ng       8595:     &commonJSfunctions($request);
1.324     albertel 8596:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.473     albertel 8597:     my $result;
1.76      ng       8598:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       8599:     my $savedState = &savedState();
1.118     ng       8600:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       8601:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       8602:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       8603:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       8604: 
1.533     bisitz   8605:     # Preselect sections
                   8606:     my $selsec="";
                   8607:     if (ref($sections)) {
                   8608:         foreach my $section (sort(@$sections)) {
                   8609:             $selsec.='<option value="'.$section.'" '.
                   8610:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
                   8611:         }
                   8612:     }
                   8613: 
1.72      ng       8614:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 8615: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       8616: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   8617: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       8618: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       8619: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       8620: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       8621: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8622: 
1.472     albertel 8623:     $result.='
1.574.2.1  raeburn  8624:     <div class="LC_grade_select_mode">
                   8625:       <div class="LC_grade_select_mode_current">
                   8626:         <h2>
                   8627:           '.&mt('Grade Current Resource').'
                   8628:         </h2>
                   8629:         <div class="LC_grade_select_mode_body">
                   8630:           <div class="LC_grades_resource_info">
                   8631:            '.$table.'
                   8632:           </div>
                   8633:           <div class="LC_grade_select_mode_selector">
                   8634:              <div class="LC_grade_select_mode_selector_header">
                   8635:                 '.&mt('Sections').'
                   8636:              </div>
                   8637:              <div class="LC_grade_select_mode_selector_body">
                   8638:                <select name="section" multiple="multiple" size="5">'."\n";
                   8639:     if (ref($sections)) {
                   8640:         foreach my $section (sort(@$sections)) {
                   8641:             $result.='<option value="'.$section.'" '.
                   8642:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
                   8643:         }
                   8644:     }
1.401     albertel 8645:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.472     albertel 8646:     $result.='
1.574.2.1  raeburn  8647:              </div>
                   8648:           </div>
                   8649:           <div class="LC_grade_select_mode_selector">
                   8650:              <div class="LC_grade_select_mode_selector_header">
                   8651:                 '.&mt('Groups').'
                   8652:              </div>
                   8653:              <div class="LC_grade_select_mode_selector_body">
                   8654:                 '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8655:              </div>
                   8656:           </div>
                   8657:           <div class="LC_grade_select_mode_selector">
                   8658:              <div class="LC_grade_select_mode_selector_header">
                   8659:                 '.&mt('Access Status').'
                   8660:              </div>
                   8661:              <div class="LC_grade_select_mode_selector_body">
                   8662:                 '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
                   8663:              </div>
                   8664:           </div>
                   8665:           <div class="LC_grade_select_mode_selector">
                   8666:              <div class="LC_grade_select_mode_selector_header">
                   8667:                 '.&mt('Submission Status').'
                   8668:              </div>
                   8669:              <div class="LC_grade_select_mode_selector_body">
                   8670:                <select name="submitonly" size="5">
                   8671:                  <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
                   8672:                  <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
                   8673:                  <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
                   8674:                  <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
1.473     albertel 8675:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
1.574.2.1  raeburn  8676:                </select>
                   8677:              </div>
                   8678:           </div>
                   8679:           <div class="LC_grade_select_mode_type_body">
                   8680:             <div class="LC_grade_select_mode_type">
1.473     albertel 8681:               <label>
                   8682:                 <input type="radio" name="radioChoice" value="submission" '.
                   8683:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
                   8684:              &mt('Select individual students to grade and view submissions.').'
1.574.2.1  raeburn  8685:               </label>
1.473     albertel 8686:             </div>
1.574.2.1  raeburn  8687:             <div class="LC_grade_select_mode_type">
                   8688:               <label>
1.473     albertel 8689:                 <input type="radio" name="radioChoice" value="viewgrades" '.
                   8690:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
                   8691:                     &mt('Grade all selected students in a grading table.').'
                   8692:               </label>
                   8693:             </div>
1.574.2.1  raeburn  8694:             <div class="LC_grade_select_mode_type">
                   8695:               <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
1.473     albertel 8696:             </div>
1.472     albertel 8697:           </div>
1.574.2.1  raeburn  8698:         </div>
                   8699:       </div>
                   8700:       <div class="LC_grade_select_mode_page">
1.473     albertel 8701:         <h2>
                   8702:          '.&mt('Grade Complete Folder for One Student').'
                   8703:         </h2>
1.574.2.1  raeburn  8704:         <div class="LC_grades_select_mode_body">
                   8705:           <div class="LC_grade_select_mode_type_body">
                   8706:             <div class="LC_grade_select_mode_type">
1.473     albertel 8707:               <label>
                   8708:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
1.574.2.1  raeburn  8709:           ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
1.473     albertel 8710:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
                   8711:               </label>
                   8712:             </div>
1.574.2.1  raeburn  8713:             <div class="LC_grade_select_mode_type">
                   8714:               <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
1.473     albertel 8715:             </div>
1.574.2.1  raeburn  8716:           </div>
1.472     albertel 8717:         </div>
1.574.2.1  raeburn  8718:       </div>
                   8719:     </div>
1.472     albertel 8720:   </form>';
1.499     albertel 8721:     $result .= &show_grading_menu_form($symb);
1.44      ng       8722:     return $result;
1.2       albertel 8723: }
                   8724: 
1.285     albertel 8725: sub reset_perm {
                   8726:     undef(%perm);
                   8727: }
                   8728: 
                   8729: sub init_perm {
                   8730:     &reset_perm();
1.300     albertel 8731:     foreach my $test_perm ('vgr','mgr','opa') {
                   8732: 
                   8733: 	my $scope = $env{'request.course.id'};
                   8734: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8735: 
                   8736: 	    $scope .= '/'.$env{'request.course.sec'};
                   8737: 	    if ( $perm{$test_perm}=
                   8738: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8739: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8740: 	    } else {
                   8741: 		delete($perm{$test_perm});
                   8742: 	    }
1.285     albertel 8743: 	}
                   8744:     }
                   8745: }
                   8746: 
1.400     www      8747: sub gather_clicker_ids {
1.408     albertel 8748:     my %clicker_ids;
1.400     www      8749: 
                   8750:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8751: 
                   8752:     # Set up a couple variables.
1.407     albertel 8753:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8754:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8755:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8756: 
1.407     albertel 8757:     foreach my $student (keys(%$classlist)) {
1.438     www      8758:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8759:         my $username = $classlist->{$student}->[$username_idx];
                   8760:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8761:         my $clickers =
1.408     albertel 8762: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8763:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8764:             $id=~s/^[\#0]+//;
1.421     www      8765:             $id=~s/[\-\:]//g;
1.407     albertel 8766:             if (exists($clicker_ids{$id})) {
1.408     albertel 8767: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8768:             } else {
1.408     albertel 8769: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8770:             }
                   8771:         }
                   8772:     }
1.407     albertel 8773:     return %clicker_ids;
1.400     www      8774: }
                   8775: 
1.402     www      8776: sub gather_adv_clicker_ids {
1.408     albertel 8777:     my %clicker_ids;
1.402     www      8778:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8779:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8780:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8781:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8782:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8783:             my ($puname,$pudom)=split(/\:/,$person);
                   8784:             my $clickers =
1.408     albertel 8785: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8786:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8787: 		$id=~s/^[\#0]+//;
1.421     www      8788:                 $id=~s/[\-\:]//g;
1.408     albertel 8789: 		if (exists($clicker_ids{$id})) {
                   8790: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8791: 		} else {
                   8792: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8793: 		}
1.405     www      8794:             }
1.402     www      8795:         }
                   8796:     }
1.407     albertel 8797:     return %clicker_ids;
1.402     www      8798: }
                   8799: 
1.413     www      8800: sub clicker_grading_parameters {
                   8801:     return ('gradingmechanism' => 'scalar',
                   8802:             'upfiletype' => 'scalar',
                   8803:             'specificid' => 'scalar',
                   8804:             'pcorrect' => 'scalar',
                   8805:             'pincorrect' => 'scalar');
                   8806: }
                   8807: 
1.400     www      8808: sub process_clicker {
                   8809:     my ($r)=@_;
                   8810:     my ($symb)=&get_symb($r);
                   8811:     if (!$symb) {return '';}
                   8812:     my $result=&checkforfile_js();
                   8813:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   8814:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   8815:     $result.=$table;
                   8816:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   8817:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 8818:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
                   8819:         '</b></td></tr>'."\n";
1.400     www      8820:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      8821: # Attempt to restore parameters from last session, set defaults if not present
                   8822:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8823:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8824:                                                  \%Saveable_Parameters);
                   8825:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8826:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8827:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8828:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8829: 
                   8830:     my %checked;
1.521     www      8831:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8832:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   8833:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      8834:        }
                   8835:     }
                   8836: 
1.400     www      8837:     my $upload=&mt("Upload File");
                   8838:     my $type=&mt("Type");
1.402     www      8839:     my $attendance=&mt("Award points just for participation");
                   8840:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8841:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8842:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8843:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8844:     my $pcorrect=&mt("Percentage points for correct solution");
                   8845:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8846:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      8847: 						   ('iclicker' => 'i>clicker',
                   8848:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 8849:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      8850:     $result.=<<ENDUPFORM;
1.402     www      8851: <script type="text/javascript">
                   8852: function sanitycheck() {
                   8853: // Accept only integer percentages
                   8854:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   8855:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   8856: // Find out grading choice
                   8857:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8858:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   8859:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   8860:       }
                   8861:    }
                   8862: // By default, new choice equals user selection
                   8863:    newgradingchoice=gradingchoice;
                   8864: // Not good to give more points for false answers than correct ones
                   8865:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   8866:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   8867:    }
                   8868: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   8869:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   8870:       document.forms.gradesupload.pcorrect.value=100;
                   8871:       document.forms.gradesupload.pincorrect.value=100;
                   8872:    }
                   8873: // If the values are different, cannot be attendance only
                   8874:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   8875:        (gradingchoice=='attendance')) {
                   8876:        newgradingchoice='personnel';
                   8877:    }
                   8878: // Change grading choice to new one
                   8879:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8880:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   8881:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   8882:       } else {
                   8883:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   8884:       }
                   8885:    }
                   8886: // Remember the old state
                   8887:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   8888: }
                   8889: </script>
1.400     www      8890: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   8891: <input type="hidden" name="symb" value="$symb" />
                   8892: <input type="hidden" name="command" value="processclickerfile" />
                   8893: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   8894: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   8895: <input type="file" name="upfile" size="50" />
                   8896: <br /><label>$type: $selectform</label>
1.569     bisitz   8897: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
                   8898: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
                   8899: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onClick="sanitycheck()" />$specific </label>
1.414     www      8900: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.569     bisitz   8901: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onClick="sanitycheck()" />$given </label>
1.521     www      8902: <br />&nbsp;&nbsp;&nbsp;
                   8903: <input type="text" name="givenanswer" size="50" />
1.413     www      8904: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
                   8905: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
                   8906: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
1.400     www      8907: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
                   8908: </form>
                   8909: ENDUPFORM
                   8910:     $result.='</td></tr></table>'."\n".
                   8911:              '</td></tr></table><br /><br />'."\n";
                   8912:     $result.=&show_grading_menu_form($symb);
                   8913:     return $result;
                   8914: }
                   8915: 
                   8916: sub process_clicker_file {
                   8917:     my ($r)=@_;
                   8918:     my ($symb)=&get_symb($r);
                   8919:     if (!$symb) {return '';}
1.413     www      8920: 
                   8921:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8922:     &Apache::loncommon::store_course_settings('grades_clicker',
                   8923:                                               \%Saveable_Parameters);
                   8924: 
1.400     www      8925:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      8926:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 8927: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   8928: 	return $result.&show_grading_menu_form($symb);
1.404     www      8929:     }
1.522     www      8930:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      8931:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
                   8932:         return $result.&show_grading_menu_form($symb);
                   8933:     }
1.522     www      8934:     my $foundgiven=0;
1.521     www      8935:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8936:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   8937:         $env{'form.givenanswer'}=~s/\s*$//gs;
                   8938:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
                   8939:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      8940:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   8941:         $foundgiven=$#answers+1;
1.521     www      8942:     }
1.407     albertel 8943:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 8944:     my %correct_ids;
1.404     www      8945:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 8946: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      8947:     }
                   8948:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      8949: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   8950: 	   $correct_id=~tr/a-z/A-Z/;
                   8951: 	   $correct_id=~s/\s//gs;
                   8952: 	   $correct_id=~s/^[\#0]+//;
1.421     www      8953:            $correct_id=~s/[\-\:]//g;
1.414     www      8954:            if ($correct_id) {
                   8955: 	      $correct_ids{$correct_id}='specified';
                   8956:            }
                   8957:         }
1.400     www      8958:     }
1.404     www      8959:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 8960: 	$result.=&mt('Score based on attendance only');
1.521     www      8961:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      8962:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      8963:     } else {
1.408     albertel 8964: 	my $number=0;
1.411     www      8965: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 8966: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      8967: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 8968: 	    if ($correct_ids{$id} eq 'specified') {
                   8969: 		$result.=&mt('specified');
                   8970: 	    } else {
                   8971: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   8972: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   8973: 	    }
                   8974: 	    $number++;
                   8975: 	}
1.411     www      8976:         $result.="</p>\n";
1.408     albertel 8977: 	if ($number==0) {
                   8978: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   8979: 	    return $result.&show_grading_menu_form($symb);
                   8980: 	}
1.404     www      8981:     }
1.405     www      8982:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 8983:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   8984: 		     '<span class="LC_error">',
                   8985: 		     '</span>',
                   8986: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      8987:         return $result.&show_grading_menu_form($symb);
                   8988:     }
1.410     www      8989: 
                   8990: # Were able to get all the info needed, now analyze the file
                   8991: 
1.411     www      8992:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 8993:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      8994:     my $heading=&mt('Scanning clicker file');
                   8995:     $result.=(<<ENDHEADER);
                   8996: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8997: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8998: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8999: <form method="post" action="/adm/grades" name="clickeranalysis">
                   9000: <input type="hidden" name="symb" value="$symb" />
                   9001: <input type="hidden" name="command" value="assignclickergrades" />
                   9002: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   9003: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      9004: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   9005: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   9006: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      9007: ENDHEADER
1.522     www      9008:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9009:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   9010:     } 
1.408     albertel 9011:     my %responses;
                   9012:     my @questiontitles;
1.405     www      9013:     my $errormsg='';
                   9014:     my $number=0;
                   9015:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 9016: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      9017:     }
1.419     www      9018:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   9019:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   9020:     }
1.411     www      9021:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   9022:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   9023:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   9024:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   9025:              '<br />';
1.522     www      9026:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   9027:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
                   9028:        return $result.&show_grading_menu_form($symb);
                   9029:     } 
1.414     www      9030: # Remember Question Titles
                   9031: # FIXME: Possibly need delimiter other than ":"
                   9032:     for (my $i=0;$i<$number;$i++) {
                   9033:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   9034:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   9035:     }
1.411     www      9036:     my $correct_count=0;
                   9037:     my $student_count=0;
                   9038:     my $unknown_count=0;
1.414     www      9039: # Match answers with usernames
                   9040: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 9041:     foreach my $id (keys(%responses)) {
1.410     www      9042:        if ($correct_ids{$id}) {
1.414     www      9043:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      9044:           $correct_count++;
1.410     www      9045:        } elsif ($clicker_ids{$id}) {
1.437     www      9046:           if ($clicker_ids{$id}=~/\,/) {
                   9047: # More than one user with the same clicker!
                   9048:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   9049:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9050:                            "<select name='multi".$id."'>";
                   9051:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   9052:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   9053:              }
                   9054:              $result.='</select>';
                   9055:              $unknown_count++;
                   9056:           } else {
                   9057: # Good: found one and only one user with the right clicker
                   9058:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   9059:              $student_count++;
                   9060:           }
1.410     www      9061:        } else {
1.411     www      9062:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   9063:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9064:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   9065:                    "\n".&mt("Domain").": ".
                   9066:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   9067:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   9068:           $unknown_count++;
1.410     www      9069:        }
1.405     www      9070:     }
1.412     www      9071:     $result.='<hr />'.
                   9072:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      9073:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      9074:        if ($correct_count==0) {
                   9075:           $errormsg.="Found no correct answers answers for grading!";
                   9076:        } elsif ($correct_count>1) {
1.414     www      9077:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      9078:        }
                   9079:     }
1.428     www      9080:     if ($number<1) {
                   9081:        $errormsg.="Found no questions.";
                   9082:     }
1.412     www      9083:     if ($errormsg) {
                   9084:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   9085:     } else {
                   9086:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   9087:     }
                   9088:     $result.='</form></td></tr></table>'."\n".
1.410     www      9089:              '</td></tr></table><br /><br />'."\n";
1.404     www      9090:     return $result.&show_grading_menu_form($symb);
1.400     www      9091: }
                   9092: 
1.405     www      9093: sub iclicker_eval {
1.406     www      9094:     my ($questiontitles,$responses)=@_;
1.405     www      9095:     my $number=0;
                   9096:     my $errormsg='';
                   9097:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      9098:         my %components=&Apache::loncommon::record_sep($line);
                   9099:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 9100: 	if ($entries[0] eq 'Question') {
                   9101: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   9102: 		$$questiontitles[$number]=$entries[$i];
                   9103: 		$number++;
                   9104: 	    }
                   9105: 	}
                   9106: 	if ($entries[0]=~/^\#/) {
                   9107: 	    my $id=$entries[0];
                   9108: 	    my @idresponses;
                   9109: 	    $id=~s/^[\#0]+//;
                   9110: 	    for (my $i=0;$i<$number;$i++) {
                   9111: 		my $idx=3+$i*6;
                   9112: 		push(@idresponses,$entries[$idx]);
                   9113: 	    }
                   9114: 	    $$responses{$id}=join(',',@idresponses);
                   9115: 	}
1.405     www      9116:     }
                   9117:     return ($errormsg,$number);
                   9118: }
                   9119: 
1.419     www      9120: sub interwrite_eval {
                   9121:     my ($questiontitles,$responses)=@_;
                   9122:     my $number=0;
                   9123:     my $errormsg='';
1.420     www      9124:     my $skipline=1;
                   9125:     my $questionnumber=0;
                   9126:     my %idresponses=();
1.419     www      9127:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9128:         my %components=&Apache::loncommon::record_sep($line);
                   9129:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      9130:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   9131:         if ($entries[1] eq 'Response') { $skipline=1; }
                   9132:         next if $skipline;
                   9133:         if ($entries[0]!=$questionnumber) {
                   9134:            $questionnumber=$entries[0];
                   9135:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9136:            $number++;
1.419     www      9137:         }
1.420     www      9138:         my $id=$entries[4];
                   9139:         $id=~s/^[\#0]+//;
1.421     www      9140:         $id=~s/^v\d*\://i;
                   9141:         $id=~s/[\-\:]//g;
1.420     www      9142:         $idresponses{$id}[$number]=$entries[6];
                   9143:     }
1.524     raeburn  9144:     foreach my $id (keys(%idresponses)) {
1.420     www      9145:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9146:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9147:     }
                   9148:     return ($errormsg,$number);
                   9149: }
                   9150: 
1.414     www      9151: sub assign_clicker_grades {
                   9152:     my ($r)=@_;
                   9153:     my ($symb)=&get_symb($r);
                   9154:     if (!$symb) {return '';}
1.416     www      9155: # See which part we are saving to
1.574.2.7  raeburn  9156:     my $res_error;
                   9157:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   9158:     if ($res_error) {
                   9159:         return &navmap_errormsg();
                   9160:     }
1.416     www      9161: # FIXME: This should probably look for the first handgradeable part
                   9162:     my $part=$$partlist[0];
                   9163: # Start screen output
1.414     www      9164:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      9165: 
1.414     www      9166:     my $heading=&mt('Assigning grades based on clicker file');
                   9167:     $result.=(<<ENDHEADER);
                   9168: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   9169: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   9170: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   9171: ENDHEADER
                   9172: # Get correct result
                   9173: # FIXME: Possibly need delimiter other than ":"
                   9174:     my @correct=();
1.415     www      9175:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   9176:     my $number=$env{'form.number'};
                   9177:     if ($gradingmechanism ne 'attendance') {
1.414     www      9178:        foreach my $key (keys(%env)) {
                   9179:           if ($key=~/^form\.correct\:/) {
                   9180:              my @input=split(/\,/,$env{$key});
                   9181:              for (my $i=0;$i<=$#input;$i++) {
                   9182:                  if (($correct[$i]) && ($input[$i]) &&
                   9183:                      ($correct[$i] ne $input[$i])) {
                   9184:                     $result.='<br /><span class="LC_warning">'.
                   9185:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   9186:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   9187:                  } elsif ($input[$i]) {
                   9188:                     $correct[$i]=$input[$i];
                   9189:                  }
                   9190:              }
                   9191:           }
                   9192:        }
1.415     www      9193:        for (my $i=0;$i<$number;$i++) {
1.414     www      9194:           if (!$correct[$i]) {
                   9195:              $result.='<br /><span class="LC_error">'.
                   9196:                       &mt('No correct result given for question "[_1]"!',
                   9197:                           $env{'form.question:'.$i}).'</span>';
                   9198:           }
                   9199:        }
                   9200:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   9201:     }
                   9202: # Start grading
1.415     www      9203:     my $pcorrect=$env{'form.pcorrect'};
                   9204:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      9205:     my $storecount=0;
1.415     www      9206:     foreach my $key (keys(%env)) {
1.420     www      9207:        my $user='';
1.415     www      9208:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      9209:           $user=$1;
                   9210:        }
                   9211:        if ($key=~/^form\.unknown\:(.*)$/) {
                   9212:           my $id=$1;
                   9213:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   9214:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      9215:           } elsif ($env{'form.multi'.$id}) {
                   9216:              $user=$env{'form.multi'.$id};
1.420     www      9217:           }
                   9218:        }
                   9219:        if ($user) { 
1.415     www      9220:           my @answer=split(/\,/,$env{$key});
                   9221:           my $sum=0;
1.522     www      9222:           my $realnumber=$number;
1.415     www      9223:           for (my $i=0;$i<$number;$i++) {
1.574.2.6  raeburn  9224:              if  ($correct[$i] eq '-') {
                   9225:                 $realnumber--;
                   9226:              } elsif ($answer[$i]) {
1.415     www      9227:                 if ($gradingmechanism eq 'attendance') {
                   9228:                    $sum+=$pcorrect;
1.574.2.6  raeburn  9229:                 } elsif ($correct[$i] eq '*') {
1.522     www      9230:                    $sum+=$pcorrect;
1.415     www      9231:                 } else {
                   9232:                    if ($answer[$i] eq $correct[$i]) {
                   9233:                       $sum+=$pcorrect;
                   9234:                    } else {
                   9235:                       $sum+=$pincorrect;
                   9236:                    }
                   9237:                 }
                   9238:              }
                   9239:           }
1.522     www      9240:           my $ave=$sum/(100*$realnumber);
1.416     www      9241: # Store
                   9242:           my ($username,$domain)=split(/\:/,$user);
                   9243:           my %grades=();
                   9244:           $grades{"resource.$part.solved"}='correct_by_override';
                   9245:           $grades{"resource.$part.awarded"}=$ave;
                   9246:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   9247:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   9248:                                                  $env{'request.course.id'},
                   9249:                                                  $domain,$username);
                   9250:           if ($returncode ne 'ok') {
                   9251:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   9252:           } else {
                   9253:              $storecount++;
                   9254:           }
1.415     www      9255:        }
                   9256:     }
                   9257: # We are done
1.549     hauer    9258:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.416     www      9259:              '</td></tr></table>'."\n".
1.414     www      9260:              '</td></tr></table><br /><br />'."\n";
                   9261:     return $result.&show_grading_menu_form($symb);
                   9262: }
                   9263: 
1.574.2.7  raeburn  9264: sub navmap_errormsg {
                   9265:     return '<div class="LC_error">'.
                   9266:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
                   9267:            &mt('It is recommended that you [_1]re-initialize the course[_2] and then return to this grading page..','<a href="/adm/roles?selectrole=1&newrole='.$env{'request.role'}.'">','</a>').
                   9268:            '</div>';
                   9269: }
                   9270: 
1.1       albertel 9271: sub handler {
1.41      ng       9272:     my $request=$_[0];
1.434     albertel 9273:     &reset_caches();
1.257     albertel 9274:     if ($env{'browser.mathml'}) {
1.141     www      9275: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       9276:     } else {
1.141     www      9277: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       9278:     }
                   9279:     $request->send_http_header;
1.44      ng       9280:     return '' if $request->header_only;
1.41      ng       9281:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 9282:     my $symb=&get_symb($request,1);
1.160     albertel 9283:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   9284:     my $command=$commands[0];
1.447     foxr     9285: 
1.160     albertel 9286:     if ($#commands > 0) {
                   9287: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   9288:     }
1.447     foxr     9289: 
1.513     foxr     9290:     $ssi_error = 0;
1.535     raeburn  9291:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
                   9292:     $request->print(&Apache::loncommon::start_page('Grading',undef,
                   9293:                                           {'bread_crumbs' => $brcrum}));
1.324     albertel 9294:     if ($symb eq '' && $command eq '') {
1.257     albertel 9295: 	if ($env{'user.adv'}) {
                   9296: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   9297: 		($env{'form.codethree'})) {
                   9298: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   9299: 		    $env{'form.codethree'};
1.41      ng       9300: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   9301: 		    &Apache::lonnet::checkin($token);
                   9302: 		if ($tsymb) {
1.137     albertel 9303: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       9304: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.513     foxr     9305: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
1.99      albertel 9306: 					  ('grade_username' => $tuname,
                   9307: 					   'grade_domain' => $tudom,
                   9308: 					   'grade_courseid' => $tcrsid,
                   9309: 					   'grade_symb' => $tsymb)));
1.41      ng       9310: 		    } else {
1.45      ng       9311: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 9312: 		    }
1.41      ng       9313: 		} else {
1.45      ng       9314: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       9315: 		}
1.14      www      9316: 	    } else {
1.41      ng       9317: 		$request->print(&Apache::lonxml::tokeninputfield());
                   9318: 	    }
                   9319: 	}
                   9320:     } else {
1.285     albertel 9321: 	&init_perm();
1.104     albertel 9322: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 9323: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 9324: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       9325: 	    &pickStudentPage($request);
1.103     albertel 9326: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       9327: 	    &displayPage($request);
1.104     albertel 9328: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       9329: 	    &updateGradeByPage($request);
1.104     albertel 9330: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       9331: 	    &processGroup($request);
1.104     albertel 9332: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 9333: 	    $request->print(&grading_menu($request));
                   9334: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   9335: 	    $request->print(&submit_options($request));
1.104     albertel 9336: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       9337: 	    $request->print(&viewgrades($request));
1.104     albertel 9338: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       9339: 	    $request->print(&processHandGrade($request));
1.106     albertel 9340: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       9341: 	    $request->print(&editgrades($request));
1.106     albertel 9342: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       9343: 	    $request->print(&verifyreceipt($request));
1.400     www      9344:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   9345:             $request->print(&process_clicker($request));
                   9346:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   9347:             $request->print(&process_clicker_file($request));
1.414     www      9348:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   9349:             $request->print(&assign_clicker_grades($request));
1.106     albertel 9350: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       9351: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 9352: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       9353: 	    $request->print(&csvupload($request));
1.106     albertel 9354: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       9355: 	    $request->print(&csvuploadmap($request));
1.246     albertel 9356: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9357: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 9358: 		$request->print(&csvuploadoptions($request));
1.41      ng       9359: 	    } else {
1.257     albertel 9360: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9361: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9362: 		} else {
1.257     albertel 9363: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9364: 		}
                   9365: 		$request->print(&csvuploadmap($request));
                   9366: 	    }
1.246     albertel 9367: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   9368: 	    $request->print(&csvuploadassign($request));
1.106     albertel 9369: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 9370: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 9371:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   9372:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 9373: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   9374: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 9375: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 9376: 	    $request->print(&scantron_process_students($request));
1.157     albertel 9377:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9378:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9379: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 9380:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 9381:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9382:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9383: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 9384:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 9385:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9386: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 9387:  	    $request->print(&scantron_download_scantron_data($request));
1.523     raeburn  9388:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
                   9389:             $request->print(&checkscantron_results($request));     
1.106     albertel 9390: 	} elsif ($command) {
1.562     bisitz   9391: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 9392: 	}
1.2       albertel 9393:     }
1.513     foxr     9394:     if ($ssi_error) {
                   9395: 	&ssi_print_error($request);
                   9396:     }
1.353     albertel 9397:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9398:     &reset_caches();
1.44      ng       9399:     return '';
                   9400: }
                   9401: 
1.1       albertel 9402: 1;
                   9403: 
1.13      albertel 9404: __END__;
1.531     jms      9405: 
                   9406: 
                   9407: =head1 NAME
                   9408: 
                   9409: Apache::grades
                   9410: 
                   9411: =head1 SYNOPSIS
                   9412: 
                   9413: Handles the viewing of grades.
                   9414: 
                   9415: This is part of the LearningOnline Network with CAPA project
                   9416: described at http://www.lon-capa.org.
                   9417: 
                   9418: =head1 OVERVIEW
                   9419: 
                   9420: Do an ssi with retries:
                   9421: While I'd love to factor out this with the vesrion in lonprintout,
                   9422: that would either require a data coupling between modules, which I refuse to perpetuate (there's quite enough of that already), or would require the invention of another infrastructure
                   9423: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   9424: 
                   9425: At least the logic that drives this has been pulled out into loncommon.
                   9426: 
                   9427: 
                   9428: 
                   9429: ssi_with_retries - Does the server side include of a resource.
                   9430:                      if the ssi call returns an error we'll retry it up to
                   9431:                      the number of times requested by the caller.
                   9432:                      If we still have a proble, no text is appended to the
                   9433:                      output and we set some global variables.
                   9434:                      to indicate to the caller an SSI error occurred.  
                   9435:                      All of this is supposed to deal with the issues described
                   9436:                      in LonCAPA BZ 5631 see:
                   9437:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   9438:                      by informing the user that this happened.
                   9439: 
                   9440: Parameters:
                   9441:   resource   - The resource to include.  This is passed directly, without
                   9442:                interpretation to lonnet::ssi.
                   9443:   form       - The form hash parameters that guide the interpretation of the resource
                   9444:                
                   9445:   retries    - Number of retries allowed before giving up completely.
                   9446: Returns:
                   9447:   On success, returns the rendered resource identified by the resource parameter.
                   9448: Side Effects:
                   9449:   The following global variables can be set:
                   9450:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   9451:                               It is up to the caller to initialize this to false
                   9452:                               if desired.
                   9453:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   9454:                               of the resource that could not be rendered by the ssi
                   9455:                               call.
                   9456:    ssi_error_message   - The error string fetched from the ssi response
                   9457:                               in the event of an error.
                   9458: 
                   9459: 
                   9460: =head1 HANDLER SUBROUTINE
                   9461: 
                   9462: ssi_with_retries()
                   9463: 
                   9464: =head1 SUBROUTINES
                   9465: 
                   9466: =over
                   9467: 
                   9468: =item scantron_get_correction() : 
                   9469: 
                   9470:    Builds the interface screen to interact with the operator to fix a
                   9471:    specific error condition in a specific scanline
                   9472: 
                   9473:  Arguments:
                   9474:     $r           - Apache request object
                   9475:     $i           - number of the current scanline
                   9476:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   9477:     $scan_config - hash ref as returned from &get_scantron_config()
                   9478:     $line        - full contents of the current scanline
                   9479:     $error       - error condition, valid values are
                   9480:                    'incorrectCODE', 'duplicateCODE',
                   9481:                    'doublebubble', 'missingbubble',
                   9482:                    'duplicateID', 'incorrectID'
                   9483:     $arg         - extra information needed
                   9484:        For errors:
                   9485:          - duplicateID   - paper number that this studentID was seen before on
                   9486:          - duplicateCODE - array ref of the paper numbers this CODE was
                   9487:                            seen on before
                   9488:          - incorrectCODE - current incorrect CODE 
                   9489:          - doublebubble  - array ref of the bubble lines that have double
                   9490:                            bubble errors
                   9491:          - missingbubble - array ref of the bubble lines that have missing
                   9492:                            bubble errors
                   9493: 
                   9494: =item  scantron_get_maxbubble() : 
                   9495: 
1.574.2.7  raeburn  9496:    Arguments:
                   9497:        $nav_error  - Reference to scalar which is a flag to indicate a
                   9498:                       failure to retrieve a navmap object.
                   9499:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   9500:        calling routine should trap the error condition and display the warning
                   9501:        found in &navmap_errormsg().
                   9502: 
1.531     jms      9503:    Returns the maximum number of bubble lines that are expected to
                   9504:    occur. Does this by walking the selected sequence rendering the
                   9505:    resource and then checking &Apache::lonxml::get_problem_counter()
                   9506:    for what the current value of the problem counter is.
                   9507: 
                   9508:    Caches the results to $env{'form.scantron_maxbubble'},
                   9509:    $env{'form.scantron.bubble_lines.n'}, 
                   9510:    $env{'form.scantron.first_bubble_line.n'} and
                   9511:    $env{"form.scantron.sub_bubblelines.n"}
                   9512:    which are the total number of bubble, lines, the number of bubble
                   9513:    lines for response n and number of the first bubble line for response n,
                   9514:    and a comma separated list of numbers of bubble lines for sub-questions
                   9515:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   9516: 
                   9517: 
                   9518: =item  scantron_validate_missingbubbles() : 
                   9519: 
                   9520:    Validates all scanlines in the selected file to not have any
                   9521:     answers that don't have bubbles that have not been verified
                   9522:     to be bubble free.
                   9523: 
                   9524: =item  scantron_process_students() : 
                   9525: 
                   9526:    Routine that does the actual grading of the bubble sheet information.
                   9527: 
                   9528:    The parsed scanline hash is added to %env 
                   9529: 
                   9530:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   9531:    foreach resource , with the form data of
                   9532: 
                   9533: 	'submitted'     =>'scantron' 
                   9534: 	'grade_target'  =>'grade',
                   9535: 	'grade_username'=> username of student
                   9536: 	'grade_domain'  => domain of student
                   9537: 	'grade_courseid'=> of course
                   9538: 	'grade_symb'    => symb of resource to grade
                   9539: 
                   9540:     This triggers a grading pass. The problem grading code takes care
                   9541:     of converting the bubbled letter information (now in %env) into a
                   9542:     valid submission.
                   9543: 
                   9544: =item  scantron_upload_scantron_data() :
                   9545: 
                   9546:     Creates the screen for adding a new bubble sheet data file to a course.
                   9547: 
                   9548: =item  scantron_upload_scantron_data_save() : 
                   9549: 
                   9550:    Adds a provided bubble information data file to the course if user
                   9551:    has the correct privileges to do so. 
                   9552: 
                   9553: =item  valid_file() :
                   9554: 
                   9555:    Validates that the requested bubble data file exists in the course.
                   9556: 
                   9557: =item  scantron_download_scantron_data() : 
                   9558: 
                   9559:    Shows a list of the three internal files (original, corrected,
                   9560:    skipped) for a specific bubble sheet data file that exists in the
                   9561:    course.
                   9562: 
                   9563: =item  scantron_validate_ID() : 
                   9564: 
                   9565:    Validates all scanlines in the selected file to not have any
1.556     weissno  9566:    invalid or underspecified student/employee IDs
1.531     jms      9567: 
1.574.2.7  raeburn  9568: =item navmap_errormsg() :
                   9569: 
                   9570:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   9571:    Should be called whenever the request to instantiate a navmap object fails.  
                   9572: 
1.531     jms      9573: =back
                   9574: 
                   9575: =cut

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